diff --git "a/4490.jsonl" "b/4490.jsonl" new file mode 100644--- /dev/null +++ "b/4490.jsonl" @@ -0,0 +1,759 @@ +{"seq_id":"345798412","text":"# -*- coding: utf-8 -*-\nfrom plone.behavior.interfaces import IBehavior\nfrom zope.interface import implementer\n\n\n@implementer(IBehavior)\nclass BehaviorRegistration(object):\n\n def __init__(self, title, description, interface, marker, factory):\n self.title = title\n self.description = description\n self.interface = interface\n self.marker = marker\n self.factory = factory\n\n def __repr__(self):\n return \"\".format(\n self.interface.__identifier__\n )\n","sub_path":"buildout-cache--/eggs/plone.behavior-1.0.3-py2.7.egg/plone/behavior/registration.py","file_name":"registration.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"576132899","text":"from django.shortcuts import render,redirect, get_object_or_404\nfrom .models import Habitacion , Clases , Opinion , Promocion , Reserva , Contacto\nfrom .forms import HabitacionForm , ClaseForm , OpinionForm , PromocionForm , ReservaForm, ContactoForm\nfrom django.http import HttpResponse\nfrom django.contrib.auth.decorators import login_required\n\n#Habitacion\n@login_required(login_url='/accout/login')\ndef index(request):\n return render(request, 'Concesionaria/index.html', {})\n\n@login_required(login_url='/accout/login')\ndef base(request):\n return render(request, 'Concesionaria/base.html', {})\n\n##########################################################################################################\n\n@login_required(login_url='/accout/login')\ndef habitacion_ver(request):\n\thabitaciones = Habitacion.objects.all()\n\treturn render(request, 'Concesionaria/ver_habitacion.html', {'habitaciones':habitaciones})\n\n@login_required(login_url='/accout/login')\ndef habitacion_nuevo(request):\n\tif request.method == \"POST\":\n\t\tform = HabitacionForm(request.POST) \n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.save()\n\t\t\treturn redirect('habitacion_ver')\n\telse:\n\t\tagregar_form = HabitacionForm()\n\t\treturn render(request, 'Concesionaria/agregar_habitacion.html', {'agregar_form': agregar_form})\n\n@login_required(login_url='/accout/login')\ndef habitacion_borrar(request , pk):\n\thabitacion = get_object_or_404(Habitacion, pk = pk)\n\thabitacion.delete()\n\treturn redirect('habitacion_ver')\n\n@login_required(login_url='/accout/login')\ndef habitacion_modificar(request , pk):\n\thabitacion = get_object_or_404(Habitacion, pk = pk)\n\tif request.method == 'POST':\n\t\tform = HabitacionForm(request.POST, instance=habitacion)\n\t\tif form.is_valid():\n\t\t\tform = form.save(commit=False)\n\t\t\tform.save()\n\t\t\treturn redirect('habitacion_ver')\n\telse:\n\t\tform = HabitacionForm(instance=habitacion)\n\treturn render(request,'Concesionaria/modificar_habitacion.html', {'form':form})\n\n\n##########################################################################################################\ndef contacto(request):\n\tif request.method == \"POST\":\n\t\tform = ContactoForm(request.POST) \n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.save()\n\t\t\treturn redirect('exito')\n\telse:\n\t\tagregar_form = OpinionForm()\n\t\treturn render(request, 'usuarios/contacto.html', {'agregar_form': agregar_form})\ndef restaurante(request):\n return render(request, 'usuarios/restaurante.html', {}) \n\n@login_required(login_url='/accout/login')\ndef opiniones_usuarios(request):\n\tif request.method == \"POST\":\n\t\tform = OpinionForm(request.POST) \n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.save()\n\t\t\treturn redirect('opiniones_usuarios')\n\telse:\n\t\tagregar_form = OpinionForm()\n\t\treturn render(request, 'usuarios/opiniones_usuarios.html', {'agregar_form': agregar_form})\n\n\ndef index_usuario(request):\n return render(request, 'usuarios/index_usuario.html', {})\n \n\ndef habitaciones_usuarios(request):\n\thabitaciones_usuarios = Habitacion.objects.all()\n\treturn render(request, 'usuarios/habitaciones_usuarios.html', {'habitaciones_usuarios':habitaciones_usuarios})\n\n@login_required(login_url='/accout/login')\ndef exito(request):\n return render(request, 'usuarios/exito.html', {})\n# @login_required(login_url='/accout/login')\n# def reservas_usuarios(request):\n# \tif request.method == \"POST\":\n# \t\tprint (request.POST)\n# \t\t# si pertenece al nuevo modelo -- lo manda a otra vista donde diga que esta ocupada la habiacion\n# \t\tform = ReservaForm(request.POST)\n# \t\tif form.is_valid():\n# \t\t\treserva = form.save(commit=False)\n\n# \t\t\thabitacion = Habitacion.objects.get(clase__tipos=reserva.clase)\n# \t\t\trequest.POST['fecha_inicio']\n# \t\t\treserva.habitacion = habitacion[1]\n\t\t\t\n# \t\t\treserva.save()\n# \t\t\t# guardar en el otro modelo , fecha, reser\n# \t\t\treturn redirect('exito')\n# \telse:\n# \t\tagregar_form = ReservaForm()\n# \t\treturn render(request, 'usuarios/reservas_usuarios.html', {'agregar_form': agregar_form})\n\n@login_required(login_url='/accout/login')\ndef reservas_usuarios(request):\n\tif request.method == \"POST\":\n\t\tprint (request.POST)\n\t\tform = ReservaForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.save()\n\t\t\treturn redirect('exito')\n\telse:\n\t\tagregar_form = ReservaForm()\n\t\treturn render(request, 'usuarios/reservas_usuarios.html', {'agregar_form': agregar_form})\n\n\n\n##########################################################################################################\n\n@login_required(login_url='/accout/login')\ndef clase_ver(request):\n\tclases = Clases.objects.all()\n\treturn render(request, 'Concesionaria/ver_clase.html', {'clases':clases})\n\n@login_required(login_url='/accout/login')\ndef clase_nuevo(request):\n\tif request.method == \"POST\":\n\t\tform = ClaseForm(request.POST) \n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.save()\n\t\t\treturn redirect('clase_ver')\n\telse:\n\t\tagregar_form = ClaseForm()\n\t\treturn render(request, 'Concesionaria/agregar_clase.html', {'agregar_form': agregar_form})\n\n@login_required(login_url='/accout/login')\ndef clase_borrar(request , pk):\n\tclase = get_object_or_404(Clases, pk = pk)\n\tclase.delete()\n\treturn redirect('clase_ver')\n\n@login_required(login_url='/accout/login')\ndef clase_modificar(request , pk):\n\tclase = get_object_or_404(Clases, pk = pk)\n\tif request.method == 'POST':\n\t\tform = ClaseForm(request.POST, instance=clase)\n\t\tif form.is_valid():\n\t\t\tform = form.save(commit=False)\n\t\t\tform.save()\n\t\t\treturn redirect('clase_ver')\n\telse:\n\t\tform = ClaseForm(instance=clase)\n\treturn render(request,'Concesionaria/modificar_clase.html', {'form':form})\n\n##########################################################################################################\n\n@login_required(login_url='/accout/login')\ndef opinion_ver(request):\n\topiniones = Opinion.objects.all()\n\treturn render(request, 'Concesionaria/ver_opinion.html', {'opiniones':opiniones})\n\n@login_required(login_url='/accout/login')\ndef opinion_nuevo(request):\n\tif request.method == \"POST\":\n\t\tform = OpinionForm(request.POST) \n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.save()\n\t\t\treturn redirect('opinion_ver')\n\telse:\n\t\tagregar_form = OpinionForm()\n\t\treturn render(request, 'Concesionaria/agregar_opinion.html', {'agregar_form': agregar_form})\n\n@login_required(login_url='/accout/login')\ndef opinion_borrar(request , pk):\n\topinion = get_object_or_404(Opinion, pk = pk)\n\topinion.delete()\n\treturn redirect('opinion_ver')\n\n@login_required(login_url='/accout/login')\ndef opinion_modificar(request , pk):\n\topinion = get_object_or_404(Opinion, pk = pk)\n\tif request.method == 'POST':\n\t\tform = OpinionForm(request.POST, instance=opinion)\n\t\tif form.is_valid():\n\t\t\tform = form.save(commit=False)\n\t\t\tform.save()\n\t\t\treturn redirect('opinion_ver')\n\telse:\n\t\tform = OpinionForm(instance=opinion)\n\treturn render(request,'Concesionaria/modificar_opinion.html', {'form':form})\n\n# ##########################################################################################################\n\n@login_required(login_url='/accout/login')\ndef contacto_ver(request):\n\tcontacto = Contacto.objects.all()\n\treturn render(request, 'Concesionaria/ver_contacto.html', {'contacto':contacto})\n\n@login_required(login_url='/accout/login')\ndef contacto_nuevo(request):\n\tif request.method == \"POST\":\n\t\tform = ContactoForm(request.POST) \n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.save()\n\t\t\treturn redirect('contacto_ver')\n\telse:\n\t\tagregar_form = ContactoForm()\n\t\treturn render(request, 'Concesionaria/agregar_contacto.html', {'agregar_form': agregar_form})\n\n@login_required(login_url='/accout/login')\ndef contacto_borrar(request , pk):\n\tcontacto = get_object_or_404(Contacto, pk = pk)\n\tcontacto.delete()\n\treturn redirect('contacto_ver')\n\n@login_required(login_url='/accout/login')\ndef contacto_modificar(request , pk):\n\tcontacto = get_object_or_404(Contacto, pk = pk)\n\tif request.method == 'POST':\n\t\tform = ContactoForm(request.POST, instance=contacto)\n\t\tif form.is_valid():\n\t\t\tform = form.save(commit=False)\n\t\t\tform.save()\n\t\t\treturn redirect('contacto_ver')\n\telse:\n\t\tform = ContactoForm(instance=contacto)\n\treturn render(request,'Concesionaria/modificar_contacto.html', {'form':form})\n\n##########################################################################################################\n\n@login_required(login_url='/accout/login')\ndef promocion_ver(request):\n\tpromociones = Promocion.objects.all()\n\treturn render(request, 'Concesionaria/ver_promocion.html', {'promociones':promociones})\n\n@login_required(login_url='/accout/login')\ndef promocion_nuevo(request):\n\tif request.method == \"POST\":\n\t\tform = PromocionForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tpost.save()\n\t\t\treturn redirect('promocion_ver')\n\telse:\n\t\tagregar_form = PromocionForm()\n\t\treturn render(request, 'Concesionaria/agregar_promocion.html', {'agregar_form': agregar_form})\n\n@login_required(login_url='/accout/login')\ndef promocion_borrar(request , pk):\n\tpromocion = get_object_or_404(Promocion, pk = pk)\n\tpromocion.delete()\n\treturn redirect('promocion_ver')\n\n@login_required(login_url='/accout/login')\ndef promocion_modificar(request , pk):\n\tpromocion = get_object_or_404(Promocion, pk = pk)\n\tif request.method == 'POST':\n\t\tform = PromocionForm(request.POST, instance=promocion)\n\t\tif form.is_valid():\n\t\t\tform = form.save(commit=False)\n\t\t\tform.save()\n\t\t\treturn redirect('promocion_ver')\n\telse:\n\t\tform = PromocionForm(instance=promocion)\n\treturn render(request,'Concesionaria/modificar_promocion.html', {'form':form})\n\n##########################################################################################################\n\n@login_required(login_url='/accout/login')\ndef reserva_ver(request):\n\treservas = Reserva.objects.all()\n\treturn render(request, 'Concesionaria/ver_reserva.html', {'reservas':reservas})\n\n@login_required(login_url='/accout/login')\ndef reserva_nuevo(request):\n\tif request.method == \"POST\":\n\t\tprint (request.POST)\n\t\tform = ReservaForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\trequest.POST['fecha_inicio']\n\t\t\tpost.save()\n\t\t\treturn redirect('reserva_ver')\n\telse:\n\t\tagregar_form = ReservaForm()\n\t\treturn render(request, 'Concesionaria/agregar_reserva.html', {'agregar_form': agregar_form})\n\n@login_required(login_url='/accout/login')\ndef reserva_borrar(request , pk):\n\treserva = get_object_or_404(Reserva, pk = pk)\n\treserva.delete()\n\treturn redirect('reserva_ver')\n\n@login_required(login_url='/accout/login')\ndef reserva_modificar(request , pk):\n\treserva = get_object_or_404(Reserva, pk = pk)\n\tif request.method == 'POST':\n\t\tform = ReservaForm(request.POST, instance=reserva)\n\t\tif form.is_valid():\n\t\t\tform = form.save(commit=False)\n\t\t\trequest.POST['fecha_inicio']\n\t\t\tform.save()\n\t\t\treturn redirect('reserva_ver')\n\telse:\n\t\tmodificar_form = ReservaForm(instance=reserva)\n\treturn render(request,'Concesionaria/modificar_reserva.html', {'modificar_form':modificar_form})\n\n","sub_path":"Programacion del Hotel/Concesionaria/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"511563551","text":"\"\"\" Activity manager configuration\n - config-file schema\n - prometheus endpoint information\n\"\"\"\nfrom typing import Dict\n\nimport trafaret as T\nfrom aiohttp.web import Application\nfrom models_library.basic_types import PortInt, VersionTag\nfrom pydantic import BaseSettings\nfrom servicelib.aiohttp.application_keys import APP_CONFIG_KEY\n\nCONFIG_SECTION_NAME = \"activity\"\n\n\nschema = T.Dict(\n {\n T.Key(\"enabled\", default=True, optional=True): T.Bool(),\n T.Key(\n \"prometheus_host\", default=\"http://prometheus\", optional=False\n ): T.String(),\n T.Key(\"prometheus_port\", default=9090, optional=False): T.ToInt(),\n T.Key(\"prometheus_api_version\", default=\"v1\", optional=False): T.String(),\n }\n)\n\n\nclass ActivitySettings(BaseSettings):\n enabled: bool = True\n prometheus_host: str = \"prometheus\"\n prometheus_port: PortInt = 9090\n prometheus_api_version: VersionTag = \"v1\"\n\n class Config:\n case_sensitive = False\n env_prefix = \"WEBSERVER_\"\n\n\ndef assert_valid_config(app: Application) -> Dict:\n cfg = app[APP_CONFIG_KEY][CONFIG_SECTION_NAME]\n _settings = ActivitySettings(**cfg)\n return cfg\n","sub_path":"services/web/server/src/simcore_service_webserver/activity/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"597697064","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport jinja2\nfrom jinja2 import Template\nimport glob\nfrom pathlib import Path\nimport argparse\n\nlyx_jinja_env = jinja2.Environment(\n block_start_string='\\BLOCK{',\n block_end_string='}',\n variable_start_string='\\VAR{',\n variable_end_string='}',\n comment_start_string='\\#{',\n comment_end_string='}',\n line_statement_prefix='%%',\n line_comment_prefix='%#',\n trim_blocks=True,\n autoescape=False,\n loader=jinja2.FileSystemLoader(os.path.abspath('.'))\n)\n\n\ndef get_pdfs(dir):\n part=os.path.split(dir)[1]\n pdfs=sorted(glob.glob(os.path.join(dir,\"*.pdf\")))\n pdfs_list=list(map(lambda path:{\"pdf_path\":path.replace('\\\\', '/'),\n \"pdf_name\":os.path.splitext(os.path.split(path)[1])[0]},pdfs))\n part_dict={\"part_name\":part,\"pdfs\":pdfs_list}\n return part_dict\n\nif __name__==\"__main__\":\n parser = argparse.ArgumentParser(description=\"生成LyX代码\")\n parser.add_argument('--dirname', help=\"文件夹名称\",default=\"example\")\n parser.add_argument('--title', help=\"报告名称\",default=\"Example Reports\")\n parser.add_argument('--author', help=\"报告作者\",default=\"Example Author\")\n args = parser.parse_args()\n dirs=glob.glob(args.dirname+\"/*\")\n dirs=sorted(list(filter(lambda path:os.path.isdir(path),dirs)))\n dirs=list(map(lambda path:os.path.abspath(path),dirs))\n parts=list(map(get_pdfs,dirs))\n template=lyx_jinja_env.get_template('template.lyx')\n output=template.render(title=args.title,author=args.author,parts=parts)\n if not os.path.isdir(\"./build\"):\n os.makedirs(\"./build\")\n with open(os.path.join(\"./build/\",args.dirname+\".lyx\"),\"w\",encoding=\"utf-8\") as fout:\n fout.write(output)\n","sub_path":"merge_lyx.py","file_name":"merge_lyx.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"438686097","text":"class Solution:\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n \n \n #eg, [7, 1, 5, 3, 6, 4]\n #dont have to do brute force and double loop\n #can do this in single loop \n #why?\n #because if we know 1 is the lowest\n #then no need to check for 3, ie, no need to check 6 - 3, 6 - 4\n #because , obviously, can't get any greater than 6 - 1 \n \n #it just that, everytime we encouter a new minimum, we need to recompute the profit\n #also , everytime the current number is higher than the minimum, we need to compute to profit (to see whether the current profit is greater than the max profit)\n \n minimumprice = 99999\n maxprofit = 0 \n for currprice in prices:\n if currprice > minimumprice:\n if currprice - minimumprice > maxprofit:\n maxprofit = currprice - minimumprice\n elif currprice < minimumprice:\n minimumprice = currprice\n \n return maxprofit\n \n #eg, [7, 1, 5, 3, 6, 4] #solution would be 1 and 6 \n #start with \n #minprice = 99999, profit = 0 \n \n # check 7\n # 7 < 99999 (the current min)\n # so minprice = 7, profit = 0 \n \n #check 1\n # 1 < 7 (the current min)\n # minprice = 1, profit = 0\n \n #check 5\n # 5 > 1 (indiate there is profit )and \n # 5 - 1 > profit 0\n # minprice = 1, profit = 4\n \n #check 3\n #3 > 1 (indicate there is profit)\n # 3 - 1 not greater than profit 4 \n #don't change \n #minprice = 1, profit = 4\n \n #check 6\n # 6 > 1(there is profit)\n # also 6 - 1 > the current profit of 4\n #minprice = 1, profit = 5\n \n \n","sub_path":"121. Best Time to Buy and Sell Stock.py","file_name":"121. Best Time to Buy and Sell Stock.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"650601208","text":"import xlwt\nimport json\n\ndef txtToxls(fileName):\n\tfiletxt = open(fileName, 'r')\n\ttxtContent = json.load(filetxt)\n\n\txlsObject = xlwt.Workbook()\n\tsheet = xlsObject.add_sheet('student')\n\n\tfor i in range(len(txtContent)):\n\t\tsheet.write(i, 0, i+1)\n\t\tcontent = txtContent[str(i+1)]\n\t\tfor j in range(len(content)):\n\t\t\tsheet.write(i, j+1, content[j])\n\n\txlsObject.save('student.xls')\n\nif __name__ == '__main__':\n\ttxtToxls('data.txt')\n","sub_path":"0014/0014.py","file_name":"0014.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"220027763","text":"\"\"\" อยู่ไหน \"\"\"\n\ndef main():\n \"\"\" main function \"\"\"\n input1 = int(input())\n if 0 >= input1 or input1 > 31:\n print(\"404 NOT FOUND\")\n elif 14 >= input1 >= 12:\n print(\"Yep! %d UNITE4\" % (input1))\n else:\n print(\"Try again!\")\n\nmain()\n","sub_path":"onsite/7 Condition/17.py","file_name":"17.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"252446758","text":"import math\nfrom scipy.stats import multivariate_normal\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn import datasets\n\npi = 22 / 7\n\ncolors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'w']\n\nclass ExpectationMaximization:\n\n def __init__(self, data, num_clusters, show_plots):\n self._data = data\n self._which_cluster = []\n self._show_plots = show_plots\n self._num_features = np.shape(self._data)[0]\n self._num_data_points = np.shape(self._data)[1]\n self._num_clusters = int(num_clusters)\n self._prob = self.normalize(np.random.rand(self._num_clusters, self._num_data_points))\n self._old_prob = self._prob\n\n def do_em(self):\n\n muc = 10 * np.random.rand(self._num_features, self._num_clusters)\n\n pic = np.random.rand(self._num_clusters, 1)\n\n sum_pic = np.sum(pic)\n for i in range(len(pic)):\n pic[i] = pic[i]/sum_pic\n\n sigma = np.random.rand(self._num_clusters, self._num_features, self._num_features)\n\n for i in range(self._num_clusters):\n sigma[i, :, :] = 100*datasets.make_spd_matrix(self._num_features)\n\n while True:\n\n self._prob = self.expectation(muc, sigma, pic)\n pic, muc, sigma = self.maximization()\n self._old_prob = self._prob\n\n for b in range(self._num_clusters):\n for a in range(self._num_data_points):\n if np.abs(self._prob[b, a] - self._old_prob[b, a]) < 0.000001:\n flag = 1\n\n if flag == 1:\n print(\"Values converged\")\n print(self._prob)\n break\n\n if self.prob_fitness_calc() > 50:\n if self._show_plots:\n self.hard_cluster()\n self.show_em_plots()\n break\n\n #Returns a normalized probability value\n def normalize(self, matrix):\n for column in range(self._num_data_points):\n norm = sum(matrix[:, column])\n matrix[:, column] /= norm\n return matrix\n\n #Calculates the liklihood for a given probability matrix and responsibility matix\n def log_liklihood(self):\n log_liklihood = np.log(np.sum((self._prob * self._pic), axis=0))\n log_liklihood = np.sum(log_liklihood)\n print(log_liklihood)\n\n def maximization(self):\n pic = np.sum(self._prob, axis=1) / self._num_data_points #updating the value of resposibility matrix\n sum_pic = np.sum(pic)\n for i in range(len(pic)):\n pic[i] = pic[i]/sum_pic\n\n mu = np.zeros([self._num_features, self._num_clusters])\n sig = np.zeros([self._num_clusters, self._num_features, self._num_features])\n\n for i in range(self._num_clusters):\n for j in range(self._num_data_points):\n mu[:, i] += self._prob[i, j] * self._data[:, j] #updating the value of mean\n\n muc = mu / self._num_data_points\n\n for i in range(self._num_clusters):\n for j in range(self._num_data_points):\n A = np.matrix(self._data[:, j] - muc[:, i])\n val = (A.T * self._prob[i, j] * A) #updating the value of Sigma\n sig[i, :, :] += val\n\n sigma = sig / self._num_data_points\n\n for mat in sigma:\n if np.linalg.det(mat) == 0:\n pass\n\n return pic, muc, sigma\n\n def expectation(self, mu, sigma, pic):\n for i in range(self._num_clusters):\n for j in range(self._num_data_points):\n var = multivariate_normal(mu[:, i], sigma[i, :, :]) #Calculating the probability matrix from the updated value\n self._prob[i, j] = var.pdf(self._data[:, j])\n\n for i in range(self._num_clusters):\n self._prob[i, :] *= pic[i]\n\n self._prob = self.normalize(self._prob) #Normalizing the updated the probability matrix\n print(self._prob)\n return self._prob\n\n def hard_cluster(self):\n self._which_cluster = np.amax(self._prob, axis=1)\n\n def show_em_plots(self):\n list_of_points = [[] for _ in range(self._num_clusters)]\n\n for points, which in zip(self._data.T, self._which_cluster):\n list_of_points[which].append(points)\n\n fig = plt.figure()\n\n ax = fig.add_subplot(111)\n\n cluster_index = 0\n\n for cluster in list_of_points:\n name = 'Cluster ' + cluster_index\n ax.scatter(x=cluster[0], y=cluster[1], c=colors[cluster_index], label=name)\n cluster_index += 1\n\n plt.legend()\n plt.show()\n\n def prob_fitness_calc(self):\n prob_diff = np.abs(self._old_prob - self._prob)\n\n return prob_diff.mean()\n","sub_path":"EM_Question1/EM.py","file_name":"EM.py","file_ext":"py","file_size_in_byte":4858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"643333830","text":"import numpy\nimport tensorflow as tf\n\nnumpy.set_printoptions(suppress=True)\n\nCLASSES = 32\nSAMPLES = 4096\nBATCH_SIZE = 1\nSEQUENCE_SIZE = 16\n\ndef main():\n\n numpy.random.seed(0)\n sequence = numpy.eye(CLASSES)[\n numpy.random.choice(CLASSES, SAMPLES + 1)]\n print(sequence)\n\n inputs = sequence[:-1]\n inputs = numpy.reshape(inputs, (SAMPLES, CLASSES))\n print(inputs)\n outputs = sequence[1:]\n outputs = numpy.reshape(outputs, (SAMPLES, CLASSES))\n print(outputs)\n\n tf.set_random_seed(0)\n\n phInputs = tf.placeholder(tf.float32, (None, SEQUENCE_SIZE, CLASSES),\n name=\"phInputs\")\n phOutputs = tf.placeholder(tf.float32, (None, SEQUENCE_SIZE, CLASSES),\n name=\"phOutputs\")\n\n lstmCell = tf.nn.rnn_cell.LSTMCell(num_units=1024)\n zeroState = lstmCell.zero_state(BATCH_SIZE, tf.float32)\n initialState = tf.nn.rnn_cell.LSTMStateTuple(\n c=tf.placeholder(tf.float32, (None, lstmCell.state_size.c)),\n h=tf.placeholder(tf.float32, (None, lstmCell.state_size.h)))\n lstmOutputs, finalState = tf.nn.dynamic_rnn(\n cell=lstmCell,\n inputs=phInputs,\n sequence_length=[SEQUENCE_SIZE],\n initial_state=initialState)\n logits = list()\n denseLayer = tf.layers.Dense(CLASSES, tf.sigmoid)\n for i in range(SEQUENCE_SIZE):\n tempLogits = denseLayer(lstmOutputs[:, i, :])\n logits.append(tempLogits)\n logits = tf.reshape(logits, tf.shape(phOutputs))\n lossOp = tf.losses.softmax_cross_entropy(phOutputs, logits)\n optimizer = tf.train.AdamOptimizer()\n trainOp = optimizer.minimize(lossOp)\n logitsSoftmax = tf.nn.softmax(logits)\n mseOp = tf.losses.mean_squared_error(phOutputs, logits)\n diffOp = tf.losses.absolute_difference(phOutputs, logits)\n\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n config.graph_options.optimizer_options.global_jit_level = \\\n tf.OptimizerOptions.ON_1\n with tf.Session(config=config) as session:\n session.run(tf.global_variables_initializer())\n epoch = 0\n try:\n while True:\n epoch += 1\n state = session.run(zeroState)\n mseMax = None\n lossMax = None\n diffMax = None\n for batch in batches(inputs, outputs):\n _, state, loss, mse, logitsValues = session.run(\n [trainOp, finalState, lossOp, mseOp, logits],\n {\n phInputs: batch.inputs,\n phOutputs: batch.outputs,\n initialState.c: state.c,\n initialState.h: state.h\n })\n lossMax = max(loss, lossMax)\n mseMax = max(mse, mseMax)\n diff = numpy.max(\n numpy.abs(logitsValues - batch.outputs))\n diffMax = max(diff, diffMax)\n print(epoch, lossMax, mseMax, diffMax)\n if diffMax < 0.2:\n break\n except KeyboardInterrupt:\n pass\n state = session.run(zeroState)\n for batch in batches(inputs, outputs):\n logitsValues, state = session.run([logits, finalState],\n {\n phInputs: batch.inputs,\n phOutputs: batch.outputs,\n initialState.c: state.c,\n initialState.h: state.h\n })\n print(batch.outputs - logitsValues)\n print(epoch)\n\nclass Batch:\n pass\n\ndef batches(inputs, outputs):\n batchNum = SAMPLES / SEQUENCE_SIZE\n for i in range(batchNum):\n firstSample = i * SEQUENCE_SIZE\n lastSample = firstSample + SEQUENCE_SIZE\n batch = Batch()\n batch.inputs = numpy.reshape(\n inputs[firstSample:lastSample,:],\n (BATCH_SIZE, SEQUENCE_SIZE, CLASSES))\n batch.outputs = numpy.reshape(\n outputs[firstSample:lastSample,:],\n (BATCH_SIZE, SEQUENCE_SIZE, CLASSES))\n yield batch\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"rnn_tf.py","file_name":"rnn_tf.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"223433690","text":"from math import exp\nfrom numpy import *\nfrom matplotlib import pyplot as plt\nfrom matplotlib.font_manager import FontProperties\n\n\ndef loadDataSet(filename):\n dataMat = []\n labelMat = []\n f = open(filename)\n for line in f.readlines():\n lineArr = line.strip().split()\n dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])\n labelMat.append(int(lineArr[2]))\n return dataMat, labelMat\n\n\ndef sigmoid(inX):\n return 1.0 / (1 + exp(-inX))\n\n\ndef gradAscent(dataMatIn, classLabels):\n '''\n 梯度上升算法\n :param dataMatIn: 数据集,一个二维Numpy数组,每列分别代表每个不同的特征,每行则代表每个训练样本。\n :param classLabels: 类别标签,是一个(1,100)的行向量。\n :return: 返回回归系数\n '''\n dataMatrix = mat(dataMatIn)\n labelMat = mat(classLabels).transpose()\n # m->样本数,n->特征数 在本例中m=100,n=3\n m, n = shape(dataMatrix)\n # alpha代表向目标移动的步长\n alpha = 0.001\n # 迭代次数\n maxCycles = 500\n # 权重值初始全为1\n weights = ones((n, 1))\n for k in range(maxCycles):\n h = sigmoid(dataMatrix * weights) # shape = (100,1)\n error = labelMat - h # shape = (100,1)\n weights += alpha * dataMatrix.transpose() * error\n return weights\n\n\ndef stocGradAscent(dataMatIn, classLabels, numIter=150):\n '''\n 随机梯度上升法\n :param dataMatIn: 数据集,一个二维Numpy数组,每列分别代表每个不同的特征,每行则代表每个训练样本。\n :param classLabels: 类别标签,是一个(1,100)的行向量。\n :param numIter: 外循环次数\n :return: 返回回归系数\n '''\n dataMatrix = mat(dataMatIn)\n m, n = shape(dataMatrix)\n weights = ones((n, 1))\n # 随机梯度, 循环150,观察是否收敛\n for j in range(numIter):\n # [0, 1, 2 .. m-1]\n dataIndex = list(range(m))\n for i in range(m):\n # i和j的不断增大,导致alpha的值不断减少,但是不为0\n alpha = 4 / (1.0 + j + i) + 0.0001 # alpha 会随着迭代不断减小,但永远不会减小到0,因为后边还有一个常数项0.0001\n # 随机产生一个 0~len(dataIndex)之间的一个值\n # random.uniform(x, y) 方法将随机生成下一个实数,它在[x,y]范围内,x是这个范围内的最小值,y是这个范围内的最大值。\n randIndex = int(random.uniform(0, len(dataIndex)))\n choose = dataIndex[randIndex]\n # sum(dataMatrix[i]*weights)为了求 f(x)的值, f(x)=w1*x1+w2*x2+..+wn*xn\n h = sigmoid(sum(dataMatrix[choose] * weights))\n error = classLabels[choose] - h\n weights += alpha * error * dataMatrix[choose].transpose()\n del (dataIndex[randIndex])\n return weights\n\n\ndef showData(dataArr, labelMat):\n '''\n 展示数据集分布情况\n :param dataArr:\n :param labelMat:\n :return: None\n '''\n n = shape(dataArr)[0]\n xcord1 = []\n ycord1 = []\n xcord2 = []\n ycord2 = []\n for i in range(n):\n if int(labelMat[i]) == 1:\n xcord1.append(dataArr[i, 1])\n ycord1.append(dataArr[i, 2])\n else:\n xcord2.append(dataArr[i, 1])\n ycord2.append(dataArr[i, 2])\n fig = plt.figure(figsize=(8, 6))\n ax = fig.add_subplot(111)\n p1 = ax.scatter(xcord1, ycord1, s=30, c='red', marker='s')\n p2 = ax.scatter(xcord2, ycord2, s=30, c='green')\n plt.legend([p1, p2], ['Class 1', 'Class 0'], loc='lower right', scatterpoints=1)\n plt.show()\n\n\ndef plotBestFit(dataArr, labelMat, weights1, weights2):\n '''\n 将我们得到的数据可视化展示出来\n :param dataArr:样本数据的特征\n :param labelMat:样本数据的类别标签,即目标变量\n :param weights:回归系数\n :return:None\n '''\n font = FontProperties(fname=r\"c:\\windows\\fonts\\simsun.ttc\", size=14)\n n = shape(dataArr)[0]\n xcord1 = []\n ycord1 = []\n xcord2 = []\n ycord2 = []\n for i in range(n):\n if int(labelMat[i]) == 1:\n xcord1.append(dataArr[i, 1])\n ycord1.append(dataArr[i, 2])\n else:\n xcord2.append(dataArr[i, 1])\n ycord2.append(dataArr[i, 2])\n fig = plt.figure(figsize=(8, 6))\n ax1 = fig.add_subplot(121)\n ax2 = fig.add_subplot(122)\n ax1.scatter(xcord1, ycord1, s=30, c='red', marker='s')\n ax1.scatter(xcord2, ycord2, s=30, c='green')\n ax2.scatter(xcord1, ycord1, s=30, c='red', marker='s')\n ax2.scatter(xcord2, ycord2, s=30, c='green')\n x1 = arange(-3.0, 3.0, 0.1)\n y1 = (-weights1[0] - weights1[1] * x1) / weights1[2]\n x2 = arange(-3.0, 3.0, 0.1)\n y2 = (-weights2[0] - weights2[1] * x2) / weights2[2]\n ax1.plot(x1, y1)\n ax2.plot(x2, y2)\n ax1_title_text = ax1.set_title(u'梯度上升算法', FontProperties=font)\n ax2_title_text = ax2.set_title(u'随机梯度上升算法', FontProperties=font)\n plt.xlabel('X')\n plt.ylabel('Y')\n # plt.setp(ax1_title_text, size=20, weight='bold', color='black')\n # plt.setp(ax2_title_text, size=20, weight='bold', color='black')\n plt.show()\n\n\ndef testLR():\n dataMat, classLabels = loadDataSet('data/TestSet.txt')\n dataArr = array(dataMat)\n weights1 = gradAscent(dataArr, classLabels)\n weights2 = stocGradAscent(dataArr, classLabels)\n test(dataArr, classLabels)\n plotBestFit(dataArr, classLabels, weights1, weights2)\n\n\nif __name__ == '__main__':\n testLR()","sub_path":"1regression/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":5532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"189922798","text":"\"\"\"\n\n test.py\n \n Merging `test_trans.py` and `test_ind.py` \n\"\"\"\n\nimport sys\nimport json\nimport cPickle\nimport argparse\nimport numpy as np\nfrom collections import namedtuple\nfrom pprint import pprint\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--dataset', help='dataset', type=str, default='citeseer')\n parser.add_argument('--inductive', help='inductive?', action=\"store_true\")\n parser.add_argument('--config', help='path to config.json', type=str, default='config.json')\n \n parser.add_argument('--learning_rate', help='learning rate for supervised loss', type=float)\n parser.add_argument('--embedding_size', help='embedding dimensions', type=int)\n parser.add_argument('--window_size', help='window size in random walk sequences', type=int)\n parser.add_argument('--path_size', help='length of random walk sequences', type=int)\n parser.add_argument('--batch_size', help='batch size for supervised loss', type=int)\n parser.add_argument('--g_batch_size', help='batch size for graph context loss', type=int)\n parser.add_argument('--g_sample_size', help='batch size for label context loss', type=int)\n parser.add_argument('--neg_samp', help='negative sampling rate; zero means using softmax', type=int)\n parser.add_argument('--g_learning_rate', help='learning rate for unsupervised loss', type=float)\n parser.add_argument('--model_file', help='filename for saving models', type=str)\n parser.add_argument('--use_feature', help='whether use input features', type=bool)\n parser.add_argument('--update_emb', help='whether update embedding when optimizing supervised loss', type=bool)\n parser.add_argument('--layer_loss', help='whether incur loss on hidden layers', type=bool)\n return parser.parse_args()\n\ndef comp_accu(tpy, ty):\n pred = np.argmax(tpy, axis=1)\n act = np.argmax(ty, axis=1)\n return (pred == act).sum() * 1.0 / tpy.shape[0]\n\nargs = parse_args()\n\n# --\n# Config\n\nconfig = json.load(open(args.config))\n\nif args.inductive:\n from ind_model import ind_model as model\n config = config['inductive']\nelse:\n from trans_model import trans_model as model\n config = config['transductive']\n\n# Add command line arguments\nfor k,v in vars(args).iteritems():\n if v:\n print >> sys.stderr, \"overriding default %s\" % k\n config[k] = v\n\npprint(config)\n\n# --\n# IO\n\nobjs = []\nfor nm in ['x', 'y', 'tx', 'ty', 'allx', 'graph']:\n try:\n fname = \"data/{}.{}.{}\".format('ind' if args.inductive else 'trans', args.dataset, nm)\n obj = cPickle.load(open(fname))\n objs.append(obj)\n except:\n print >> sys.stderr, 'test: could not load %s' % nm\n objs.append(None)\n\nx, y, tx, ty, allx, graph = tuple(objs)\n\ntrain_data = [x, y, allx, graph] if args.inductive else [x, y, graph]\n\n# --\n# Define model\n\nmargs = namedtuple('my_args', ' '.join(config.keys()))\n\nm = model(margs(**config))\nm.add_data(*train_data)\nm.build()\n\n# Pre-training\nm.init_train(\n init_iter_label=config['init_train']['iter_label'], \n init_iter_graph=config['init_train']['iter_graph']\n)\n\n# --\n# Train model\n\niter_cnt, max_accu = 0, 0\nwhile True:\n # perform a training step\n m.step_train(\n max_iter=config['step_train']['max_iter'],\n iter_graph=config['step_train']['iter_graph'],\n iter_inst=config['step_train']['iter_inst'],\n iter_label=config['step_train']['iter_label'],\n )\n \n # predict the dev set\n tpy = m.predict(tx)\n \n # compute the accuracy on the dev set\n accu = comp_accu(tpy, ty)\n \n sys.stdout.write(\"\\r step_train\\t%d\\t%f\\t%f\" % (iter_cnt, accu, max_accu))\n sys.stdout.flush()\n \n iter_cnt += 1\n \n if accu > max_accu:\n # store the model if better result is obtained\n m.store_params()\n max_accu = max(max_accu, accu)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"439066421","text":"import math\nimport random\n\nimport discord\nfrom discord.ext import commands as c\n\nfrom module import db, item, monsters, status, str_calc\n\nMONSTER_NUM = 50\n\n\nclass Battle(c.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n async def into_battle(self, user_id, channel_id):\n error_message = \"\"\n player_level = status.get_player_level(user_id)\n in_battle = db.player.hp.get(user_id)\n if not in_battle:\n player_hp = player_level * 5 + 50 # player_max_hp\n db.player.hp.set(user_id, channel_id, player_hp)\n return player_hp, error_message\n in_battle_channel_id = in_battle[0]\n battle_channel = self.bot.get_channel(in_battle_channel_id)\n if not battle_channel: # if deleted the battle_channel\n player_hp = player_level * 5 + 50\n db.channel.not_found(in_battle_channel_id, channel_id, user_id, player_hp)\n return player_hp, error_message\n player_hp = in_battle[1]\n if in_battle_channel_id != channel_id:\n error_message = f\"<@{user_id}>は'{battle_channel.guild.name}の{battle_channel.mention}'で既に戦闘中だ。\"\n elif player_hp == 0:\n error_message = \"<@{}>はもうやられている!(戦いをやり直すには「{}reset」だ)\".format(user_id, db.prefix(self.bot.get_channel(channel_id).guild).get())\n return player_hp, error_message\n\n async def effect(self, ctx, monster):\n text = [\"<@{}>は{}の毒ダメージを受けた\".format(*i) for i in db.player.effect.poison.progress(ctx.channel.id) if i]\n if random.random() < monster[\"effect\"].get(\"poison\", [0])[0]:\n if db.player.effect.poison.add(ctx.author.id, ctx.channel.id, monster[\"effect\"].get(\"poison\", [5]*3)[2]):\n text += [f\"{ctx.author.name}は毒の効果を受けてしまった!\"]\n if text:\n return \"\\n\"+\"\\n\".join(text)\n return \"\"\n\n\ndef get_boss(ctx):\n channel_status = db.boss_status.get_st(ctx.channel.id)\n if not channel_status:\n boss_lv = 1\n monster = monsters.get(boss_lv)\n monster[1][\"HP\"] = monster[1][\"HP\"].replace(\"boss_level\", str(boss_lv))\n db.boss_status.set_st(ctx, monster[0], boss_lv, str_calc.calc(monster[1][\"HP\"]))\n channel_status = [boss_lv, str_calc.calc(monster[1][\"HP\"]), monster[0]]\n return channel_status\n\n\ndef get_player_attack(player_level, boss_level, boss_id, rand):\n boss = monsters.get(boss_level, boss_id)\n if rand < boss[1][\"Evasion rate\"]:\n player_attack = 0\n elif boss_level % MONSTER_NUM in [3, 11, 17, 32, 41]:\n plus = rand / 3 + 0.5 if rand < 0.96 else 3\n player_attack = int(player_level * plus + 10)\n elif boss_level % 5 == 0:\n plus = rand / 2 + 0.8 if rand < 0.96 else 3\n player_attack = int(player_level * plus + 10)\n else:\n plus = rand / 2 + 1 if rand < 0.96 else 3\n player_attack = int(player_level * plus + 10)\n return player_attack\n\n\ndef get_attack_message(user_id, player_attack, monster_name, rand):\n if player_attack == 0:\n return \"<@{}>の攻撃!{}にかわされてしまった...!!\".format(user_id, monster_name, )\n elif rand == 2:\n return \"<@{}>の特殊魔法!{}に`{}`のダメージを与えた!\".format(user_id, monster_name, player_attack)\n else:\n kaishin = \"会心の一撃!\" if rand > 0.96 else \"\"\n return \"<@{}>の攻撃!{}{}に`{}`のダメージを与えた!\".format(user_id, kaishin, monster_name, player_attack)\n\n\ndef get_boss_attack(ctx):\n boss_lv, _, boss_id = db.boss_status.get_st(ctx.channel.id)\n monster = monsters.get(boss_lv, boss_id)[1]\n monster[\"ATK\"] = monster[\"ATK\"].replace(\"boss_level\", str(boss_lv))\n return str_calc.calc(monster[\"ATK\"])\n\n\ndef boss_attack_process(ctx, player_hp, player_level, monster_name):\n boss_attack = get_boss_attack(ctx)\n player_hp = player_hp - boss_attack\n user_id = ctx.author.id\n if boss_attack == 0:\n return \"{0}の攻撃!<@{1}>は華麗にかわした!\\n - <@{1}>のHP:`{2}`/{3}\".format(\n monster_name, ctx.author.id, player_hp, player_level * 5 + 50)\n elif player_hp <= 0:\n db.player.hp.update(0, user_id)\n return \"{0}の攻撃!<@{1}>は`{2}`のダメージを受けた。\\n - <@{1}>のHP:`0`/{3}\\n<@{1}>はやられてしまった。。。\".format(\n monster_name, ctx.author.id, boss_attack, player_level * 5 + 50)\n else:\n db.player.hp.update(player_hp, user_id,)\n return \"{0}の攻撃!<@{1}>は`{2}`のダメージを受けた。\\n - <@{1}>のHP:`{3}`/{4}\".format(\n monster_name, ctx.author.id, boss_attack, player_hp, player_level * 5 + 50)\n\n\ndef win_process(channel_id, boss_level, monster_name):\n battle_members = [m for m in\n db.channel.all_player(channel_id)]\n level_up_comments = []\n members = \"\"\n fire_members = \"\"\n elixir_members = \"\"\n pray_members = \"\"\n boss_lv, _, boss_id = db.boss_status.get_st(channel_id)\n monster = monsters.get(boss_lv, boss_id)[1]\n monster[\"exp\"] = monster[\"exp\"].replace(\"boss_level\", str(boss_lv))\n exp = str_calc.calc(monster[\"exp\"])\n for battle_member in battle_members:\n member_id = battle_member[0]\n level_up_comments.append(status.experiment(member_id, exp))\n members += \"<@{}> \".format(member_id)\n p = min(0.02 * boss_level * boss_level / db.player.experience.get(member_id), 0.1)\n if boss_level % 10 == 0 and random.random() < p:\n elixir_members += \"<@{}> \".format(member_id)\n item.obtain_an_item(member_id, 1)\n if random.random() < p:\n fire_members += \"<@{}> \".format(member_id)\n item.obtain_an_item(member_id, 2)\n if random.random() < p * 2:\n pray_members += \"<@{}> \".format(member_id)\n item.obtain_an_item(member_id, 3)\n if fire_members:\n fire_members += \"は`ファイアボールの書`を手に入れた!\"\n if elixir_members:\n elixir_members += \"は`エリクサー`を手に入れた!\"\n if pray_members:\n pray_members += \"は`祈りの書`を��に入れた!\"\n level_up_comment = \"\\n\".join([c for c in level_up_comments if c])\n item_get = \"\\n\".join(c for c in [elixir_members, fire_members, pray_members] if c)\n msg=\"{0}を倒した!\\n\\n{1}は`{2}`の経験値を得た。\\n{3}\\n{4}\".format(monster_name, members, exp, level_up_comment, item_get)\n return (\"勝利メッセージが2000文字を超えたので表示できません\" if len(msg)>2000 else msg)\n\n\nasync def reset_battle(ctx, level_up=False):\n db.channel.end_battle(ctx.channel.id, level_up)\n boss_lv, boss_hp, boss_id = get_boss(ctx)\n from module import monsters\n monster = monsters.get(boss_lv, boss_id)\n boss_lv += level_up\n monster = monsters.get(boss_lv, None if (monster[1].get(\"canReset\") == \"True\" or level_up) else boss_id)\n from module.str_calc import calc\n monster[1][\"HP\"] = monster[1][\"HP\"].replace(\"boss_level\", str(boss_lv))\n db.boss_status.set_st(ctx, monster[0], boss_lv, calc(monster[1][\"HP\"]))\n em = discord.Embed(title=\"{}が待ち構えている...!\\nLv.{} HP:{}\".\n format(monster[1][\"name\"], boss_lv, calc(monster[1][\"HP\"])))\n em.set_image(url=f\"{db.CONFIG_ROOT}Discord/FFM/img/{monster[1].get('img','404.png')}\")\n await ctx.send(embed=em)\n","sub_path":"module/battle.py","file_name":"battle.py","file_ext":"py","file_size_in_byte":7460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"326683118","text":"#!/usr/bin/env python3\n\nimport os\nimport sqlite3\nfrom datetime import datetime\n\n\nclass Schema:\n def __init__(self, datafile):\n self.connection = sqlite3.connect(datafile, check_same_thread=False)\n self.cursor = self.connection.cursor()\n\n def __enter__(self):\n return self\n\n def __exit__(self, exception_type, exception_value, traceback):\n if self.connection:\n if self.cursor:\n self.connection.commit()\n self.cursor.close()\n self.connection.close()\n\n def create_table(self, table_name):\n try:\n sql = ''' CREATE TABLE \"{0}\"(\n pk INTEGER PRIMARY KEY AUTOINCREMENT\n );'''.format(table_name)\n self.cursor.execute(sql)\n return True\n except:\n return False\n\n def add_column(self, table_name, column_name, column_type):\n try:\n sql = ''' ALTER TABLE \"{0}\"\n ADD COLUMN \"{1}\" \"{2}\"\n ;'''.format(table_name, column_name, column_type)\n self.cursor.execute(sql)\n return True\n except:\n return False\n\n def delete_table(self, table_name):\n try:\n self.cursor.execute(\n '''DROP TABLE IF EXISTS \"{0}\";'''.format(table_name))\n return True\n except:\n return False\n\n def login(self, username, password):\n try:\n sql = ''' SELECT *\n FROM users\n WHERE username = '{0}'\n AND password = '{1}';'''.format(username, password)\n self.cursor.execute(sql)\n users = self.cursor.fetchall()\n return users\n except:\n return False\n\n def initialize_user(self, username):\n try:\n sql = ''' SELECT *\n FROM users\n WHERE username = \"{0}\";'''.format(username)\n self.cursor.execute(sql)\n user = self.cursor.fetchall()\n return user\n except:\n return False\n\n def signup(self, username, password, email):\n self.cursor.execute('''INSERT INTO users(\n username, password, balance, email\n ) VALUES (?,?,?,?);''',\n (username, password, 0, email))\n return True\n\n def query_table(self, table_name):\n try:\n sql = '''SELECT username\n FROM \"{0}\";'''.format(table_name)\n self.cursor.execute(sql)\n user_list = self.cursor.fetchall()\n return user_list\n except:\n return False\n\n def query_userinfo(self):\n try:\n sql = '''SELECT *\n FROM users;'''\n self.cursor.execute(sql)\n users_list = self.cursor.fetchall()\n return users_list\n except:\n return False\n\n def delete_user(self, table_name, user_name):\n try:\n sql = ''' DROP *\n FROM \"{0}\"\n WHERE username = \"{1}\";'''.format(table_name, user_name)\n self.cursor.execute(sql)\n return True\n except:\n return False\n\n def check_username(self, user_name):\n sql = ''' SELECT *\n FROM users\n WHERE username = \"{0}\";'''.format(user_name)\n self.cursor.execute(sql)\n user = self.cursor.fetchall()\n if len(user) == 1:\n return True\n return False\n\n def check_email(self, email):\n self.cursor.execute(\n '''SELECT *\n FROM users\n WHERE email = \"{0}\";'''.format(email)\n )\n user = self.cursor.fetchall()\n if len(user) == 1:\n return True\n return False\n\n def get_trades(self, user_id):\n try:\n self.cursor.execute(\n '''SELECT *\n FROM trades\n WHERE user_id = {0};'''.format(user_id)\n )\n trades = self.cursor.fetchall()\n trades_dict = {}\n i = 1\n for trade in trades:\n time = datetime.fromtimestamp(\n trade[5]).strftime('%Y-%m-%d %H:%M:%S')\n trades_dict[i] = [time,\n trade[2], trade[4], trade[3], trade[1]]\n i += 1\n return trades_dict\n except:\n return False\n\n def query_position(self, username, ticker):\n try:\n sql = ''' SELECT ticker, num_of_shares\n FROM positions\n WHERE user_id =\n (SELECT user_id\n FROM users\n WHERE username = ?)\n AND ticker = ?;'''\n return self.cursor.execute(sql, (username, ticker))\n except:\n return False\n\n def query_positions(self, userid):\n try:\n sql = ''' SELECT *\n FROM positions\n WHERE user_id = {0}\n GROUP BY ticker;'''.format(userid)\n self.cursor.execute(sql)\n positions = self.cursor.fetchall()\n position_dict = {}\n for position in positions:\n position_dict[position[1]] = position[2]\n return position_dict\n except:\n return False\n\n def get_sell_trades(self, userid):\n try:\n sql = ''' Select *\n FROM trades\n WHERE type = 'sell'\n AND user_id = {0};'''.format(userid)\n self.cursor.execute(sql)\n trades = self.cursor.fetchall()\n trades_dict = {}\n for trade in trades:\n if not trades_dict.get(trade[2]):\n trades_dict[trade[2]] = trade[3]*trade[4]\n else:\n trades_dict[trade[2]] += trade[3]*trade[4]\n return trades_dict\n except:\n return False\n\n def get_buy_trades(self, userid):\n try:\n sql = ''' SELECT *\n FROM trades\n WHERE type = 'buy'\n And user_id = {0};'''.format(userid)\n self.cursor.execute(sql)\n trades = self.cursor.fetchall()\n trades_dict = {}\n for trade in trades:\n if not trades_dict.get(trade[2]):\n trades_dict[trade[2]] = trade[3]*trade[4]\n else:\n trades_dict[trade[2]] += trade[3]*trade[4]\n return trades_dict\n except:\n return False\n","sub_path":"run/models/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":6807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"287286421","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread('src/lambo.PNG')\nprint(img.shape)\n\nimgResize = cv2.resize(img, (300,200))\n\n\nimgCropped = img[0:200, 200:500]\n\n\ncv2.imshow('image', img)\ncv2.imshow('imageResize', imgResize)\ncv2.imshow('Crop', imgCropped)\n\n\ncv2.waitKey(0)\n","sub_path":"02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"398465568","text":"from classy import Class \nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom numpy import log, exp\nimport sys\nfrom time import time \n\n# z = 0.61\n# z = 0.38\nz=0.86\ncosmo = Class ()\ncosmo.set({'k_pivot':'0.05',\n'ln10^{10}A_s':'3.044',\t\n# 'A_s':'2.19896453e-9',\n'n_s':'0.9649',\n'YHe':0.25,\n'tau_reio':'0.052',\n# 'T_cmb':'2.726',\n'h':'0.6737',\n'omega_b':'0.02237',\n'N_ncdm':'1',\n'm_ncdm':'0.06',\n'N_ur':'2.0328',\n'omega_cdm':'0.12',\n'P_k_max_h/Mpc': '100.',\n'output':'mPk,tCl',\n'z_pk':z,\n'non linear':' PT ',\n'IR resummation':' Yes ',\n'Bias tracers':' Yes ',\n'RSD':' Yes ',\n'AP':'Yes',\n'Omfid':0.31,\n# 'SigmaFOG':0.\n})\nt1 = time()\ncosmo.compute() \n\n\nh = cosmo.h()\nDa =cosmo.angular_distance(z)\nprint(\"Da=\",Da)\nfz = cosmo.scale_independent_growth_factor_f(z)\nprint(\"fz=\",fz)\n\n# omb = cosmo.omega_b()\n# Omm = cosmo.Omega_m()\n# # omm = cosmo.Omega_m()\n# # rat = omb/omm\n# # print(\"rat\",rat)\n# print(\"omega_b =\",omb)\n# print(\"Omega_m =\",Omm)\n\n#omcdm = Omm * h**2. - omb\n# omcdm = cosmo.omegach2()\n# print(\"omega_cdm =\",omcdm)\n\n#k1 = 0.7*1.028185622909e-5\n#k1 = 1.e-6\n#z = 0.0\n#k1 = 0.1\n#print(cosmo.pk(k1,z))\n#print(cosmo.pk_lin(k1,z))\n\nk = np.linspace(log(0.0001),log(50),200)\nk = np.exp(k)\ntestout = [ [0 for x in range(42)] for y in range(len(k))];\nfor i in range(len(k)):\n testout[i][0] = k[i]\n testout[i][41] = cosmo.pk_lin(k[i]*h,z)*h**3\n for j in range(40):\n# print(\"j=\",j)\n testout[i][j+1] = cosmo.pk(k[i]*h,z)[j]*h**3\n# testout[i][0] = k[i]\n# testout[i][1] = cosmo.pk(k[i],z)[0]\n# testout[i][2] = cosmo.pk(k[i],z)[1]\n# testout[i][3] = cosmo.pk(k[i],z)[2]\n# testout[i][4] = cosmo.pk(k[i],z)[3]\n# testout[i][5] = cosmo.pk(k[i],z)[4]\n# testout[i][6] = cosmo.pk(k[i],z)[5]\n# testout[i][7] = cosmo.pk(k[i],z)[6]\n# testout[i][8] = cosmo.pk(k[i],z)[7]\n# testout[i][9] = cosmo.pk(k[i],z)[8]\n#\ttestout[i][10] = cosmo.pk_lin(k[i],0)\n# np.savetxt('planck_pk_nl_bestfit_z038.dat', testout)\nnp.savetxt('planck_pk_nl_bestfit_z086.dat', testout)\nt2 = time()\nprint(\"overall elapsed time=\",t2-t1)\n### everything is in units Mpc! \n\n#l = np.array(range(2,2501))\n#factor = l*(l+1)/(2*np.pi)\n#raw_cl = cosmo.raw_cl(2500)\n#lensed_cl = cosmo.lensed_cl(2500)\n#raw_cl.viewkeys()\n\n#z = 0.2\n#raw_pk = np.zeros(len(k))\n#for i in range(len(k)):\n# raw_pk[i] = k[i]*cosmo.pk(k[i],z)\n\n#cosmo.set({'P_k_max_h/Mpc': '100.','output':'mPk','z_pk':'0.2','non linear':' SPT ','IR resummation':' Yes ','Bias tracers':' No '})\n#cosmo.compute()\n\n#z = 0.2\n#pk_lin = np.zeros(len(k))\n#for i in range(len(k)):\n# pk_lin[i] = float(cosmo.pk(k[i],z))\n\n#plt.loglog(k,raw_pk)\n#plt.xlabel(r\"$k$\")\n\n#plt.ylabel(r\"$P(k)$\")\n#plt.tight_layout()\n#plt.savefig(\"misha_test.pdf\")\n\n","sub_path":"python/planck_bf.py","file_name":"planck_bf.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"516156965","text":"# Cyclic Rotation\n#\n# Given array A = [3, 8, 9, 7, 6] and integer value K, design an algorithm\n# that returns the elements in A shifted by amount k\n#\n# Example\n#\n# A = [3, 8, 9, 7, 6]\n# K = 3\n#\n# output: [9, 7, 6, 3, 8]\n#\n# [3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]\n# [6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]\n# [7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]\n#\n# Example 2\n#\n# A = [0, 0, 0]\n# K = 1\n#\n# output: [0, 0, 0]\n#\n# Example 3\n#\n# A = [1, 2, 3, 4]\n# K = 4\n#\n# output: [1,2,3,4]\n#\n#\n# inputs\n# - an array of integers\n# - integer\n#\n# output\n# - an array of integers\n#\n# constraint\n# - N and K are integers in range [0 ... 100]\n# - each element in array A is an integer in range [-1000 ... 1000]\n# - we don't need to focus on the efficiency of the problem. correctness suffices\n#\n#\n# [3, 8, 9, 7, 6] K =3\n#\n#\n# [3, 8, 9, 7, 6] --> [9, 7, 6, 3, 8] ==> putting an element at index in index + K in another array!!!\n# 0 3\n#\n# [3, 8, 9, 7, 6] --> [9, 7, 6, 3, 8] ==> putting an element at index in ( index + K ) % len(A) in another array!!!\n# 3 1\n#\n# [3, 8, 9, 7, 6] , [-,-,-,-,-]\n#\n# # 1\n# [3, 8, 9, 7, 6] , [-,-,-,3,-]\n# x\n#\n# # 2\n# [3, 8, 9, 7, 6] , [-,-,-,3,8]\n# x\n#\n# # 3\n# [3, 8, 9, 7, 6] , [9,-,-,3,8]\n# x\n#\n# # 4\n# [3, 8, 9, 7, 6] , [9,7,-,3,8]\n# x\n#\n# # 4\n# [3, 8, 9, 7, 6] , [9,7,6,3,8]\n# x\n#\n# Pseudocode\nclass Solution:\n def solve(self, A, K):\n # 1. initialize output array ([None] * len(A))\n\n if len(A) == 0 or len(A) == 1 or K == len(A):\n return A\n\n output = [None] * len(A)\n\n # 2. for each element, index in A. put element in output at position (index + K) % len(A)\n index = 0\n while index < len(A):\n index_new = (index + K) % len(A)\n output[index_new] = A[index]\n\n index += 1\n\n return output\n # 3. return output\n#\n# time complexity O(N) and spatial complexity O(N)\n\nif __name__ == '__main__':\n A_case_1 = []\n K_case_1 = 100\n A_case_2 = [1]\n K_case_2 = 2\n A_case_3 = [3, 8, 9, 7, 6]\n K_case_3 = 3\n A_case_4 = [1,2,3,4]\n K_case_4 = 4\n\n expected_1 = []\n expected_2 = [1]\n expected_3 = [9, 7, 6, 3, 8]\n expected_4 = [1,2,3,4]\n\n solution_1 = Solution().solve(A_case_1, K_case_1)\n solution_2 = Solution().solve(A_case_2, K_case_2)\n solution_3 = Solution().solve(A_case_3, K_case_3)\n solution_4 = Solution().solve(A_case_4, K_case_4)\n\n assert expected_1 == solution_1\n assert expected_2 == solution_2\n assert expected_3 == solution_3\n assert expected_4 == solution_4\n","sub_path":"codility_practice/arrays/cyclic_rotation_video_practice_01.py","file_name":"cyclic_rotation_video_practice_01.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"19207380","text":"class Solution(object):\n def shuffle(self, nums, n):\n \"\"\"\n :type nums: List[int]\n :type n: int\n :rtype: List[int]\n \"\"\"\n # result = []\n # result1 = nums[0:n]\n # result2 = nums[n:len(nums)]\n # j,k = 0,0\n # for i in range(0,len(nums)):\n # if i % 2 == 0:\n # result.append(result1[j])\n # j = j + 1\n # else:\n # result.append(result2[k])\n # k = k + 1\n # return result\n \n\n\n \n\ntemp = Solution()\n\nlist = [1,2,3,4]\n\nprint(temp.shuffle(list,2))\n","sub_path":"LeetCodeTest/ReArray.py","file_name":"ReArray.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"317912028","text":"\nimport time\n\nimport pygame\nfrom pygame import Rect\n\nfrom tilegamelib import TiledMap\nfrom tilegamelib.game import Game\nfrom tilegamelib.map_move import MapMove\nfrom tilegamelib.sprites import Sprite\nfrom tilegamelib.config import config\n\n\nBOXMAP = \"\"\"##########\n#..#...**#\n#..#.##**#\n#..#.##..#\n##x....x.#\n#.x.....x#\n#........#\n##########\"\"\"\n\nconfig.RESOLUTION = (450, 400)\n\n\nclass Boxes:\n\n def __init__(self):\n self.game = Game()\n self.tm = TiledMap(self.game)\n self.player = Sprite(self.game, 'b.tail', (4, 1), speed=4)\n self.tm.set_map(BOXMAP)\n\n def draw(self):\n self.tm.draw()\n self.player.draw()\n\n def move(self, direction):\n nearpos = self.player.pos + direction\n farpos = nearpos + direction\n near = self.tm.at(nearpos)\n far = self.tm.at(farpos)\n if near == '#':\n return\n if near in 'xX' and far in '#xX':\n return\n else:\n # move possible\n self.player.add_move(direction)\n moves = [self.player]\n if near in 'xX':\n # crate moved\n floor = '.' if near == 'x' else '*'\n insert = 'X' if far == '*' else 'x'\n moves.append(MapMove(self.tm, nearpos, direction, 4,\n floor_tile=floor, insert_tile=insert))\n self.game.wait_for_move(moves, self.draw, 0.02)\n\n self.draw()\n self.check_complete()\n\n def check_complete(self):\n s = self.tm.get_map()\n if s.count('X') == 4:\n print(\"\\nCongratulations!\\n\")\n time.sleep(2)\n self.game.exit()\n\n def run(self):\n self.game.event_loop(figure_moves=self.move, draw_func=self.draw)\n\n\nif __name__ == '__main__':\n boxes = Boxes()\n boxes.run()\n pygame.quit()\n","sub_path":"examples/boxes.py","file_name":"boxes.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"567682908","text":"\nimport turtle\nimport random\nimport time\n\nturtle.tracer(1,0)\n\nwindow_size_x=1920\nwindow_size_y=1080\n\nturtle.setup(window_size_x,window_size_y)\nglobal score\nscore = 0\n\nfrom pygame import mixer \n\nmixer.init()\nmixer.music.load('whackamole.mp3')\nmixer.music.play()\n\nturtle.addshape(\"hammer.gif\")\nhammer=turtle.clone()\nhammer.shape(\"hammer.gif\")\nhammer.penup()\n\ntrash=turtle.clone()\nteachers=turtle.clone()\nscreen=turtle.clone()\nwriter=turtle.clone()\n\nturtle.register_shape(\"heart.gif\")\nturtle.register_shape(\"trash.gif\")\nturtle.register_shape(\"Calebb.gif\")\nturtle.register_shape(\"backpack.gif\")\n\nteachers.shape(\"Calebb.gif\")\nturtle.addshape(\"heart.gif\")\nturtle.bgpic(\"backpack.gif\")\ntrash = turtle.clone()\nturtle.addshape(\"trash3.gif\")\ntrash.shape(\"trash3.gif\")\ntrash.penup()\n#first heart \nheart = turtle.clone()\nheart.shape(\"heart.gif\")\nheart.penup()\nheart.goto(-700,400)\n#second heart\nheart2 = turtle.clone()\nheart2.shape(\"heart.gif\")\nheart2.penup()\nheart2.goto(-770,400)\n#third heart\nheart3= turtle.clone()\nheart3.shape(\"heart.gif\")\nheart3.penup()\nheart3.goto(-840,400)\nturtle.undo()\nheart.penup()\nwriter.penup()\nteachers.penup()\n\nDeath=0\nhole_loc = [(483,293),(-14,289),(-512,292),(595,91),(185,87),(-217,90),(-633,88),(496,-220),(-20,-224),(-537,-222)]\ntrash_list = [trash, trash.clone()]\ncaleb_list = [teachers, teachers.clone()]\ntrash_hole = []\ncaleb_hole = []\ndef show_trash():\n global trash_hole\n trash_hole = []\n for t in trash_list:\n hole = random.randint(0,9)\n while hole in trash_hole or hole in caleb_hole:\n hole = random.randint(0,9)\n trash_hole.append(hole)\n t.goto(hole_loc[hole])\n \n\ndef show_caleb():\n global caleb_hole\n caleb_hole = []\n for c in caleb_list:\n hole = random.randint(0,9)\n while hole in trash_hole or hole in caleb_hole:\n hole = random.randint(0,9)\n caleb_hole.append(hole)\n c.goto(hole_loc[hole])\n\ndef end_timer():\n show_trash()\n show_caleb()\n print(caleb_hole+trash_hole)\n turtle.ontimer(end_timer, 3000)\n \n\ndef click(x,y):\n global Death, score, play\n play = False\n hammer.goto(x,y)\n x=hammer.pos()[0]\n y=hammer.pos()[1]\n z=30\n click_trash = False\n for t in trash_list:\n if x in range (t.pos()[0]-z,t.pos()[0]+z) and y in range (t.pos()[1]-z,t.pos()[1]+z):\n show_trash()\n turtle.undo()\n turtle.hideturtle()\n turtle.penup()\n turtle.color('red')\n score+=1\n turtle.goto(900,450)\n turtle.write(score, move=False, align='left', font= ('Arial', 30,'normal'))\n click_trash = True\n if not click_trash:\n Death+=1\n for c in caleb_list:\n if x in range (c.pos()[0]-z,c.pos()[0]+z) and y in range (c.pos()[1]-z,c.pos()[1]+z):\n show_caleb()\n if Death == 1 :\n heart.ht()\n elif Death == 2 :\n heart2.ht()\n elif Death == 3 :\n heart3.ht()\n writer.ht()\n FONT = ('Arial',60,'normal')\n writer.color(\"white\") \n writer.goto(-200,0)\n writer.write(\"Game Over\",font=FONT)\n return quit()\n#for i in rang (0, \nturtle.onscreenclick(click)\nend_timer()\n\n\nshow_trash()\nshow_caleb()\n\n\nturtle.mainloop()\n \n","sub_path":"part 1 code.py","file_name":"part 1 code.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"292805187","text":"import json\nfrom typing import Dict\n\nfrom flask import Blueprint, Response, request\n\nfrom ssh_manager_backend.app.controllers import UserController\nfrom ssh_manager_backend.app.services import rsa\n\nrsa_ = Blueprint(\"rsa\", __name__)\nusers_ = Blueprint(\"users\", __name__)\n\n\n@rsa_.route(\"/get_rsa_key\", methods=[\"GET\"])\ndef rsa_handler() -> Response:\n if not rsa.is_generated():\n rsa.generate_key_pair()\n\n return Response(response=json.dumps({\"data\": {\"public_key\": rsa.public_key}}))\n\n\n@users_.route(\"/register\", methods=[\"POST\"])\ndef register_handler() -> Response:\n body: Dict[str, any] = json.loads(request.get_json())\n return UserController().register(body)\n\n\n@users_.route(\"/login\", methods=[\"POST\"])\ndef login_handler() -> Response:\n body: Dict[str, any] = json.loads(request.get_json())\n return UserController().login(body)\n\n\n@users_.route(\"/logout\", methods=[\"POST\"])\ndef logout_handler() -> Response:\n access_token: str = request.headers.get(\"access_token\")\n body: Dict[str, any] = json.loads(request.get_json())\n return UserController(access_token=access_token).logout(body=body)\n\n\n@users_.route(\"/is_admin\", methods=[\"POST\"])\ndef is_admin_handler() -> Response:\n body: Dict[str, any] = json.loads(request.get_json())\n access_token: str = request.headers.get(\"access_token\")\n return UserController(access_token=access_token).is_admin(body=body)\n\n\n@users_.route(\"/is_logged_in\", methods=[\"POST\"])\ndef is_logged_in():\n body: Dict[str, any] = json.loads(request.get_json())\n access_token: str = request.headers.get(\"access_token\")\n return UserController(access_token=access_token).is_logged_in(body=body)\n","sub_path":"ssh_manager_backend/config/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"330814885","text":"\"\"\"\n演示引用\n\"\"\"\n\"\"\"\n❤ 引用就是变量指向数据存储空间的现象\n\n❤ 相同数据(不可变类型)使用同一个空间存储, 节约内存占用\n\n❤ 使用 id(数据) 操作可以获取到数据存储的内存空间引用地址\t\n\n\"\"\"\n\n# 变量是一个箱子,是一个容器,可以用来保存数据,,推翻掉 >>> 引用\n# a = 1 # 整型 a → 1\n# print(a)\n# b = 'hello' # 字符串\n# c = [1,2,3] # 列表\n#\n# # a = 1 # a → 1 (101) 拆掉 引用关系\n# a = 2 # a → 2 (102)\n\n\n\"\"\"\n1, 1, 2, 3, 5, 8\n假设demo(5) 得到的是斐波那契额数列第五个值 5\n假设demo(3) 得到的是斐波那契额数列第三个值 2\n假设demo(4) 得到的是斐波那契额数列第四个值 3\n 5 = 3 + 2\n那么demo(5) = demo(5-1) + demo(5-2)\n demo(5) = demo(4) + demo(3)\n\n函数名():\n1.会执行函数里面的代码,\n2.执行完代码之后,本身就代表返回值\n\"\"\"\n\n#\n# 相同数据(不可变类型)使用同一个空间存储, 节约内存占用\n# 使用 id(数据) 操作可以获取到数据存储的内存空间引用地址\n# a = 1 # a → 1\n# print(id(a)) # a 的内存地址 id(1)\n# b = 1\n# print(id(b)) # 如果他们的值相同\n\n\n# 可变类型\n# list1 = [1,2,3]\n# list2 = [1,2,3]\n#\n# print(id(list1)) # 打印list1指向的[1,2,3]的地址\n# print(id(list2)) # 打印list2指向的[1,2,3]的地址\n\n\n# list1 = [1,2,3]\n# print(id(list1)) # 打印列表[1,2,3]的内存地址值(门牌号)\n# print(id(list1[0])) # 打印数据 1 的内存地址值(门牌号)\n# print(id(list1[1])) # 打印数据 2 的内存地址值(门牌号)\n# print(id(list1[2])) # 打印数据 3 的内存地址值(门牌号)\n# # 如果门牌号是一模一样的, 那么就说明他们在同一个地方\n# 内存地址值不一样\n\n\n\n# 函数\ndef demo1(): # 函数名 变量名\n print('bobo老师无敌帅气')\n\n# demo1()\naaa = demo1 # 指向了函数内部的代码空间 aaa也指向了这片代码空间 aaa → demo1\n\ndemo1() # 函数的调用, 跟着引用箭头去那片空间里面执行代码\n\naaa() # 函数的调用, 跟着引用箭头去那片空间里面执行代码\n\n# 名称虽然不同,, 但是却指向了同一片内存空间, 因为调用函数之后,, 结果是一样的\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ITcoach/sixstar/基础班代码/13_闭包装饰器/lx_01_引用.py","file_name":"lx_01_引用.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"587513114","text":"def countLines(file):\n file.seek(0)\n return len(file.readlines())\n\ndef countChars(file):\n file.seek(0)\n return len(file.read())\n\ndef test(name):\n file = open(name)\n print('the number of lines in the file:', file.name, str(countLines(file)))\n print('the number of chars in the file:', file.name, str(countChars(file)))\n file.close()\n\nif __name__ == '__main__':\n import sys\n if len(sys.argv) > 1:\n test(sys.argv[1])\n else: print('error: you need input file name after mymod.py')\n","sub_path":"Python/mypkg/mymod.py","file_name":"mymod.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"333755218","text":"import numpy as np\nfrom collections import OrderedDict\nimport matplotlib.pyplot as plt\nimport copy\ndef get_evaluation_rollouts(policy, env, num_of_paths, max_ep_steps, render= True):\n\n a_bound = env.action_space.high\n paths = []\n\n for ep in range(num_of_paths):\n s = env.reset()\n path = {'rewards':[],\n 'lrewards':[]}\n for step in range(max_ep_steps):\n if render:\n env.render()\n a = policy.choose_action(s, evaluation=True)\n action = a * a_bound\n action = np.clip(action, -a_bound, a_bound)\n s_, r, done, info = env.step(action)\n l_r = info['l_rewards']\n\n path['rewards'].append(r)\n path['lrewards'].append(l_r)\n s = s_\n if done or step == max_ep_steps-1:\n paths.append(path)\n break\n if len(paths)< num_of_paths:\n print('no paths is acquired')\n\n return paths\n\n\ndef evaluate_rollouts(paths):\n total_returns = [np.sum(path['rewards']) for path in paths]\n total_lreturns = [np.sum(path['lrewards']) for path in paths]\n episode_lengths = [len(p['rewards']) for p in paths]\n import matplotlib.pyplot as plt\n [plt.plot(np.arange(0, len(path['rewards'])), path['rewards']) for path in paths]\n try:\n diagnostics = OrderedDict((\n ('return-average', np.mean(total_returns)),\n ('return-min', np.min(total_returns)),\n ('return-max', np.max(total_returns)),\n ('return-std', np.std(total_returns)),\n ('lreturn-average', np.mean(total_lreturns)),\n ('lreturn-min', np.min(total_lreturns)),\n ('lreturn-max', np.max(total_lreturns)),\n ('lreturn-std', np.std(total_lreturns)),\n ('episode-length-avg', np.mean(episode_lengths)),\n ('episode-length-min', np.min(episode_lengths)),\n ('episode-length-max', np.max(episode_lengths)),\n ('episode-length-std', np.std(episode_lengths)),\n ))\n except ValueError:\n print('Value error')\n else:\n return diagnostics\n\n\ndef evaluate_training_rollouts(paths):\n data = copy.deepcopy(paths)\n if len(data) < 1:\n return None\n try:\n diagnostics = OrderedDict((\n ('return', np.mean([np.sum(path['rewards']) for path in data])),\n ('length', np.mean([len(p['rewards']) for p in data])),\n ))\n except KeyError:\n return\n [path.pop('rewards') for path in data]\n for key in data[0].keys():\n result = [np.mean(path[key]) for path in data]\n diagnostics.update({key: np.mean(result)})\n\n return diagnostics\n","sub_path":"LAC/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"449775798","text":"import requests\nimport docx\nimport sys\nimport re\n\n\nclass contentScrapper():\n\n def __init__(self,url,page = 1):\n self.page = page\n if not self.verify_url(url):\n raise TypeError(\"Not a valid url\")\n\n\n\n\n def break_into_paragraphs(text):\n \"Breaks html into text content paragraphs\"\n text = text.replace('

','')\n text = re.sub(r'','',text)\n paragraphs = text.split('

')\n return paragraphs\n\n def verify_url(self,url):\n pattern = re.compile('http(s)?://(www\\.)?\\w+\\.\\w{1,5}')\n if pattern.match(url) != None:\n return True\n return False\n\n def get_title(text):\n \"Acquires the title for the post\"\n startI = text.find('

')\n temp = text[startI:startI+100]\n startI = temp.find('title\">')\n\n endinI = temp.find('

')\n title = temp[startI + 7: endinI]\n title = title.replace('&','&')\n title = title.replace(' ',' ')\n return title \n\n def isolate_content(text):\n \"Removes everything that is not content\"\n startI = text.find('
')\n text = text[startI:]\n startI = text.find('

')\n endinI = text.find('

%s' % (old_var_name, var_name))\n break\n return var_name\n\n\ndef _rnn_name_replacement_sharded(var_name):\n for pattern in _RNN_SHARDED_NAME_REPLACEMENTS:\n if pattern in var_name:\n old_var_name = var_name\n var_name = var_name.replace(pattern,\n _RNN_SHARDED_NAME_REPLACEMENTS[pattern])\n logging.info('Converted: %s --> %s' % (old_var_name, var_name))\n return var_name\n\n\ndef _split_sharded_vars(name_shape_map):\n \"\"\"Split shareded variables.\n\n Args:\n name_shape_map: A dict from variable name to variable shape.\n\n Returns:\n not_sharded: Names of the non-sharded variables.\n sharded: Names of the sharded variables.\n \"\"\"\n sharded = []\n not_sharded = []\n for name in name_shape_map:\n if re.match(name, '_[0-9]+$'):\n if re.sub('_[0-9]+$', '_1', name) in name_shape_map:\n sharded.append(name)\n else:\n not_sharded.append(name)\n else:\n not_sharded.append(name)\n return not_sharded, sharded\n\n\ndef convert_names(checkpoint_from_path,\n checkpoint_to_path,\n write_v1_checkpoint=False):\n \"\"\"Migrates the names of variables within a checkpoint.\n\n Args:\n checkpoint_from_path: Path to source checkpoint to be read in.\n checkpoint_to_path: Path to checkpoint to be written out.\n write_v1_checkpoint: Whether the output checkpoint will be in V1 format.\n\n Returns:\n A dictionary that maps the new variable names to the Variable objects.\n A dictionary that maps the old variable names to the new variable names.\n \"\"\"\n with ops.Graph().as_default():\n logging.info('Reading checkpoint_from_path %s' % checkpoint_from_path)\n reader = pywrap_tensorflow.NewCheckpointReader(checkpoint_from_path)\n name_shape_map = reader.get_variable_to_shape_map()\n not_sharded, sharded = _split_sharded_vars(name_shape_map)\n new_variable_map = {}\n conversion_map = {}\n for var_name in not_sharded:\n new_var_name = _rnn_name_replacement(var_name)\n tensor = reader.get_tensor(var_name)\n var = variables.Variable(tensor, name=var_name)\n new_variable_map[new_var_name] = var\n if new_var_name != var_name:\n conversion_map[var_name] = new_var_name\n for var_name in sharded:\n new_var_name = _rnn_name_replacement_sharded(var_name)\n var = variables.Variable(tensor, name=var_name)\n new_variable_map[new_var_name] = var\n if new_var_name != var_name:\n conversion_map[var_name] = new_var_name\n\n write_version = (saver_pb2.SaverDef.V1\n if write_v1_checkpoint else saver_pb2.SaverDef.V2)\n saver = saver_lib.Saver(new_variable_map, write_version=write_version)\n\n with session.Session() as sess:\n sess.run(variables.global_variables_initializer())\n logging.info('Writing checkpoint_to_path %s' % checkpoint_to_path)\n saver.save(sess, checkpoint_to_path)\n\n logging.info('Summary:')\n logging.info(' Converted %d variable name(s).' % len(new_variable_map))\n return new_variable_map, conversion_map\n\n\ndef main(_):\n convert_names(\n FLAGS.checkpoint_from_path,\n FLAGS.checkpoint_to_path,\n write_v1_checkpoint=FLAGS.write_v1_checkpoint)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.register('type', 'bool', lambda v: v.lower() == 'true')\n parser.add_argument('checkpoint_from_path', type=str,\n help='Path to source checkpoint to be read in.')\n parser.add_argument('checkpoint_to_path', type=str,\n help='Path to checkpoint to be written out.')\n parser.add_argument('--write_v1_checkpoint', action='store_true',\n help='Write v1 checkpoint')\n FLAGS, unparsed = parser.parse_known_args()\n\n app.run(main=main, argv=[sys.argv[0]] + unparsed)\n","sub_path":"Tensorflow/source/tensorflow/contrib/rnn/python/tools/checkpoint_convert.py","file_name":"checkpoint_convert.py","file_ext":"py","file_size_in_byte":10962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"53572938","text":"import os, time, math\n# Vahin Sharma\nprint(\"============== OLD FILES DELETER ==============\")\ndef getFileAge(x):\n return math.floor(time.time()-os.stat(x).st_mtime) // (24 * 3600)\nwhile True:\n path = input(\"Please enter the path (enter 'quit' to stop this program): \")\n if os.path.exists(path):\n for i in os.listdir(path):\n nPath = path+\"/\"+i\n if getFileAge(nPath) > 25:\n askUsr = input(\"Should I delete this: {} (y/n) \".format(i)).lower()\n if askUsr == \"y\":\n try:\n os.remove(nPath)\n except:\n print(\"Access denied, either due to system permissions, or the file is read-only.\")\n else:\n print(\"NO\")\n elif path == \"quit\":\n quit()\n else:\n print(\"Invalid Path\")\n","sub_path":"removeFiles.py","file_name":"removeFiles.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"365798703","text":"# -*- coding: utf-8 -*-\n\"\"\"Implementation of a branch on a repository.\"\"\"\nfrom __future__ import unicode_literals\n\nfrom json import dumps\n\nfrom . import commit\nfrom .. import decorators\nfrom .. import models\n\n\nclass _Branch(models.GitHubCore):\n \"\"\"A representation of a branch on a repository.\n\n See also https://developer.github.com/v3/repos/branches/\n\n This object has the following attributes:\n \"\"\"\n\n # The Accept header will likely be removable once the feature is out of\n # preview mode. See: http://git.io/v4O1e\n PREVIEW_HEADERS = {'Accept': 'application/vnd.github.loki-preview+json'}\n\n class_name = 'Repository Branch'\n\n def _update_attributes(self, branch):\n self.commit = commit.MiniCommit(branch['commit'], self)\n self.name = branch['name']\n base = self.commit.url.split('/commit', 1)[0]\n self._api = self._build_url('branches', self.name, base_url=base)\n\n def _repr(self):\n return '<{0} [{1}]>'.format(self.class_name, self.name)\n\n def latest_sha(self, differs_from=''):\n \"\"\"Check if SHA-1 is the same as the remote branch.\n\n See: https://git.io/vaqIw\n\n :param str differs_from:\n (optional), sha to compare against\n :returns:\n string of the SHA or None\n \"\"\"\n # If-None-Match returns 200 instead of 304 value does not have quotes\n headers = {\n 'Accept': 'application/vnd.github.v3.sha',\n 'If-None-Match': '\"{0}\"'.format(differs_from)\n }\n base = self._api.split('/branches', 1)[0]\n url = self._build_url('commits', self.name, base_url=base)\n resp = self._get(url, headers=headers)\n if self._boolean(resp, 200, 304):\n return resp.content\n return None\n\n @decorators.requires_auth\n def protection(self):\n \"\"\"Retrieve the protections enabled for this branch.\n\n See:\n https://developer.github.com/v3/repos/branches/#get-branch-protection\n\n :returns:\n The protections enabled for this branch.\n :rtype:\n :class:`~github3.repos.branch.BranchProtection`\n \"\"\"\n url = self._build_url('protection', base_url=self._api)\n headers_map = BranchProtection.PREVIEW_HEADERS_MAP\n headers = headers_map['required_approving_review_count']\n resp = self._get(url, headers=headers)\n json = self._json(resp, 200)\n return BranchProtection(json, self)\n\n @decorators.requires_auth\n def protect(self, enforcement=None, status_checks=None):\n \"\"\"Enable force push protection and configure status check enforcement.\n\n See: http://git.io/v4Gvu\n\n :param str enforcement:\n (optional), Specifies the enforcement level of the status checks.\n Must be one of 'off', 'non_admins', or 'everyone'. Use `None` or\n omit to use the already associated value.\n :param list status_checks:\n (optional), An list of strings naming status checks that must pass\n before merging. Use `None` or omit to use the already associated\n value.\n :returns:\n True if successful, False otherwise\n :rtype:\n bool\n \"\"\"\n previous_values = None\n if self.protection:\n previous_values = self.protection['required_status_checks']\n if enforcement is None and previous_values:\n enforcement = previous_values['enforcement_level']\n if status_checks is None and previous_values:\n status_checks = previous_values['contexts']\n\n edit = {'protection': {'enabled': True, 'required_status_checks': {\n 'enforcement_level': enforcement, 'contexts': status_checks}}}\n json = self._json(self._patch(self._api, data=dumps(edit),\n headers=self.PREVIEW_HEADERS), 200)\n self._update_attributes(json)\n return True\n\n @decorators.requires_auth\n def unprotect(self):\n \"\"\"Disable force push protection on this branch.\"\"\"\n edit = {'protection': {'enabled': False}}\n json = self._json(self._patch(self._api, data=dumps(edit),\n headers=self.PREVIEW_HEADERS), 200)\n self._update_attributes(json)\n return True\n\n\nclass Branch(_Branch):\n \"\"\"The representation of a branch returned in a collection.\n\n GitHub's API returns different amounts of information about repositories\n based upon how that information is retrieved. This object exists to\n represent the limited amount of information returned for a specific\n branch in a collection. For example, you would receive this class when\n calling :meth:`~github3.repos.repo.Repository.branches`. To provide a\n clear distinction between the types of branches, github3.py uses different\n classes with different sets of attributes.\n\n This object has the same attributes as a\n :class:`~github3.repos.branch.ShortBranch` as well as the following:\n\n .. attribute:: links\n\n The dictionary of URLs returned by the API as ``_links``.\n\n .. attribute:: protected\n\n A boolean attribute that describes whether this branch is protected or\n not.\n\n .. attribute:: original_protection\n\n .. versionchanged:: 1.1.0\n\n To support a richer branch protection API, this is the new name\n for the information formerly stored under the attribute\n ``protection``.\n\n A dictionary with details about the protection configuration of this\n branch.\n\n .. attribute:: protection_url\n\n The URL to access and manage details about this branch's protection.\n \"\"\"\n\n class_name = 'Repository Branch'\n\n def _update_attributes(self, branch):\n super(Branch, self)._update_attributes(branch)\n self.commit = commit.ShortCommit(branch['commit'], self)\n #: Returns '_links' attribute.\n self.links = branch['_links']\n #: Provides the branch's protection status.\n self.protected = branch['protected']\n self.original_protection = branch['protection']\n self.protection_url = branch['protection_url']\n if self.links and 'self' in self.links:\n self._api = self.links['self']\n\n\nclass ShortBranch(_Branch):\n \"\"\"The representation of a branch returned in a collection.\n\n GitHub's API returns different amounts of information about repositories\n based upon how that information is retrieved. This object exists to\n represent the limited amount of information returned for a specific\n branch in a collection. For example, you would receive this class when\n calling :meth:`~github3.repos.repo.Repository.branches`. To provide a\n clear distinction between the types of branches, github3.py uses different\n classes with different sets of attributes.\n\n This object has the following attributes:\n\n .. attribute:: commit\n\n A :class:`~github3.repos.commit.MiniCommit` representation of the\n newest commit on this branch with the associated repository metadata.\n\n .. attribute:: name\n\n The name of this branch.\n \"\"\"\n\n class_name = 'Short Repository Branch'\n _refresh_to = Branch\n\n\nclass BranchProtection(models.GitHubCore):\n \"\"\"The representation of a branch's protection.\n\n .. seealso::\n\n `Branch protection API documentation`_\n GitHub's documentation of branch protection\n\n This object has the following attributes:\n\n .. attribute:: enforce_admins\n\n A :class:`~github3.repos.branch.ProtectionEnforceAdmins` instance\n representing whether required status checks are required for admins.\n\n .. attribute:: restrictions\n\n A :class:`~github3.repos.branch.ProtectionRestrictions` representing\n who can push to this branch. Team and user restrictions are only\n available for organization-owned repositories.\n\n .. attribute:: required_pull_request_reviews\n\n A :class:`~github3.repos.branch.ProtectionRequiredPullRequestReviews`\n representing the protection provided by requiring pull request\n reviews.\n\n .. attribute:: required_status_checks\n\n A :class:`~github3.repos.branch.ProtectionRequiredStatusChecks`\n representing the protection provided by requiring status checks.\n\n .. links\n .. _Branch protection API documentation:\n https://developer.github.com/v3/repos/branches/#get-branch-protection\n \"\"\"\n\n PREVIEW_HEADERS_MAP = {\n 'required_approving_review_count': {\n 'Accept': 'application/vnd.github.luke-cage-preview+json',\n },\n 'requires_signed_commits': {\n 'Accept': 'application/vnd.github.zzzax-preview+json',\n },\n 'nested_teams': {\n 'Accept': 'application/vnd.github.hellcat-preview+json',\n },\n }\n\n def _update_attributes(self, protection):\n self._api = protection['url']\n\n def _set_conditional_attr(name, cls):\n value = protection.get(name)\n setattr(self, name, value)\n if getattr(self, name):\n setattr(self, name, cls(value, self))\n\n _set_conditional_attr('enforce_admins', ProtectionEnforceAdmins)\n _set_conditional_attr('restrictions', ProtectionRestrictions)\n _set_conditional_attr('required_pull_request_reviews',\n ProtectionRequiredPullRequestReviews)\n _set_conditional_attr('required_status_checks',\n ProtectionRequiredStatusChecks)\n\n\nclass ProtectionEnforceAdmins(models.GitHubCore):\n \"\"\"The representation of a sub-portion of branch protection.\n\n .. seealso::\n\n `Branch protection API documentation`_\n GitHub's documentation of branch protection\n\n This object has the following attributes:\n\n .. attribute:: enabled\n\n A boolean attribute indicating whether the ``enforce_admins``\n protection is enabled or disabled.\n\n\n .. links\n .. _Branch protection API documentation:\n https://developer.github.com/v3/repos/branches/#get-branch-protection\n \"\"\"\n\n def _update_attributes(self, protection):\n self._api = protection['url']\n self.enabled = protection['enabled']\n\n\nclass ProtectionRestrictions(models.GitHubCore):\n \"\"\"The representation of a sub-portion of branch protection.\n\n .. seealso::\n\n `Branch protection API documentation`_\n GitHub's documentation of branch protection\n\n `Branch restriction documentation`_\n GitHub's description of branch restriction\n\n This object has the following attributes:\n\n .. attribute:: original_teams\n\n List of :class:`~github3.orgs.ShortTeam` objects representing\n the teams allowed to push to the protected branch.\n\n .. attribute:: original_users\n\n List of :class:`~github3.users.ShortUser` objects representing\n the users allowed to push to the protected branch.\n\n .. attribute:: teams_url\n\n The URL to retrieve the list of teams allowed to push to the\n protected branch.\n\n .. attribute:: users_url\n\n The URL to retrieve the list of users allowed to push to the\n protected branch.\n\n\n .. links\n .. _Branch protection API documentation:\n https://developer.github.com/v3/repos/branches/#get-branch-protection\n .. _Branch restriction documentation:\n https://help.github.com/articles/about-branch-restrictions\n \"\"\"\n\n def _update_attributes(self, protection):\n from .. import orgs, users\n self._api = protection['url']\n self.users_url = protection['users_url']\n self.teams_url = protection['teams_url']\n self.original_users = protection['users']\n if self.original_users:\n self.original_users = [\n users.ShortUser(user, self)\n for user in self.original_users\n ]\n\n self.original_teams = protection['teams']\n if self.original_teams:\n self.original_teams = [\n orgs.ShortTeam(team, self)\n for team in self.original_teams\n ]\n\n def teams(self, number=-1):\n \"\"\"Retrieve an up-to-date listing of teams.\n\n :returns:\n An iterator of teams\n :rtype:\n :class:`~github3.orgs.ShortTeam`\n \"\"\"\n from .. import orgs\n return self._iter(int(number), self.teams_url, orgs.ShortTeam)\n\n def users(self, number=-1):\n \"\"\"Retrieve an up-to-date listing of users.\n\n :returns:\n An iterator of users\n :rtype:\n :class:`~github3.users.ShortUser`\n \"\"\"\n from .. import users\n return self._iter(int(number), self.users_url, users.ShortUser)\n\n\nclass ProtectionRequiredPullRequestReviews(models.GitHubCore):\n \"\"\"The representation of a sub-portion of branch protection.\n\n .. seealso::\n\n `Branch protection API documentation`_\n GitHub's documentation of branch protection\n\n\n .. links\n .. _Branch protection API documentation:\n https://developer.github.com/v3/repos/branches/#get-branch-protection\n \"\"\"\n\n def _update_attributes(self, protection):\n self._api = protection['url']\n self.dismiss_stale_reviews = protection['dismiss_stale_reviews']\n # Use a temporary value to stay under line-length restrictions\n value = protection['require_code_owner_reviews']\n self.require_code_owner_reviews = value\n # Use a temporary value to stay under line-length restrictions\n value = protection['required_approving_review_count']\n self.required_approving_review_count = value\n self.dismissal_restrictions = ProtectionRestrictions(\n protection['dismissal_restrictions'],\n self,\n )\n\n\nclass ProtectionRequiredStatusChecks(models.GitHubCore):\n \"\"\"The representation of a sub-portion of branch protection.\n\n .. seealso::\n\n `Branch protection API documentation`_\n GitHub's documentation of branch protection\n `Required Status Checks documentation`_\n GitHub's description of required status checks\n\n\n .. links\n .. _Branch protection API documentation:\n https://developer.github.com/v3/repos/branches/#get-branch-protection\n .. _Required Status Checks documentation:\n https://help.github.com/articles/about-required-status-checks\n \"\"\"\n\n def _update_attributes(self, protection):\n self._api = protection['url']\n self.strict = protection['strict']\n self.original_contexts = protection['contexts']\n self.contexts_url = protection['contexts_url']\n\n @decorators.requires_auth\n def add_contexts(self, contexts):\n \"\"\"Add contexts to the existing list of required contexts.\n\n See:\n https://developer.github.com/v3/repos/branches/#add-required-status-checks-contexts-of-protected-branch\n\n :param list contexts:\n The list of contexts to append to the existing list.\n :returns:\n The updated list of contexts.\n :rtype:\n list\n \"\"\"\n resp = self._post(self.contexts_url, json=contexts)\n json = self._json(resp, 200)\n return json\n\n @decorators.requires_auth\n def contexts(self):\n \"\"\"Retrieve the list of contexts required as status checks.\n\n See:\n https://developer.github.com/v3/repos/branches/#list-required-status-checks-contexts-of-protected-branch\n\n :returns:\n A list of context names which are required status checks.\n :rtype:\n list\n \"\"\"\n resp = self._get(self.contexts_url)\n json = self._json(resp, 200)\n return json\n\n @decorators.requires_auth\n def remove_contexts(self, contexts):\n \"\"\"Remove the specified contexts from the list of required contexts.\n\n See:\n https://developer.github.com/v3/repos/branches/#remove-required-status-checks-contexts-of-protected-branch\n\n :param list contexts:\n The context names to remove\n :returns:\n The updated list of contexts required as status checks.\n :rtype:\n list\n \"\"\"\n resp = self._delete(self.contexts_url, json=contexts)\n json = self._json(resp, 200)\n return json\n\n @decorators.requires_auth\n def replace_contexts(self, contexts):\n \"\"\"Replace the existing contexts required as status checks.\n\n See:\n https://developer.github.com/v3/repos/branches/#replace-required-status-checks-contexts-of-protected-branch\n\n :param list contexts:\n The names of the contexts to be required as status checks\n :returns:\n The updated list of contexts required as status checks.\n :rtype:\n list\n \"\"\"\n resp = self._put(self.contexts_url, json=contexts)\n json = self._json(resp, 200)\n return json\n\n @decorators.requires_auth\n def update(self, strict=None, contexts=None):\n \"\"\"Update required status checks for the branch.\n\n This requires admin or owner permissions to the repository and\n branch protection to be enabled.\n\n .. seealso::\n\n `API docs`_\n Descrption of how to update the required status checks.\n\n :param bool strict:\n Whether this should be strict protection or not.\n :param list contexts:\n A list of context names that should be required.\n :returns:\n A new instance of this class with the updated information\n :rtype:\n :class:`~github3.repos.branch.ProtectionRequiredStatusChecks`\n\n\n .. links\n .. _API docs:\n https://developer.github.com/v3/repos/branches/#update-required-status-checks-of-protected-branch\n \"\"\"\n update_data = {}\n if strict is not None:\n update_data['strict'] = strict\n if contexts is not None:\n update_data['contexts'] = contexts\n if update_data:\n resp = self._patch(self.url, json=update_data)\n json = self._json(resp, 200)\n return ProtectionRequiredStatusChecks(json, self)\n\n @decorators.requires_auth\n def delete(self):\n \"\"\"Remove required status checks from this branch.\n\n See:\n https://developer.github.com/v3/repos/branches/#remove-required-status-checks-of-protected-branch\n\n :returns:\n True if successful, False otherwise\n :rtype:\n bool\n \"\"\"\n resp = self._delete(self.url)\n return self._boolean(resp, 204, 404)\n","sub_path":"drf_venv/lib/python3.5/site-packages/github3/repos/branch.py","file_name":"branch.py","file_ext":"py","file_size_in_byte":18630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"117458719","text":"import numpy as np\r\n\r\nimport cv2\r\nimport imutils\r\nfrom keras.models import load_model\r\nfrom keras.preprocessing.image import img_to_array\r\n\r\nface_cascade_path = '../Model/haarcascade_frontalface_default.xml'\r\nemotion_model_path = '../Model/_mini_XCEPTION.58-0.66.hdf5'\r\n\r\nface_cascade = cv2.CascadeClassifier(face_cascade_path)\r\nemotion_classifier = load_model(emotion_model_path, compile=False)\r\nEMOTIONS = [\"angry\", \"disgust\", \"scared\",\r\n \"happy\", \"sad\", \"surprised\", \"neutral\"]\r\n\r\ncam = cv2.VideoCapture(0)\r\n\r\nwhile True:\r\n ret, frame = cam.read()\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n faces = face_cascade.detectMultiScale(\r\n gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)\r\n # frameClone = frame.copy()\r\n for (x, y, w, h) in faces:\r\n roi_gray = gray[y:y+h, x:x+w]\r\n cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)\r\n # Extract the ROI of the face from the grayscale image, resize it to a fixed 28x28 pixels, and then prepare\r\n # the ROI for classification via the CNN\r\n roi = cv2.resize(roi_gray, (48, 48))\r\n roi = roi.astype(\"float\") / 255.0\r\n roi = img_to_array(roi)\r\n roi = np.expand_dims(roi, axis=0)\r\n preds = emotion_classifier.predict(roi)[0]\r\n emotion_probability = np.max(preds)\r\n label = EMOTIONS[preds.argmax()]\r\n # print(label)\r\n cv2.putText(frame, label, (x, y),\r\n cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\r\n for (i, (emotion, prob)) in enumerate(zip(EMOTIONS, preds)):\r\n # construct the label text\r\n text = \"{}: {:.2f}%\".format(emotion, prob * 100)\r\n # print(text)\r\n cv2.imshow('Emotion detection', frame)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\ncam.release()\r\ncv2.destroyAllWindows()\r\n","sub_path":"EMotions/Scripts/real_time_video.py","file_name":"real_time_video.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"493551081","text":"from string import letters\n\n\ndef rollerCoaster(text):\n new = ''\n counter = 0\n for i in text:\n if i in letters and counter == 0:\n new += i.upper()\n counter += 1\n elif i in letters and counter == 1:\n new += i.lower()\n counter -= 1\n else:\n new += i\n return new\n","sub_path":"rollerCoaster/rollerCoaster.py","file_name":"rollerCoaster.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"467261781","text":"\"\"\"\nUsage:\n task.py [options]\n\nOptions:\n --mode= train/evaluate/predict [default: train]\n --project= name of the GCP project\n --bucket= GCS bucket\n\n --schema_path= path to schema json in GCS [default: None]\n --brand_vocab= path to brand vocabulary file [default: 'brand_vocab.csv']\n --train_data= path to train data\n --dev_data= path to dev (validation) data\n --test_data= path to test data (for evaluation, or prediction)\n\n --model_type= model to train [default: WD]\n --feature_selec= features to exclude (from 1 to 7) [default: None]\n --train_epochs= number of epochs to train for [default: 1]\n --batch_size= batch size while training [default: 1024]\n --learning_rate= learning rate while training [default: 0.01]\n --optimizer= GD optimizer [default: Adam]\n --dropout= dropout fraction [default: 0.2]\n --hidden_units= hidden units of DNN [default: '128,64']\n\n --n_trees= number of trees [default: 100]\n --max_depth= maximum depth of BT model [default: 6]\n\n --early_stopping stop training early if no decrease in loss over specified number of steps\n --cloud running jobs on AI Platform\n --job-dir= working directory for models and checkpoints [default: 'model']\n\n\"\"\"\nimport argparse\nimport ast\nimport datetime\nimport json\nimport os\nimport subprocess\nimport sys\nimport time\n\nimport tensorflow as tf\n\n# local or AI Platform training\ntry:\n from utils import (\n export_train_results, export_eval_results, get_schema, make_csv_cols)\nexcept:\n from trainer.utils import (\n export_train_results, export_eval_results, get_schema, make_csv_cols)\n\nRANDOM_SEED = 42\n\n\ndef get_args():\n \"\"\"\n Parse command-line arguments\n \"\"\"\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--mode', type=str, default='train', help='{train, predict, evaluate}')\n parser.add_argument('--project', type=str, default='example-project')\n parser.add_argument('--bucket', type=str, default='example-bucket')\n parser.add_argument('--schema_path', type=str, default='schema.json')\n parser.add_argument('--brand_vocab', type=str, default='brand_vocab.csv')\n\n parser.add_argument('--train_data', type=str, default='trainData/*.csv')\n parser.add_argument('--dev_data', type=str, default='devData/*.csv')\n parser.add_argument('--test_data', type=str, default='testData/*.csv')\n\n parser.add_argument('--model_type', type=str, default='WD', help='{DNN, WD, BT}')\n parser.add_argument('--feature_selec', type=str, default=None)\n parser.add_argument('--train_epochs', type=int, default=1)\n parser.add_argument('--batch_size', type=int, default=1024)\n parser.add_argument('--learning_rate', type=float, default=0.01)\n parser.add_argument('--optimizer', type=str, default='Adam', help='{ProximalAdagrad, Adagrad, Adam}')\n parser.add_argument('--dropout', type=float, default=0.2)\n parser.add_argument('--hidden_units', type=str, default='128,64')\n\n parser.add_argument('--n_trees', type=int, default=100)\n parser.add_argument('--max_depth', type=int, default=6)\n\n parser.add_argument('--cloud', dest='cloud', action='store_true')\n parser.add_argument('--early_stopping', dest='early_stopping', action='store_true')\n parser.add_argument('--job-dir', type=str, default='model')\n\n return parser.parse_known_args()\n\n\nCOLUMNS_TYPE_DICT = {\n 'STRING': tf.string,\n 'INTEGER': tf.int64,\n 'FLOAT': tf.float32,\n 'NUMERIC': tf.float32,\n 'BOOLEAN': tf.bool,\n 'TIMESTAMP': None,\n 'RECORD': None\n}\n\nFLAGS, unparsed = get_args()\nSCHEMA = get_schema(FLAGS)\nLABEL = 'label'\nCSV_COLUMNS, CSV_COLUMN_DEFAULTS = make_csv_cols(SCHEMA)\n\n\ndef input_fn(path_dir, epochs, batch_size=1024, shuffle=True, skip_header_lines=1):\n \"\"\"\n Generation of features and labels for Estimator\n :param path_dir: path to directory containing data\n :param epochs: number of times to repeat\n :param batch_size: stacks n consecutive elements of dataset into single element\n :param skip_header_lines: lines to skip if header present\n :return: features, labels\n \"\"\"\n\n def parse_csv(records):\n \"\"\"\n :param records: A Tensor of type string - each string is a record/row in the CSV\n :return: features, labels\n \"\"\"\n columns = tf.decode_csv(\n records=records, record_defaults=CSV_COLUMN_DEFAULTS)\n features = dict(zip(CSV_COLUMNS, columns))\n\n # forwarding features for customer ID and brand\n features['customer_identity'] = tf.identity(features['customer_id'])\n features['brand_identity'] = tf.identity(features['brand'])\n\n try:\n labels = features.pop(LABEL)\n return features, labels\n except KeyError:\n return features, []\n\n file_list = tf.gfile.Glob(path_dir)\n dataset = tf.data.Dataset.from_tensor_slices(file_list)\n # shuffle file list\n if shuffle:\n dataset = dataset.shuffle(50, seed=RANDOM_SEED)\n\n # read lines of files as row strings, then shuffle and batch\n f = lambda filepath: tf.data.TextLineDataset(filepath).skip(skip_header_lines)\n dataset = dataset.interleave(f, cycle_length=8, block_length=8)\n\n if shuffle:\n dataset = dataset.shuffle(buffer_size=100000, seed=RANDOM_SEED)\n\n dataset = dataset.batch(batch_size) \\\n .map(parse_csv, num_parallel_calls=8) \\\n .repeat(epochs)\n\n iterator = dataset.make_one_shot_iterator()\n features, labels = iterator.get_next()\n\n return features, labels\n\n\ndef serving_input_receiver_fn():\n \"\"\"\n Build the serving inputs during online prediction\n :return: ServingInputReceiver\n \"\"\"\n raw_features = dict()\n INPUT = [field for field in SCHEMA if field['name'] not in [LABEL]]\n\n for field in INPUT:\n dtype = COLUMNS_TYPE_DICT[field['type']]\n raw_features[field['name']] = tf.placeholder(\n shape=[None], dtype=dtype)\n\n features = raw_features.copy()\n features['customer_identity'] = tf.identity(features['customer_id'])\n features['brand_identity'] = tf.identity(features['brand'])\n\n return tf.estimator.export.ServingInputReceiver(features,\n raw_features)\n\n\ndef metrics(labels, predictions):\n \"\"\"\n Define evaluation metrics\n :return: dict of metrics\n \"\"\"\n return {\n 'accuracy': tf.metrics.accuracy(labels, predictions['class_ids']),\n 'precision': tf.metrics.precision(labels, predictions['class_ids']),\n 'recall': tf.metrics.recall(labels, predictions['class_ids']),\n 'f1': tf.contrib.metrics.f1_score(labels, predictions['class_ids']),\n 'auc': tf.metrics.auc(labels, predictions['logistic'])\n }\n\n\ndef build_feature_columns():\n \"\"\"\n Build feature columns as input to the model\n :return: feature column tensors\n \"\"\"\n\n # most of the columns are numeric columns\n exclude = ['customer_id', 'brand', 'promo_sensitive', 'label']\n\n if FLAGS.feature_selec:\n feature_dict = {\n 1: 'returned',\n 2: 'chains',\n 3: 'max_sale_quantity',\n 4: 'overall',\n 5: '12m',\n 6: '6m',\n 7: '3m'\n }\n terms = [feature_dict[key] for key in ast.literal_eval(FLAGS.feature_selec)]\n feature_list = [col for col in CSV_COLUMNS if any(word in col for word in terms)]\n exclude += feature_list\n\n numeric_column_names = [col for col in CSV_COLUMNS if col not in exclude]\n numeric_columns = [tf.feature_column.numeric_column(col) for col in numeric_column_names]\n\n # promo sensitive\n promo_sensitive = tf.feature_column.categorical_column_with_identity(\n key='promo_sensitive', num_buckets=2)\n\n # customer id and brand hash buckets\n customer_id = tf.feature_column.categorical_column_with_hash_bucket(\n key='customer_id', hash_bucket_size=100000)\n brand = tf.feature_column.categorical_column_with_vocabulary_file(\n key='brand', vocabulary_file=FLAGS.brand_vocab)\n\n # bucketizing columns\n seasonality_names = [col for col in numeric_columns if 'seasonality' in col.key]\n brand_seasonality = [tf.feature_column.bucketized_column(\n col, boundaries=[3, 6, 9, 12]) for col in seasonality_names]\n\n aov_column_names = [col for col in numeric_columns if 'aov' in col.key]\n aov_columns = [tf.feature_column.bucketized_column(\n col, boundaries=[0, 3, 6, 9, 12, 15, 30, 50, 100]) for col in aov_column_names]\n\n days_1m_names = [col for col in numeric_columns if 'days_shopped_1m' in col.key]\n days_3m_names = [col for col in numeric_columns if 'days_shopped_3m' in col.key]\n days_6m_names = [col for col in numeric_columns if 'days_shopped_6m' in col.key]\n days_12m_names = [col for col in numeric_columns if 'days_shopped_12m' in col.key]\n\n days_1m = [tf.feature_column.bucketized_column(\n col, boundaries=[0, 2, 5, 10, 20, 30]) for col in days_1m_names]\n days_3m = [tf.feature_column.bucketized_column(\n col, boundaries=[0, 30, 60, 90]) for col in days_3m_names]\n days_6m = [tf.feature_column.bucketized_column(\n col, boundaries=[0, 60, 120, 180]) for col in days_6m_names]\n days_12m = [tf.feature_column.bucketized_column(\n col, boundaries=[0, 90, 180, 270, 360]) for col in days_12m_names]\n\n quantity_column_names = [col for col in numeric_columns if any(\n word in col.key for word in ['quantity', 'distinct_brands'])]\n quantity_columns = [tf.feature_column.bucketized_column(\n col, boundaries=[0, 5, 10, 20, 50, 100, 500, 1000]) for col in quantity_column_names]\n\n product_column_names = [col for col in numeric_columns if 'products' in col.key]\n product_columns = [tf.feature_column.bucketized_column(\n col, boundaries=[0, 5, 10, 20, 50, 100]) for col in product_column_names]\n\n cat_column_names = [col for col in numeric_columns if 'category' in col.key]\n cat_columns = [tf.feature_column.bucketized_column(\n col, boundaries=[0, 2, 5, 10, 20, 30, 50, 100]) for col in cat_column_names]\n\n customer_embeddings = tf.feature_column.embedding_column(customer_id, dimension=18)\n brand_embeddings = tf.feature_column.embedding_column(brand, dimension=6)\n\n deep_columns = numeric_columns + [customer_embeddings, brand_embeddings]\n tree_columns = (\n brand_seasonality + aov_columns + days_1m + days_3m + days_6m +\n days_12m + quantity_columns + product_columns + cat_columns)\n wide_columns = [promo_sensitive] + tree_columns\n\n return wide_columns, deep_columns, tree_columns\n\n\ndef initialize_optimizer():\n \"\"\"\n Define GD optimizer\n :return: optimizer\n \"\"\"\n optimizers = {\n 'Adagrad': tf.train.AdagradOptimizer(FLAGS.learning_rate),\n 'ProximalAdagrad': tf.train.ProximalAdagradOptimizer(FLAGS.learning_rate),\n 'Adam': tf.train.AdamOptimizer(FLAGS.learning_rate)\n }\n\n if optimizers.get(FLAGS.optimizer):\n return optimizers[FLAGS.optimizer]\n\n raise Exception('Optimizer {} not recognised'.format(FLAGS.optimizer))\n\n\ndef initialize_estimator(model_checkpoints):\n \"\"\"\n Define estimator\n :return: estimator\n \"\"\"\n optimizer = initialize_optimizer()\n run_config = tf.estimator.RunConfig(\n tf_random_seed=RANDOM_SEED,\n save_checkpoints_steps=100,\n save_summary_steps=100)\n\n wide_columns, deep_columns, tree_columns = build_feature_columns()\n\n if FLAGS.model_type == 'DNN':\n return tf.estimator.DNNClassifier(\n n_classes=2,\n feature_columns=deep_columns,\n activation_fn=tf.nn.relu,\n optimizer=optimizer,\n hidden_units=FLAGS.hidden_units.split(','),\n dropout=FLAGS.dropout,\n batch_norm=True,\n model_dir=model_checkpoints,\n config=run_config)\n elif FLAGS.model_type == 'WD':\n return tf.estimator.DNNLinearCombinedClassifier(\n n_classes=2,\n linear_feature_columns=wide_columns,\n linear_optimizer='Ftrl',\n dnn_feature_columns=deep_columns,\n dnn_optimizer=optimizer,\n dnn_hidden_units=FLAGS.hidden_units.split(','),\n dnn_activation_fn=tf.nn.relu,\n dnn_dropout=FLAGS.dropout,\n batch_norm=True,\n model_dir=model_checkpoints,\n config=run_config)\n elif FLAGS.model_type == 'BT':\n n_batches = 500\n return tf.estimator.BoostedTreesClassifier(\n n_classes=2,\n n_batches_per_layer=n_batches,\n feature_columns=tree_columns,\n learning_rate=FLAGS.learning_rate,\n n_trees=FLAGS.n_trees,\n max_depth=FLAGS.max_depth,\n model_dir=model_checkpoints,\n config=run_config)\n\n raise Exception(\n 'Model type {} not recognised - choose from DNN, WD or BT.'.format(\n FLAGS.model_type))\n\n\ndef main(unused_argv):\n tf.logging.set_verbosity(tf.logging.INFO)\n\n model_checkpoints = os.path.join(FLAGS.job_dir, 'model')\n model_serving = os.path.join(FLAGS.job_dir, 'serving')\n\n if not FLAGS.cloud:\n timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%d_%H-%M-%S')\n model_checkpoints = model_checkpoints + '_{}'.format(timestamp)\n model_serving = model_serving + '_{}'.format(timestamp)\n\n trial = json.loads(os.environ.get('TF_CONFIG', '{}')).get('task', {}).get(\n 'trial', '')\n\n if not trial:\n trial = 1\n\n model_checkpoints = os.path.join(model_checkpoints, str(trial))\n model_serving = os.path.join(model_serving, str(trial))\n\n estimator = initialize_estimator(model_checkpoints=model_checkpoints)\n estimator = tf.contrib.estimator.add_metrics(estimator, metrics)\n estimator = tf.contrib.estimator.forward_features(\n estimator, keys=['customer_identity', 'brand_identity'])\n\n # train / evaluate / predict\n\n if FLAGS.mode == \"train\":\n start_time = time.time()\n\n # stop if loss does not decrease within given max steps\n if FLAGS.early_stopping:\n early_stopping = tf.contrib.estimator.stop_if_no_decrease_hook(\n estimator, metric_name='loss', max_steps_without_decrease=1000)\n hooks = [early_stopping]\n else:\n hooks = None\n\n results = tf.estimator.train_and_evaluate(\n estimator,\n tf.estimator.TrainSpec(\n input_fn=lambda: input_fn(\n path_dir=FLAGS.train_data,\n epochs=FLAGS.train_epochs,\n shuffle=True,\n batch_size=FLAGS.batch_size),\n hooks=hooks\n ),\n tf.estimator.EvalSpec(\n input_fn=lambda: input_fn(\n path_dir=FLAGS.dev_data,\n epochs=1,\n shuffle=False,\n batch_size=FLAGS.batch_size\n ),\n steps=1000,\n throttle_secs=60\n )\n )\n\n duration = time.time() - start_time\n\n print(\"Training time: {} seconds / {} minutes\".format(\n round(duration, 2), round((duration/60.0), 2)))\n\n # export model for serving\n estimator.export_savedmodel(export_dir_base=model_serving,\n serving_input_receiver_fn=serving_input_receiver_fn)\n\n # export model settings (add results from train_and_evaluate)\n if results:\n results = results[0]\n else:\n results = {}\n results['duration'] = duration\n results['checkpoints_dir'] = model_checkpoints\n\n export_train_results(FLAGS, trial, results)\n\n # use for local predictions on a test set - for batch scoring use AI Platform predict\n elif FLAGS.mode == 'predict':\n predictions = estimator.predict(\n input_fn=lambda: input_fn(\n path_dir=FLAGS.test_data,\n shuffle=False,\n epochs=1,\n batch_size=FLAGS.batch_size\n ),\n checkpoint_path=tf.train.latest_checkpoint(FLAGS.job_dir))\n\n timestamp = datetime.datetime.utcnow().strftime('%Y_%m_%d_%H_%M_%S')\n file_name = 'predictions_{}.json'.format(timestamp)\n output_path = os.path.join(FLAGS.job_dir, file_name)\n\n with open(output_path, 'w') as json_output:\n for p in predictions:\n results = {\n 'customer_id': p['customer_identity'].decode('utf-8'),\n 'brand': p['brand_identity'].decode('utf-8'),\n 'predicted_label': int(p['class_ids'][0]),\n 'logistic': float(p['logistic'][0])\n }\n\n json_output.write(json.dumps(results, ensure_ascii=False) + '\\n')\n\n gcs_command = 'gsutil -m cp -r ' + output_path + ' gs://{}/evaluation/{}'.format(\n FLAGS.bucket, file_name)\n subprocess.check_output(gcs_command.split())\n\n bq_schema = 'logistic:FLOAT,predicted_label:INTEGER,customer_id:STRING,brand:STRING'\n bq_command = ('bq --location=EU load --source_format=NEWLINE_DELIMITED_JSON propensity_dataset.{} '\n 'gs://{}/evaluation/{} {}').format(\n file_name.replace('.json', ''), FLAGS.bucket, file_name, bq_schema\n )\n subprocess.check_output(bq_command.split())\n\n # use for evaluation on a test set\n elif FLAGS.mode == 'evaluate':\n\n results = estimator.evaluate(\n input_fn=lambda: input_fn(\n path_dir=FLAGS.test_data,\n epochs=1,\n shuffle=False,\n batch_size=FLAGS.batch_size\n ),\n checkpoint_path=tf.train.latest_checkpoint(FLAGS.job_dir)\n )\n\n export_eval_results(FLAGS, trial, results)\n\n else:\n print('Unrecognised mode {}'.format(FLAGS.mode))\n\n\nif __name__ == '__main__':\n tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)\n","sub_path":"ai-platform/package/trainer/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":18224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"160827718","text":"import string\n\n\ndef rank(st, we, n):\n if not st:\n return 'No participants'\n elif n > len(st.split(',')):\n return 'Not enough participants'\n\n alpha = string.ascii_lowercase\n names = dict(zip(st.split(','), we))\n\n for x in names:\n calc = (len(x) + sum(alpha.index(ch.lower()) + 1 for ch in x)) * names[x]\n names[x] = calc\n\n return sorted(sorted(names), key=names.get, reverse=True)[n - 1]","sub_path":"codewars/prize_draw.py","file_name":"prize_draw.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"604702333","text":"import sys\nimport os\nimport geocoder\n\n# Build spark session\nimport findspark\n\n# spark location on namenode server\nfindspark.init(\"/usr/hdp/current/spark2-client\")\nimport pyspark\nconf = pyspark.SparkConf().setAll([('spark.app.name', 'guobiao_tsp_tbls.trip_map'), # App Name\n ('spark.master', 'yarn'), # spark run mode: locally or remotely\n ('spark.submit.deployMode', 'client'), # deploy in yarn-client or yarn-cluster\n ('spark.executor.memory', '10g'), # memory allocated for each executor\n #('spark.memory.fraction', '0.7'),\n ('spark.executor.cores', '3'), # number of cores for each executor\n ('spark.executor.instances', '5'), # number of executors in total\n ('spark.driver.maxResultSize', '5g'), # Result size is large, need to increase from default of 1g\n ('spark.yarn.am.memory', '10g')]) # memory for spark driver (application master)\nsc = pyspark.SparkContext.getOrCreate(conf=conf)\n\nfrom pyspark.sql import HiveContext\n\n# Hive context\nhc = HiveContext(sc)\n\ndef GenerateTrips(sc):\n from pyspark.sql import HiveContext\n \n # Hive context\n hc = HiveContext(sc) \n \n sql = 'DROP TABLE IF EXISTS guobiao_tsp_tbls.starts_latest PURGE' \n hc.sql(\"\"\"{}\"\"\".format(sql))\n\n sql = 'create table guobiao_tsp_tbls.starts_latest as select vin, veh_odo, max(ts_seconds) as ts_seconds from \\\n guobiao_tsp_tbls.starts_redundant group by vin, veh_odo'\n hc.sql(\"\"\"{}\"\"\".format(sql))\n\n sql = 'DROP TABLE IF EXISTS guobiao_tsp_tbls.starts PURGE' \n hc.sql(\"\"\"{}\"\"\".format(sql))\n\n sql = 'create table guobiao_tsp_tbls.starts as select starts_redundant.* from \\\n guobiao_tsp_tbls.starts_redundant inner join guobiao_tsp_tbls.starts_latest \\\n on starts_redundant.vin = starts_latest.vin and starts_redundant.veh_odo == starts_latest.veh_odo and starts_redundant.ts_seconds = starts_latest.ts_seconds'\n hc.sql(\"\"\"{}\"\"\".format(sql))\n\n \n sql = 'DROP TABLE IF EXISTS guobiao_tsp_tbls.ends_latest PURGE' \n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'create table guobiao_tsp_tbls.ends_latest as select vin, veh_odo, min(ts_seconds) as ts_seconds \\\n from guobiao_tsp_tbls.ends_redundant group by vin, veh_odo'\n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'DROP TABLE IF EXISTS guobiao_tsp_tbls.ends PURGE' \n hc.sql(\"\"\"{}\"\"\".format(sql))\n\n sql = 'create table guobiao_tsp_tbls.ends as select ends_redundant.* \\\n from guobiao_tsp_tbls.ends_redundant inner join guobiao_tsp_tbls.ends_latest \\\n on ends_redundant.vin = ends_latest.vin and ends_redundant.veh_odo == ends_latest.veh_odo \\\n and ends_redundant.ts_seconds = ends_latest.ts_seconds'\n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'drop table if exists guobiao_tsp_tbls.trip_candidates purge' \n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'create table guobiao_tsp_tbls.trip_candidates as select starts.vin, starts.loc_lat as start_loc_lat, starts.loc_lon as start_loc_lon, \\\n from_utc_timestamp(to_utc_timestamp(from_unixtime(starts.ts_seconds), \"America/Los_Angeles\"), \"Asia/Shanghai\") as start_time, \\\n starts.day as start_day, ends.loc_lat as end_loc_lat, ends.loc_lon as end_loc_lon, from_utc_timestamp(to_utc_timestamp(from_unixtime(ends.ts_seconds), \"America/Los_Angeles\"), \"Asia/Shanghai\") as end_time, \\\n ends.veh_odo - starts.veh_odo as distance \\\n from guobiao_tsp_tbls.starts inner join guobiao_tsp_tbls.ends on starts.vin = ends.vin \\\n where ends.veh_odo >= starts.veh_odo and ends.ts_seconds > starts.ts_seconds and ends.ts_seconds - starts.ts_seconds < 50000 and ends.veh_odo - starts.veh_odo < 1000'\n hc.sql(\"\"\"{}\"\"\".format(sql))\n\n sql = 'drop table if exists guobiao_tsp_tbls.trip_distance purge' \n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'create table guobiao_tsp_tbls.trip_distance as select vin, start_time, min(distance) as distance \\\n from guobiao_tsp_tbls.trip_candidates group by vin, start_time'\n hc.sql(\"\"\"{}\"\"\".format(sql))\n\n sql = 'drop table if exists ubi.trips purge' \n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'create table ubi.trips as select distinct trip_candidates.* \\\n from guobiao_tsp_tbls.trip_candidates inner join guobiao_tsp_tbls.trip_distance \\\n on trip_candidates.vin = trip_distance.vin and trip_candidates.start_time = trip_distance.start_time and trip_candidates.distance = trip_distance.distance \\\n where trip_candidates.distance % 5 = 0 and trip_distance.distance % 5 = 0'\n hc.sql(\"\"\"{}\"\"\".format(sql))\n\n sql = 'insert into table ubi.trips select distinct trip_candidates.* \\\n from guobiao_tsp_tbls.trip_candidates inner join guobiao_tsp_tbls.trip_distance \\\n on trip_candidates.vin = trip_distance.vin and trip_candidates.start_time = trip_distance.start_time and trip_candidates.distance = trip_distance.distance \\\n where trip_candidates.distance % 5 = 1 and trip_distance.distance % 5 = 1'\n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'insert into table ubi.trips select distinct trip_candidates.* \\\n from guobiao_tsp_tbls.trip_candidates inner join guobiao_tsp_tbls.trip_distance \\\n on trip_candidates.vin = trip_distance.vin and trip_candidates.start_time = trip_distance.start_time and trip_candidates.distance = trip_distance.distance \\\n where trip_candidates.distance % 5 = 2 and trip_distance.distance % 5 = 2'\n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'insert into table ubi.trips select distinct trip_candidates.* \\\n from guobiao_tsp_tbls.trip_candidates inner join guobiao_tsp_tbls.trip_distance \\\n on trip_candidates.vin = trip_distance.vin and trip_candidates.start_time = trip_distance.start_time and trip_candidates.distance = trip_distance.distance \\\n where trip_candidates.distance % 5 = 3 and trip_distance.distance % 5 = 3'\n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'insert into table ubi.trips select distinct trip_candidates.* \\\n from guobiao_tsp_tbls.trip_candidates inner join guobiao_tsp_tbls.trip_distance \\\n on trip_candidates.vin = trip_distance.vin and trip_candidates.start_time = trip_distance.start_time and trip_candidates.distance = trip_distance.distance \\\n where trip_candidates.distance % 5 = 4 and trip_distance.distance % 5 = 4'\n hc.sql(\"\"\"{}\"\"\".format(sql)) \n \n sql = 'drop table if exists ubi.trip_distance_complete purge' \n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'create table ubi.trip_distance_complete as select vin, end_time, min(start_time) as start_time \\\n from ubi.trips group by vin, end_time'\n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n print('End')\n\n\n\n# def BatchGenerateTrips(sc):\n# \n# sql = 'DROP TABLE IF EXISTS guobiao_tsp_tbls.starts_redundant PURGE' \n# hc.sql(\"\"\"{}\"\"\".format(sql))\n# \n# sql = 'create table guobiao_tsp_tbls.starts_redundant as select vin, loc_lat, loc_lon, bigint(ts / 1000) as ts_seconds, day, veh_odo from \\\n# guobiao_tsp_tbls.guobiao_raw_orc where veh_st = 1'\n# hc.sql(\"\"\"{}\"\"\".format(sql))\n# \n# sql = 'DROP TABLE IF EXISTS guobiao_tsp_tbls.ends_redundant PURGE' \n# hc.sql(\"\"\"{}\"\"\".format(sql))\n# \n# sql = 'create table guobiao_tsp_tbls.ends_redundant as select vin, loc_lat, loc_lon, bigint(ts / 1000) as ts_seconds, day, veh_odo \\\n# from guobiao_tsp_tbls.guobiao_raw_orc where veh_st = 2'\n# hc.sql(\"\"\"{}\"\"\".format(sql))\n# \n# GenerateTrips(sc)\n# \n# sql = 'drop table if exists ubi.trips_complete purge' \n# hc.sql(\"\"\"{}\"\"\".format(sql))\n# \n# sql = 'create table ubi.trips_complete as select distinct trips.* \\\n# from ubi.trips inner join ubi.trip_distance_complete \\\n# on trips.vin = trip_distance_complete.vin and trips.start_time = trip_distance_complete.start_time and trips.end_time = trip_distance_complete.end_time'\n\n\ndef BatchGenerateTrips(sc):\n \n sql = 'drop table if exists ubi.trips_complete purge' \n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'create table ubi.trips_complete as select distinct trips.* \\\n from ubi.trips inner join ubi.trip_distance_complete \\\n on trips.vin = trip_distance_complete.vin and trips.start_time = trip_distance_complete.start_time and trips.end_time = trip_distance_complete.end_time \\\n where int(trips.start_time) % 5 = 0'\n \n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'insert into table ubi.trips_complete select distinct trips.* \\\n from ubi.trips inner join ubi.trip_distance_complete \\\n on trips.vin = trip_distance_complete.vin and trips.start_time = trip_distance_complete.start_time and trips.end_time = trip_distance_complete.end_time \\\n where int(trips.start_time) % 5 = 1'\n \n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'insert into table ubi.trips_complete select distinct trips.* \\\n from ubi.trips inner join ubi.trip_distance_complete \\\n on trips.vin = trip_distance_complete.vin and trips.start_time = trip_distance_complete.start_time and trips.end_time = trip_distance_complete.end_time \\\n where int(trips.start_time) % 5 = 2'\n\n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'insert into table ubi.trips_complete select distinct trips.* \\\n from ubi.trips inner join ubi.trip_distance_complete \\\n on trips.vin = trip_distance_complete.vin and trips.start_time = trip_distance_complete.start_time and trips.end_time = trip_distance_complete.end_time \\\n where int(trips.start_time) % 5 = 3'\n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'insert into table ubi.trips_complete select distinct trips.* \\\n from ubi.trips inner join ubi.trip_distance_complete \\\n on trips.vin = trip_distance_complete.vin and trips.start_time = trip_distance_complete.start_time and trips.end_time = trip_distance_complete.end_time \\\n where int(trips.start_time) % 5 = 4'\n\n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n\ndef GenerateTodayTrips(sc, n):\n from datetime import datetime, date, timedelta\n start_date = date.today() - timedelta(n)\n end_date = date.today()\n\n sql = 'DROP TABLE IF EXISTS ubi.end_time PURGE' \n hc.sql(\"\"\"{}\"\"\".format(sql)) \n sql=\"\"\"create table ubi.end_time as select vin, max(bigint(ts / 1000)) as lasttime from guobiao_tsp_tbls.guobiao_raw_orc where day='{0}' and veh_st = 2 group by vin\"\"\".format(start_date) \n hc.sql(\"\"\"{}\"\"\".format(sql))\n sql = 'DROP TABLE IF EXISTS guobiao_tsp_tbls.starts_redundant PURGE' \n hc.sql(\"\"\"{}\"\"\".format(sql))\n\n sql = \"\"\"create table guobiao_tsp_tbls.starts_redundant as select vin, loc_lat, loc_lon, bigint(ts / 1000) as ts_seconds, day, veh_odo from \\\n guobiao_tsp_tbls.guobiao_raw_orc inner join ubi.end_time on guobiao_tsp_tbls.guobiao_raw_orc.vin = ubi.end_time.vin where day>='{0}' and veh_st = 1 and bigint(ts / 1000) > ubi.end_time.lasttime \"\"\".format(start_date)\n hc.sql(\"\"\"{}\"\"\".format(sql))\n\n sql = 'DROP TABLE IF EXISTS guobiao_tsp_tbls.ends_redundant PURGE' \n hc.sql(\"\"\"{}\"\"\".format(sql))\n\n sql = \"\"\"create table guobiao_tsp_tbls.ends_redundant as select vin, loc_lat, loc_lon, bigint(ts / 1000) as ts_seconds, day, veh_odo \\\n from guobiao_tsp_tbls.guobiao_raw_orc where day='{0}' and veh_st = 2\"\"\".format(end_date)\n hc.sql(\"\"\"{}\"\"\".format(sql))\n \n sql = 'DROP TABLE IF EXISTS ubi.end_time PURGE' \n sql=\"\"\"create table ubi.end_time as select vin, max(end_time) from guobiao_tsp_tbls.guobiao_raw_orc where day='{0}' and veh_st = 2 group by vin\"\"\".format(start_date) \n hc.sql(\"\"\"{}\"\"\".format(sql)) \n \n GenerateTrips(sc)\n \n sql = 'insert into table ubi.trips_complete select distinct trips.* \\\n from ubi.trips inner join ubi.trip_distance_complete \\\n on trips.vin = trip_distance_complete.vin and trips.start_time = trip_distance_complete.start_time and trips.end_time = trip_distance_complete.end_time'\n\n \ndef hive2string(hc, query, colname):\n spark_df = hc.sql(\"\"\"{}\"\"\".format(query))\n row = spark_df.first()\n res = row[colname]\n return res\n\n\ndef hive2pandas(hc, query):\n spark_df = hc.sql(\"\"\"{}\"\"\".format(query))\n # Convert to pandas dataframe\n df = spark_df.toPandas()\n return df\n\ndef hive2csv(hc, query, outfile):\n df = hive2pandas(hc, query)\n df.to_csv(outfile)\n \ndef generateList(hc, start_day):\n tableName = \"ubi.trips_complete\"\n query = \"\"\"SELECT vin, start_time, end_time FROM {} WHERE start_day = '{}'\"\"\".format(tableName, start_day)\n df=hive2pandas(hc, query)\n res={}\n for x in range(len(df)):\n vin=df.iloc[x,0]\n start_time=df.iloc[x,1]\n end_time=df.iloc[x,2]\n temp=(start_time, end_time)\n if not res.has_key(vin):\n res.setdefault(vin,[])\n res[vin].append(temp)\n \n with open('/home/wchen/ubi/log_guobiaoxxxxx.txt', 'w') as outfile:\n for vin in res.keys():\n outfile.write(vin + '\\t' + str(res[vin]) + '\\n')\n return res\n\ndef addLocation(hc, p):\n query = \"\"\"SELECT distinct ROUND(CAST(start_loc_lat as float), 3) as loc_lat, ROUND(CAST(start_loc_lon as float), 3) as loc_lon from ubi.trips_complete union SELECT distinct ROUND(CAST(end_loc_lat as float), 3) as loc_lat, ROUND(CAST(end_loc_lon as float), 3) as loc_lon from ubi.trips_complete\"\"\"\n df=hive2pandas(hc, query)\n with open('/home/wchen/ubi/latlon2location_' + str(p) + '.txt', 'w') as outfile:\n for x in range(len(df)):\n if(int(df.iloc[x,0] * 10) % 10 == p):\n g = geocoder.gaode([df.iloc[x,0], df.iloc[x,1]], method='reverse', key='27522a3d9da8f4e80d6580c80d010d4c')\n adds = g.address\n if g.address is None:\n adds=''\n elif type(g.address)==list:\n adds=str(adds)\n outfile.write('%.3f'%(df.iloc[x,0]) + '\\t' + '%.3f'%(df.iloc[x,1]) + '\\t' + adds.encode('utf-8') + '\\n')\n print('Done with location: ' + p)\n \nif __name__ == \"__main__\":\n#PrepareTodayData(sc) or BatchPrepareData(sc)\n args = sys.argv[1:]\n \n usage_msg = \"\"\"usage:\n \\tfor today: --today \n \\tto run entire history: --all \n \\tfor a start date: -d yyyymmdd or -date yyyymmdd\n \\tto get help: --help\"\"\"\n\n help_msg = \"\"\"Required to specify all days or today trip data.\n Options:\n \\t-today: add today's trip\n \\t--all: run for entire history, e.g. --all\n \\t-d, --date: specify a starting date, e.g. -d 20150118\"\"\"\n if not args:\n print(usage_msg)\n sys.exit(1)\n if args[0] == '--today': # run one day\n if len(args) < 2:\n print('no date provided')\n sys.exit(1)\n if len(args[1]) != 8:\n print('invalid input date: {}'.format(args[1]))\n sys.exit(1)\n #GenerateTodayTrips(sc, 1)\n del args[0]\n elif args[0] == '--all': # run entire history\n #BatchGenerateTrips(sc)\n del args[0]\n elif args[0] in ['-d', '--date']: # run one day\n if len(args) < 2:\n print('no date provided')\n sys.exit(1)\n if len(args[1]) != 8:\n print('invalid input date: {}'.format(args[1]))\n sys.exit(1)\n generateList(hc, args[1])\n del args[0:2]\n elif args[0] == '--help':\n print(help_msg)\n print(usage_msg)\n sys.exit(0)\n elif args[0] == '--location':\n addLocation(hc, 2)\n del args[0]\n else:\n print('invalid option {}'.format(args[0]))\n sys.exit(1)\n # generateList(hc, '20170517')\n","sub_path":"user profile/trip/trip_v3_2.py","file_name":"trip_v3_2.py","file_ext":"py","file_size_in_byte":15370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"326240058","text":"\n\n#calss header\nclass _MOTOWN():\n\tdef __init__(self,): \n\t\tself.name = \"MOTOWN\"\n\t\tself.definitions = [u'a type of popular music that was produced an American record company based in Detroit in the 1960s and 70s']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_motown.py","file_name":"_motown.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"384309562","text":"#Sacar provecho a nuestra documentación.\n\n\"\"\"\nAlmacenamos las funciones dentro de nuestro diccionario, \nposteriormente iteramos los elementos del diccionario \ny en cada iteración imprimimos la documentación\n\"\"\"\n\ndef suma(a, b):\n\t\"\"\"Función suma (documentación)\"\"\"\n\treturn a + b\n\ndef resta(a, b):\n\t\"\"\"Función resta (documentación)\"\"\"\n\treturn a - b\n\nopciones = {'a' : suma, 'b': resta}\n\nprint(\"Ingrese la opción deseada\")\n\nfor opcion, funcion in opciones.items():\n\tmensaje = '{}) {}'.format(opcion, funcion.__doc__)\n\tprint(mensaje)\n\nopcion = input(\"Opción : \")","sub_path":"funciones/documentacion.py","file_name":"documentacion.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"274887947","text":"# https://leetcode.com/problems/binary-tree-level-order-traversal/\n# https://www.jiuzhang.com/solutions/binary-tree-level-order-traversal/#tag-highlight-lang-python\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def levelOrder(self, root: TreeNode) -> List[List[int]]:\n # return self.methodB(root)\n return self.bfs(root)\n\n def bfs(self, root):\n if not root:\n return []\n\n output = []\n from collections import deque\n queue = deque([root])\n while queue:\n level_output = []\n n_items = len(queue)\n for _ in range(n_items):\n node = queue.popleft()\n level_output.append(node.val)\n\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n\n output.append(level_output)\n return output\n\n def methodA(self, root):\n # use the queu method to traverse through the BT\n levels = []\n if not root:\n return levels\n queue = [root]\n lv_cnt = 0\n\n # Loop through levels with BFS\n while len(queue):\n levels.append([])\n lv_len = len(queue)\n\n # empty out the stuff at the same queue while accumulating next level\n for i in range(lv_len):\n node = queue.pop(0)\n levels[lv_cnt].append(node.val)\n\n if node.left is not None:\n queue.append(node.left)\n\n if node.right is not None:\n queue.append(node.right)\n print(levels)\n # update level count\n lv_cnt += 1\n return levels\n\n def methodB(self, root):\n if not root:\n return []\n # Using FIFO method\n levels, queue = [], [root]\n while queue:\n tmp_level = []\n tmp_queue = []\n for node in queue:\n tmp_level.append(node.val)\n for lf in [node.left, node.right]:\n if lf:\n tmp_queue.append(lf)\n levels.append(tmp_level)\n queue = tmp_queue\n return levels\n","sub_path":"leetcode/lc102_Binary_Tree_Level_Order_Traversal.py","file_name":"lc102_Binary_Tree_Level_Order_Traversal.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"536115282","text":"# ====================================================================================== #\n# Pipeline for pivotal voter analysis.\n# Author: Eddie Lee, edlee@santafe.edu\n# ====================================================================================== #\nimport numpy as np\nimport os\nimport pickle\nimport dill\nfrom .utils import *\nfrom .fim import *\n\n\n\ndef pivotal_blocs(X, component_names=None, solve_inverse_kw={}):\n \"\"\"Solve pairwise maxent model and calculate Fisher information matrix and pivotal\n bloc analysis as in paper.\n \n Parameters\n ----------\n X : ndarray\n Each row is a sample from the system.\n component_names : list of strings, None\n \n Returns\n -------\n tuple\n (solved couplings, dict from scipy.optimize.minimize)\n tuple\n (IsingFisherCurvatureMethod2 instance,\n (hess, errorflag, errornorm),\n eigenvalues,\n eigenvectors)\n \"\"\"\n \n import pyutils.pipeline as pipe\n from warnings import warn\n from .influence import pair_asymmetry, block_subspace_eig\n assert X.shape[1]<=18\n assert set(np.unique(X))<=set((-1,1))\n assert np.isclose(X.sum(0), 0).all()\n if component_names is None:\n component_names = [str(i) for i in range(X.shape[1])]\n\n data = {'example':[component_names, X]}\n\n pipe.solve_inverse_on_data(data, **solve_inverse_kw)\n if np.linalg.norm(data['example'][-1]['fun'])>1e-3:\n warn(\"Large numerical error in maxent solution.\")\n\n print(\"Calculating FI...\")\n fimResult = pipe.calculate_fisher_on_pk(data, save=False, fi_method='2')\n \n # extract useful parts\n n = X.shape[1]\n sisj = squareform(pair_corr(data['example'][1])[1])\n couplings = squareform(data['example'][2][n:])\n eigvecs = (np.insert(fimResult['example'][-1][:,0],range(0,n*n,n),0).reshape(n,n),\n np.insert(fimResult['example'][-1][:,1],range(0,n*n,n),0).reshape(n,n))\n pivotalness = np.array([i[0] for i in block_subspace_eig(fimResult['example'][1][0], n-1)[0]])\n pivotalness = pivotalness/np.linalg.norm(pivotalness)\n assert np.linalg.norm(pivotalness.imag)<1e-12\n pivotalness = pivotalness.real\n asymmetry = (pair_asymmetry(fimResult['example'][-1], n, by_voter=True, rank=0),\n pair_asymmetry(fimResult['example'][-1], n, by_voter=True, rank=1))\n\n return sisj, couplings, eigvecs, pivotalness, asymmetry, data['example'][2:], fimResult['example']\n\ndef entropy_estimates(system, method,\n prefix='cache',\n n_boot=10_000,\n Squad_kwargs={}):\n \"\"\"\n Parameters\n ----------\n system : str\n method : str\n prefix : str, 'cache'\n Constructed path will be of form '%s/%s/%s'%(prefix,system,method)\n n_boot : int, 10_000\n\n Returns\n -------\n ndarray\n miCaptured\n ndarray\n Entropy of data.\n ndarray\n Entropy of indpt model.\n ndarray\n Entropy of pairwise fit.\n ndarray\n Ma entropy.\n ndarray\n Quadratic fit.\n \"\"\"\n \n from entropy.estimators import S_ma\n\n path = 'cache/%s/%s'%(system,method)\n\n fname = '%s/data.p'%path\n if os.path.isfile(fname):\n data = pickle.load(open(fname,'rb'))['data']\n\n miCaptured = np.zeros(len(data))\n Sdata = np.zeros(len(data))\n Sind = np.zeros(len(data))\n Spair = np.zeros(len(data))\n Sma = np.zeros(len(data))\n quadfit = []\n\n for i,k in enumerate(list(data.keys())):\n if len(data[k])>2 and (not data[k][-1] is None) and data[k][-1]['success']:\n X, hJ = data[k][1:3]\n assert (X.mean(0)==0).all()\n miCaptured[i], Stuple, quadfit_ = multi_info(X, hJ, n_boot=n_boot, disp=False, **Squad_kwargs)\n quadfit.append(quadfit_)\n Sdata[i], Sind[i], Spair[i] = Stuple\n Sma[i] = S_ma(X)\n\n return miCaptured, Sdata, Sind, Spair, Sma, quadfit\n\ndef check_corr(system, method, orders=range(2,9,2), prefix='cache'):\n \"\"\"\n Parameters\n ----------\n system : str\n method : str\n prefix : str, 'cache'\n Constructed path will be of form '%s/%s/%s'%(prefix,system,method)\n n_boot : int, 10_000\n\n Returns\n -------\n ndarray\n Errors on each kth order correlation coefficient.\n ndarray\n Correlation coefficient of model estimate of correlation by data.\n \"\"\"\n \n import importlib\n\n path = 'cache/%s/%s'%(system,method)\n\n fname = '%s/data.p'%path\n if os.path.isfile(fname):\n data = pickle.load(open(fname,'rb'))['data']\n errs = np.zeros((len(data),len(orders)))\n corr = np.zeros((len(data),len(orders)))\n\n for i,k in enumerate(list(data.keys())):\n if len(data[k])>2 and (not data[k][-1] is None) and data[k][-1]['success']:\n X, hJ = data[k][1:3]\n assert (X.mean(0)==0).all()\n ising = importlib.import_module('coniii.ising_eqn.ising_eqn_%d_sym'%X.shape[1])\n p = ising.p(hJ)\n \n errs[i], corr[i] = check_correlations(X, p, orders)\n return errs, corr\n\ndef solve_inverse_on_data(data, n_cpus=4, potts=False, force_krylov=False):\n \"\"\"Automate solution of inverse problem on data dictionary. Only run on tuples in dict\n that only have two entries (the others presumably have already been solved and the\n solutions saved).\n\n Turns out that Pseudo can help get close enough to the solution when Enumerate is\n having a hard time calculating the gradient accurately. This happens (surprisingly)\n in weird parts of parameter space where the couplings are not necessarily much larger\n than unity.\n\n Parameters\n ----------\n data : dict\n As saved into the data dictionary when reading out voting records. Each element is\n a two-element list containing the voter names, voting record.\n n_cpus : int, 4\n potts: bool, False\n force_krylov : bool, False\n\n Returns\n -------\n None\n \"\"\"\n \n from coniii.utils import pair_corr, define_ising_helper_functions, define_pseudo_ising_helper_functions\n from data_sets.neuron.data import potts_pair_corr\n from coniii.solvers import Enumerate, Pseudo\n import importlib\n from multiprocess import Pool, cpu_count\n \n _, calc_observables, _ = define_ising_helper_functions()\n\n def single_solution_wrapper(item):\n name = item[0]\n X = item[1][1]\n n = X.shape[1]\n print(\"Solving %s.\"%name)\n if potts:\n assert np.array_equal(np.unique(X), [0,1,2])\n sisj = potts_pair_corr(X, k=3, concat=True)\n ising = importlib.import_module('coniii.ising_eqn.ising_eqn_%d_potts'%n)\n else:\n sisj = pair_corr(X, concat=True)\n ising = importlib.import_module('coniii.ising_eqn.ising_eqn_%d_sym'%n)\n enumSolver = Enumerate(n, calc_observables_multipliers=ising.calc_observables)\n\n hJ, soln = enumSolver.solve(sisj,\n max_param_value=50*n/9,\n full_output=True,\n scipy_solver_kwargs={'method':'hybr'})\n if not potts and np.linalg.norm(soln['fun'])>1e-3:\n # try Pseudo (non-ergodic?)\n print(\"Entering pseudo %s.\"%name)\n get_multipliers_r, calc_observables_r = define_pseudo_ising_helper_functions(n)\n pseudoSolver = Pseudo(n,\n calc_observables=calc_observables,\n calc_observables_r=calc_observables_r,\n get_multipliers_r=get_multipliers_r)\n hJ = pseudoSolver.solve(X, np.zeros(n+n*(n-1)//2))\n\n # try again\n try:\n if force_krylov:\n kwargs = {'method':'krylov'}\n else:\n kwargs = {'method':'hybr'}\n hJ, soln = enumSolver.solve(sisj,\n initial_guess=hJ,\n max_param_value=50*n/9,\n scipy_solver_kwargs=kwargs,\n full_output=True)\n # this occurs when Jacobian inverse returns zero vector\n except ValueError:\n soln = None\n elif potts and np.linalg.norm(soln['fun'])>1e-3:\n hJ, soln = enumSolver.solve(sisj,\n max_param_value=50*n/9,\n full_output=True,\n scipy_solver_kwargs={'method':'krylov'})\n\n print(\"Done with %s.\"%name)\n return hJ, soln\n \n if n_cpus>1:\n pool = Pool(cpu_count()//4)\n hJ, soln = list( zip(*pool.map(single_solution_wrapper, \n [i for i in data.items() if len(i[1])==2] )))\n pool.close()\n else:\n hJ = []\n soln = []\n for item in [i for i in data.items() if len(i[1])==2]:\n hJ_, soln_ = single_solution_wrapper(item)\n hJ.append(hJ_)\n soln.append(soln_)\n \n # update data dict\n keys = [i[0] for i in data.items() if len(i[1])==2]\n for i,k in enumerate(keys):\n n = len(data[k][0])\n if potts:\n hJ[i][:n*3] -= np.tile(hJ[i][:n],3)\n data[k].append(hJ[i])\n data[k].append(soln[i])\n assert all([len(i)==4 for i in data.values()])\n\ndef calculate_fisher_on_pk(data,\n system='',\n method='',\n computed_results=None,\n eps=1e-6,\n high_prec_dps=30,\n save=True,\n save_every_loop=True,\n fi_method=2,\n high_prec=False):\n \"\"\"\n Parameters\n ----------\n data : dict\n system : str, ''\n method : str, ''\n computed_results: dict, None\n If given, results will be appended onto this.\n high_prec_dps : int, 30\n save : bool, True\n Save to pickle.\n save_every_loop : bool, True\n If False, only save at very end after loops.\n fi_method : int, 2\n allow_high_prec : bool, True\n If True, allow high precision calculation to run.\n\n Returns\n -------\n dict\n \"\"\"\n \n import importlib\n \n # fname is only used if save is True\n fname = 'cache/Method%s/%s/%s/fisherResultMaj.p'%(str(fi_method),system,method)\n if not os.path.isdir('cache/Method%s/%s/%s'%(str(fi_method),system,method)):\n os.makedirs('cache/Method%s/%s/%s'%(str(fi_method),system,method))\n \n if computed_results is None:\n fisherResultMaj = {}\n else:\n fisherResultMaj = computed_results\n\n for k in [kp for kp in data.keys() if not kp in fisherResultMaj.keys()]:\n if (data[k][-1] is None or\n (np.linalg.norm(data[k][-1]['fun'])<1e-3)):\n print(\"Starting %s...\"%k)\n n = len(data[k][0])\n hJ = data[k][2]\n \n try:\n if str(fi_method)=='1':\n isingdkl = IsingFisherCurvatureMethod1(n, h=hJ[:n], J=hJ[n:], eps=eps, high_prec=high_prec)\n elif fi_method=='1a':\n isingdkl = IsingFisherCurvatureMethod1a(n, h=hJ[:n], J=hJ[n:], eps=eps)\n elif str(fi_method)=='2':\n isingdkl = IsingFisherCurvatureMethod2(n, h=hJ[:n], J=hJ[n:], eps=eps)\n elif str(fi_method)=='2b':\n isingdkl = IsingSpinReplacementFIM(n, h=hJ[:n], J=hJ[n:], eps=eps)\n elif str(fi_method)=='3':\n isingdkl = IsingFisherCurvatureMethod3(n, h=hJ[:n], J=hJ[n:], eps=eps)\n elif str(fi_method)=='4':\n isingdkl = IsingFisherCurvatureMethod4(n, 3, h=hJ[:n*3], J=hJ[3*n:], eps=eps)\n elif fi_method=='4a':\n isingdkl = IsingFisherCurvatureMethod4a(n, 3, h=hJ[:n*3], J=hJ[3*n:], eps=eps)\n else:\n raise Exception(\"Invalid method.\")\n if fi_method=='2b':\n hess, errflag, err = isingdkl.maj_curvature(full_output=True,\n epsdJ=isingdkl.eps,\n iprint=False)\n else:\n epsdJ = min(1/np.abs(isingdkl.dJ).max()/10, 1e-4)\n hess, errflag, err = isingdkl.maj_curvature(full_output=True,\n epsdJ=epsdJ,\n iprint=False)\n\n eigval, eigvec = isingdkl.hess_eig(hess)\n \n fisherResultMaj[k] = [isingdkl, (hess, errflag, err), eigval, eigvec]\n \n if save and save_every_loop:\n print(\"Saving into %s\"%fname)\n with open(fname, 'wb') as f:\n dill.dump({'fisherResultMaj':fisherResultMaj}, f, -1)\n except AssertionError as e:\n print(\"AssertionError for key %s\"%k)\n print(e)\n\n if save and not save_every_loop:\n print(\"Saving into %s\"%fname)\n with open(fname, 'wb') as f:\n dill.dump({'fisherResultMaj':fisherResultMaj}, f, -1)\n return fisherResultMaj\n\ndef extract_voter_subspace(fisherResult,\n return_n_voters=3,\n remove_n_modes=0):\n \"\"\"\n Parameters\n ----------\n fisherResult : dict\n return_n_voters : int, False\n If an int is given, number of voter subspace eigenvalues to return.\n remove_n_modes : int, 0\n If True, subtract off principal modes from Hessian.\n\n Returns\n -------\n ndarray\n Principal bloc\n ndarray\n Voter subspace eigenvalues (sorted).\n ndarray\n sort index\n \"\"\"\n \n K = len(fisherResult)\n pivotalEigval = np.zeros(K)-1\n voterEigval = np.zeros((K,return_n_voters))\n voterEigvalSortix = np.zeros((K,return_n_voters), dtype=int)\n\n for i,k in enumerate(fisherResult.keys()):\n out = _extract_voter_subspace(fisherResult[k], return_n_voters, remove_n_modes) \n pivotalEigval[i] = out[0] \n voterEigval[i] = out[1]\n voterEigvalSortix[i] = out[2]\n\n assert 0<=(voterEigval[i,0]/pivotalEigval[i])<=1, \"Hessian calculation error. Condition violated.\"\n return pivotalEigval, voterEigval, voterEigvalSortix\n\ndef _extract_voter_subspace(fisherResultValue,\n return_n_voters=3,\n remove_n_modes=0):\n \"\"\"\n Parameters\n ----------\n fisherResultValue : list\n return_n_voters : int, False\n If an int is given, number of voter subspace eigenvalues to return.\n remove_n_modes : int, 0\n If True, subtract off n principal modes from Hessian.\n\n Returns\n -------\n ndarray\n Principal bloc\n ndarray\n Voter subspace eigenvalues (sorted).\n ndarray\n sort index\n \"\"\"\n \n voterEigval = np.zeros(return_n_voters)\n voterEigvalSortix = np.zeros(return_n_voters, dtype=int)\n n = fisherResultValue[0].n\n \n # read out results stored in dict\n isingdkl, (hess, errflag, err), eigval, eigvec = fisherResultValue\n if remove_n_modes>0:\n for i in range(remove_n_modes):\n hess = remove_principal_mode(hess)\n eigval, eigvec = np.linalg.eig(hess)\n sortix = np.argsort(eigval)[::-1]\n eigval = eigval[sortix]\n eigvec = eigvec[:,sortix]\n \n # only consider hessians that are well-estimated\n pivotalEigval = eigval[0]\n\n # when limited to the subspace of a single voter at a given time (how do we \n # optimally tweak a single voter to change the system?)\n veigval = []\n veigvec = []\n \n \n if type(fisherResultValue[0]) is IsingFisherCurvatureMethod1:\n for j in range(n):\n veigval.append(hess[j,j])\n veigvec.append(np.ones(1))\n elif type(fisherResultValue[0]) is IsingFisherCurvatureMethod4a:\n for j in range(n):\n subspaceHess = hess[[j,j+n,j+2*n],:][:,[j,j+n,j+2*n]]\n u, v = np.linalg.eig(subspaceHess)\n sortix = np.argsort(u)[::-1]\n u = u[sortix]\n v = v[:,sortix]\n\n veigval.append(u)\n veigvec.append(v)\n elif not type(fisherResultValue[0]) is IsingFisherCurvatureMethod4a:\n # iterate through subspace for each voter (assuming each voter is connected n-1 others\n for j in range(n):\n subspaceHess = hess[j*(n-1):(j+1)*(n-1), j*(n-1):(j+1)*(n-1)]\n u, v = np.linalg.eig(subspaceHess)\n sortix = np.argsort(u)[::-1]\n u = u[sortix]\n v = v[:,sortix]\n\n veigval.append(u)\n veigvec.append(v)\n voterEigval_ = np.vstack(veigval)\n\n # sort voters by largest voter eigenvalue\n voterEigvalSortix = np.argsort(voterEigval_[:,0])[::-1][:return_n_voters]\n voterEigval = voterEigval_[:,0][voterEigvalSortix]\n\n assert 0<=(voterEigval[0]/pivotalEigval)<=1, \"Hessian calculation error. Condition violated.\"\n return pivotalEigval, voterEigval, voterEigvalSortix\n\ndef degree_collective(fisherResult, **kwargs):\n \"\"\"\n Parameters\n ----------\n fisherResult : dict\n method : str, 'eig'\n 'val': use individual subspace eigenvalues\n 'vec': use weight in entries of eigenvector\n remove_first_mode : bool, False\n If True, subtract off principal mode from Hessian.\n\n Returns\n -------\n ndarray\n \"\"\"\n \n K = len(fisherResult)\n degree = np.zeros(K)-1\n \n for i,k in enumerate(fisherResult.keys()):\n if type(fisherResult[k][0]) is IsingFisherCurvatureMethod1:\n degree[i] = _degree_collective1(fisherResult[k], **kwargs) \n elif type(fisherResult[k][0]) is IsingFisherCurvatureMethod2:\n degree[i] = _degree_collective2(fisherResult[k], **kwargs) \n elif type(fisherResult[k][0]) is IsingFisherCurvatureMethod4:\n degree[i] = _degree_collective2(fisherResult[k], **kwargs) \n elif type(fisherResult[k][0]) is IsingFisherCurvatureMethod4a:\n degree[i] = _degree_collective4a(fisherResult[k], **kwargs) \n else:\n raise Exception(\"Invalid type for key %s.\"%k)\n return degree\n\ndef _degree_collective1(fisherResultValue,\n remove_n_modes=0,\n voter_eig_rank=0,\n method='val'):\n \"\"\"\n Parameters\n ----------\n fisherResultValue : list\n remove_first_mode : bool, False\n If True, subtract off principal mode from rows of Hessian.\n voter_eig_rank : int, 0\n Rank of eigenvalue and eigenvector to return from voter subspaces.\n method : str, 'val'\n\n Returns\n -------\n float\n If 'val' option, then the entropy of the sum of the columns is returned.\n If 'vec' option, then the fractional weights per column are returned.\n \"\"\"\n \n n = fisherResultValue[0].n\n isingdkl, (hess, errflag, err), eigval, eigvec = fisherResultValue\n if remove_n_modes>0:\n for i in range(remove_n_modes):\n hess = remove_principal_mode(hess)\n eigval, eigvec = np.linalg.eig(hess)\n sortix = np.argsort(eigval)[::-1]\n eigval = eigval[sortix]\n eigvec = eigvec[:,sortix]\n \n # only consider hessians that are well-estimated\n #if err is None or np.linalg.norm(err)<(.05*np.linalg.norm(hess)):\n if method=='vec':\n p = eigvec[:,0]**2\n p /= p.sum()\n\n elif method=='val':\n # when limited to the subspace of a single voter at a given time (how do we \n # optimally tweak a single voter to change the system?)\n veigval = []\n veigvec = []\n \n # iterate through subspace for each voter (assuming each voter is connected n-1 others\n for j in range(n):\n veigval.append(hess[j,j])\n veigvec.append(np.ones(1))\n veigval = np.vstack(veigval)[:,voter_eig_rank]\n \n # entropy\n p = veigval / veigval.sum()\n\n else:\n raise Exception(\"Invalid choice for method.\")\n degree = -np.log2(p).dot(p) / np.log2(p.size)\n return degree\n\ndef _degree_collective2(fisherResultValue,\n remove_n_modes=0,\n voter_eig_rank=0,\n method='val'):\n \"\"\"\n Parameters\n ----------\n fisherResultValue : list\n remove_first_mode : bool, False\n If True, subtract off principal mode from rows of Hessian.\n voter_eig_rank : int, 0\n Rank of eigenvalue and eigenvector to return from voter subspaces.\n method : str, 'val'\n\n Returns\n -------\n float\n If 'val' option, then the entropy of the sum of the columns is returned.\n If 'vec' option, then the fractional weights per column are returned.\n \"\"\"\n \n n = fisherResultValue[0].n\n isingdkl, (hess, errflag, err), eigval, eigvec = fisherResultValue\n if remove_n_modes>0:\n for i in range(remove_n_modes):\n hess = remove_principal_mode(hess)\n eigval, eigvec = np.linalg.eig(hess)\n sortix = np.argsort(eigval)[::-1]\n eigval = eigval[sortix]\n eigvec = eigvec[:,sortix]\n \n # only consider hessians that are well-estimated\n #if err is None or np.linalg.norm(err)<(.05*np.linalg.norm(hess)):\n if method=='vec':\n v = np.insert(eigvec[:,0], range(0,n*n,n), 0).reshape(n,n)\n #p = (v**2).sum(1)\n #p = ((v**2).sum(1)+(v**2).sum(0))/2\n #p /= p.sum()\n degree = (v**2+v.T**2-2*np.abs(v*v.T)).sum()/2\n\n elif method=='val':\n # when limited to the subspace of a single voter at a given time (how do we \n # optimally tweak a single voter to change the system?)\n veigval = []\n veigvec = []\n \n # iterate through subspace for each voter (assuming each voter is connected n-1 others\n for j in range(n):\n subspaceHess = hess[j*(n-1):(j+1)*(n-1), j*(n-1):(j+1)*(n-1)]\n u, v = np.linalg.eig(subspaceHess)\n sortix = np.argsort(u)[::-1]\n u = u[sortix]\n v = v[:,sortix]\n\n veigval.append(u)\n veigvec.append(v)\n veigval = np.vstack(veigval)[:,voter_eig_rank]\n \n # entropy\n p = veigval / veigval.sum()\n\n else:\n raise Exception(\"Invalid choice for method.\")\n #degree = -np.log2(p).dot(p) / np.log2(p.size)\n return degree\n\ndef _degree_collective4a(fisherResultValue,\n remove_n_modes=0,\n voter_eig_rank=0,\n method='val'):\n \"\"\"\n Parameters\n ----------\n fisherResultValue : list\n remove_first_mode : bool, False\n If True, subtract off principal mode from rows of Hessian.\n voter_eig_rank : int, 0\n Rank of eigenvalue and eigenvector to return from voter subspaces.\n method : str, 'val'\n\n Returns\n -------\n float\n If 'val' option, then the entropy of the sum of the columns is returned.\n If 'vec' option, then the fractional weights per column are returned.\n \"\"\"\n \n n = fisherResultValue[0].n\n isingdkl, (hess, errflag, err), eigval, eigvec = fisherResultValue\n if remove_n_modes>0:\n for i in range(remove_n_modes):\n hess = remove_principal_mode(hess)\n eigval, eigvec = np.linalg.eig(hess)\n sortix = np.argsort(eigval)[::-1]\n eigval = eigval[sortix]\n eigvec = eigvec[:,sortix]\n \n # only consider hessians that are well-estimated\n #if err is None or np.linalg.norm(err)<(.05*np.linalg.norm(hess)):\n if method=='vec':\n v = eigvec[:,voter_eig_rank].reshape(3,n)\n p = (v**2).sum(0)\n p /= p.sum()\n\n elif method=='val':\n # when limited to the subspace of a single voter at a given time (how do we \n # optimally tweak a single voter to change the system?)\n veigval = []\n veigvec = []\n \n # iterate through subspace for each voter (assuming each voter is connected n-1 others\n for j in range(n):\n subspaceHess = hess[[j,j+n,j+2*n],:][:,[j,j+n,j+2*n]]\n u, v = np.linalg.eig(subspaceHess)\n sortix = np.argsort(u)[::-1]\n u = u[sortix]\n v = v[:,sortix]\n\n veigval.append(u)\n veigvec.append(v)\n veigval = np.vstack(veigval)[:,voter_eig_rank]\n \n # entropy\n p = veigval / veigval.sum()\n\n else:\n raise Exception(\"Invalid choice for method.\")\n degree = -np.log2(p).dot(p) / np.log2(p.size)\n return degree\n","sub_path":"pyutils/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":24895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"93207919","text":"from __future__ import unicode_literals, print_function, division\nfrom veil.model.collection import *\nfrom veil.environment import *\n\nNGINX_PID_PATH = VEIL_VAR_DIR / 'nginx.pid'\n\ndef nginx_program(servers, enable_compression=False, has_bunker=False, is_bunker=False, bunker_ip=None):\n return objectify({\n 'nginx': {\n 'execute_command': 'nginx -c {}'.format(VEIL_ETC_DIR / 'nginx.conf'),\n 'run_as': 'root',\n 'resources': [('veil.frontend.nginx.nginx_resource', {\n 'servers': servers,\n 'enable_compression': enable_compression,\n 'has_bunker': has_bunker,\n 'is_bunker': is_bunker,\n 'bunker_ip': bunker_ip\n })]\n }\n })\n\n\ndef nginx_server(server_name, listen, locations, upstreams=None, error_page=None, error_page_dir=None, default_server=False, **kwargs):\n return {\n server_name: dict({\n 'listen': '{}{}'.format(listen, ' default_server' if default_server else ''),\n 'locations': locations,\n 'upstreams': upstreams,\n 'error_page': error_page,\n 'error_page_dir': error_page_dir\n }, **kwargs)\n }\n\n\ndef nginx_reverse_proxy_location(upstream_host, upstream_port):\n return {\n '_': \"\"\"\n proxy_pass http://%s:%s;\n \"\"\" % (upstream_host, upstream_port)\n }\n","sub_path":"src/veil/frontend/nginx_setting.py","file_name":"nginx_setting.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"586436583","text":"from escape_room_001 import EscapeRoomGame\nimport time, socket\n\nclass MsgHandler:\n def __init__ (self, socket):\n self.s = socket\n def send(self, string_to_send):\n data = string_to_send +\"\\n\"\n data_as_byte = str.encode(data)\n self.s.send(data_as_byte)\n print(\"sent:\".ljust(12)+string_to_send+'\\n')\n def recv(self):\n data = self.s.recv(1024)\n data_as_string = data.decode()\n lines = data_as_string.split(\"\\n\")\n msg_list = []\n for line in lines:\n if line == \"\":\n continue\n print(\"received:\".ljust(12)+line+'\\n')\n msg_list.append(line)\n return msg_list\n\n# create socket\ns = socket.socket()\nhost =\"192.168.200.52\"\nport = 19002\ns.connect((host,port))\nprint(\"Socket successfully created!\\n\")\n\nmsgHandler = MsgHandler(s)\n\n# send student name\nmsgHandler.recv()\nstudent_name = \"xjmTest\"\nmsgHandler.send(student_name)\nprint((\"student name sent:\"+student_name).center(100,'-')+'\\n')\n\n# section 1\nescape_strings = [\"look mirror\", \"get hairpin\", \"unlock door with hairpin\", \"open door\"]\nfor escape_string in escape_strings:\n msgHandler.send(escape_string)\n time.sleep(0.25)\n msgHandler.recv()\nprint(\"section 1 finished\".center(100,'-')+\"\\n\")\n \n# section 2\ngame = EscapeRoomGame(output=msgHandler.send)\ngame.create_game()\ngame.start()\nwhile game.status == \"playing\":\n lines = msgHandler.recv()\n for msg in lines:\n if msg == \"\":\n continue\n game.command(msg)\n time.sleep(0.25)\nprint(\"Section 2 finished!\".center(100,'-')+'\\n')","sub_path":"submisssions/HW2/E2.py","file_name":"E2.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"266588939","text":"import gevent as gevent\nfrom sqlalchemy import Column, String, create_engine, Integer\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nBase = declarative_base()\n\n\nclass PublishDetail(Base):\n # 表名称\n __tablename__ = 't_publish_detail'\n # 表结构\n id = Column(Integer, primary_key=True, autoincrement=True)\n name = Column(String(127))\n code = Column(String(127))\n date = Column()\n branch = Column(String(127))\n category = Column(String(127))\n content = Column(String)\n\n\n# 初始化数据库连接: 使用pymysql 官方文档为: http://docs.sqlalchemy.org/en/latest/dialects/index.html\nengine = create_engine('mysql+pymysql://tao:tao@10.77.40.27:3306/py_voucher')\n# 创建DBSession类型:\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\npublish_detail = PublishDetail(name=\"kkk\", code=\"777\", date=\"2017/05/30\", branch=\"sdffsd\", category=\"kkkk\",\n content=\"sksksks\")\ntry:\n session.add(publish_detail)\n session.commit()\n\n # 创建Query查询,filter是where条件,最后调用one()返回唯一行,如果调用all()则返回所有行:\n detail = session.query(PublishDetail).filter(PublishDetail.id == '739').one()\n # 打印类型和对象的name属性:\n print('type:', type(detail))\n print('name:', detail.name)\n session.close()\nexcept gevent.Timeout:\n session.invalidate()\n raise\nexcept:\n session.rollback()\n raise\n","sub_path":"py/mysqltest.py","file_name":"mysqltest.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"114108362","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n# Logistic Regression Using L1 and L2 Regularization\r\ndef Logistic_Regression_Using_Gradient_Descent(lr, weights, epochs, x, y):\r\n l1 = 0.4\r\n l2 = 1 - l1\r\n costs = []\r\n for _ in range(epochs):\r\n prediction = np.dot(x, weights)\r\n sigmoid = 1 / (1 + np.exp(-prediction))\r\n error = sigmoid - y\r\n cost = (-y) * np.log(sigmoid) - (1 - y) * np.log(1 - sigmoid)\r\n cost = sum(cost) / len(x)\r\n costs.append(cost)\r\n weights = weights - (lr * (x.T.dot(error) + l1 * np.sign(weights) + l2 * 2 * weights) * 1 / len(x))\r\n return weights, costs\r\n\r\n\r\ndef accuracy_metric(actual, predicted):\r\n correct = 0\r\n for value in range(len(actual)):\r\n if actual[value] == predicted[value]:\r\n correct += 1\r\n return correct / len(actual) * 100.0\r\n\r\n\r\nnp.random.seed(123)\r\ndata = pd.read_csv(\"Logistic_Regression_Dataset.csv\")\r\nv = len(data.columns)\r\nX = data.iloc[:, 1:v - 1].values\r\n# thetas = np.random.rand(len(X[0]))\r\nthetas = np.zeros(len(X[0]))\r\nY = data.iloc[:, v - 1].values\r\n\r\n# Splitting Data_Sets\r\nval = len(X) // 3\r\nX_train = X[val:]\r\nX_test = X[: val]\r\nY_train = Y[val:]\r\nY_test = Y[: val]\r\n\r\ntheta_, past_cost = Logistic_Regression_Using_Gradient_Descent(0.025, thetas, 1000, X_train, Y_train)\r\nprint(past_cost)\r\nprint(theta_)\r\n\r\n# Plot the cost function...\r\nplt.title('Cost Function')\r\nplt.xlabel('No. of iterations')\r\nplt.ylabel('Cost')\r\nplt.plot(past_cost)\r\nplt.show()\r\n\r\npredictions = []\r\nfor i in X_test:\r\n s = 0\r\n for j in range(0, len(i)):\r\n # print(j)\r\n s = s + (theta_[j] * i[j])\r\n z = round(1 / (1 + np.exp(-s)))\r\n predictions.append(z)\r\nprint(predictions)\r\nprint(Y_test)\r\nprint(\"Accuracy = \", accuracy_metric(Y_test, predictions))\r\n","sub_path":"Manan_Mukim_Assignment_10_1700146C202/Codes/Problem - 3 (Logistic_Regression_L1_L2_Regularization).py","file_name":"Problem - 3 (Logistic_Regression_L1_L2_Regularization).py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"513474292","text":"import requests\nimport json\nimport config\nimport dates\nfrom datetime import datetime\n\n\ndef _build_payload(method, *args):\n quoted_args = ['\\\"%s\\\"' % arg for arg in args]\n return '{\"jsonrpc\":\"2.0\", \"method\":\"%s\", \"params\":[%s], \"id\":\"1\"}' \\\n % (method, ','.join(quoted_args))\n\n\ndef _build_record_payload(method, record, update=False):\n # Make it compatible with PHP's json decode\n update = 'true' if update else 'false'\n\n return '{\"jsonrpc\":\"2.0\", \"method\":\"%s\", \"params\":[\"%s\", %s, %s], \"id\":\"1\"}' \\\n % (method, config.get('ApiKey'), json.dumps(record), update)\n\n\ndef _do_request(payload):\n kimai_url = config.get('KimaiUrl')\n return requests.post('{}/core/json.php'.format(kimai_url), data=payload)\n\n\ndef authenticate(username, password):\n \"\"\"Authenticate a user against the kimai backend.\"\"\"\n payload = _build_payload('authenticate', username, password)\n response = _do_request(payload)\n return KimaiAuthResponse(response)\n\n\ndef get_projects():\n \"\"\"Return a list of all available projects.\"\"\"\n payload = _build_payload('getProjects', config.get('ApiKey'))\n response = KimaiResponse(_do_request(payload))\n return response.items\n\n\ndef get_tasks():\n \"\"\"Return a list of all available tasks.\"\"\"\n payload = _build_payload('getTasks', config.get('ApiKey'))\n response = KimaiResponse(_do_request(payload))\n return response.items\n\n\ndef start_recording(task_id, project_id):\n \"\"\"Starts a new recording for the provided task and project.\"\"\"\n payload = _build_payload(\n 'startRecord',\n config.get('ApiKey'),\n project_id,\n task_id\n )\n return KimaiResponse(_do_request(payload))\n\n\ndef stop_recording():\n \"\"\"Stops the running record if there is one.\"\"\"\n current_record = get_current()\n\n if current_record is None:\n return\n\n payload = _build_payload(\n 'stopRecord',\n config.get('ApiKey'),\n current_record['timeEntryID']\n )\n return KimaiResponse(_do_request(payload))\n\n\ndef get_current():\n \"\"\"Returns the currently running record if there is any.\"\"\"\n timesheet = get_timesheet()\n\n if not timesheet:\n return\n\n if timesheet[0]['end'] != '0':\n return\n\n return Record(timesheet[0])\n\n\ndef get_todays_records():\n \"\"\"Returns all records for the current day\"\"\"\n payload = _build_payload(\n 'getTimesheet',\n config.get('ApiKey'),\n dates.parse('today at 00:00').isoformat(),\n dates.parse('today at 23:59:59').isoformat()\n )\n response = KimaiResponse(_do_request(payload))\n return [Record(r) for r in response.items]\n\n\ndef get_timesheet():\n payload = _build_payload('getTimesheet', config.get('ApiKey'))\n response = KimaiResponse(_do_request(payload))\n return response.items\n\n\ndef add_record(start, end, project, task, comment=''):\n payload = _build_record_payload('setTimesheetRecord', {\n 'start': start.isoformat(),\n 'end': end.isoformat(),\n 'projectId': project,\n 'taskId': task,\n 'statusId': 1,\n 'comment': comment\n })\n return KimaiResponse(_do_request(payload))\n\n\n# TODO: Holy shit this doesn't check that I'm actually deleting one of my\n# own records...\ndef delete_record(id):\n payload = _build_payload('removeTimesheetRecord', config.get('ApiKey'), id)\n return KimaiResponse(_do_request(payload))\n\n\nclass KimaiResponse(object):\n \"\"\"Generic response object for the Kimai (sort of) JSON API\"\"\"\n\n def __init__(self, response):\n self.data = json.loads(response.text)['result']\n\n @property\n def successful(self):\n return self.data['success']\n\n @property\n def error(self):\n if self.successful:\n return None\n return self.data['error']['msg']\n\n @property\n def items(self):\n if not self.successful:\n return None\n return self.data['items']\n\n\nclass KimaiAuthResponse(KimaiResponse):\n \"\"\"Specific response for the result of an authentication request\"\"\"\n\n @property\n def apiKey(self):\n if not self.successful:\n return None\n return self.items[0]['apiKey']\n\n\nclass Record(dict):\n def __getitem__(self, key):\n if key in ['start', 'end']:\n value = int(super(Record, self).__getitem__(key))\n\n if value == 0:\n return '-'\n\n return datetime.fromtimestamp(value).strftime('%H:%M:%S')\n\n return super(Record, self).__getitem__(key)\n","sub_path":"kimai.py","file_name":"kimai.py","file_ext":"py","file_size_in_byte":4477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"229588382","text":"print(\"Hello World\")\n\nnum_candidates = 3\n\nwinning_percentage = 73.81\n\ncandidate_name = \"Diane\"\n\nwon_election = True\n\ncounties=[\"Arapahoe\",\"Denver\",\"Jefferson\"]\n\nprint(counties[-2])\n\nprint (len(counties))\n\nprint (counties[0:2])\n\ncounties.append(\"El Paso\")\n\ncounties.insert(2,\"El Paso\")\n\ncounties.remove(\"El Paso\")\n\ncounties.pop(3)\n\ncounties[2]=\"El Paso\"\n\ncounties_dict={'Arapahoe':422829,'Denver':463353,'Jefferson':432438}\n\nprint(len(counties_dict))\n\nprint(counties_dict)\n\ncounties_dict.values()\n\ncounties_dict.items()\n\nprint(counties_dict[\"Arapahoe\"])\n\nvoting_data=[{'county': 'Arapahoe', 'registered_voters': 422829}, {'county': 'Denver', 'registered_voters': 463353}, {'county': 'Jefferson', 'registered_voters': 432438}]\n\nvoting_data.append({'county':'El Paso','registered_voters':461149})\n\nprint(voting_data)\n\nmy_votes = int(input(\"How many votes did you get in the election? \"))\n\ntotal_votes = int(input(\"What is the total votes in the election? \"))\n\npercentage_votes = (my_votes / total_votes) * 100\n\nprint(\"I received \" + str(percentage_votes)+\"% Of the total votes.\")\n\ncounties = [\"Arapahoe\",\"Denver\",\"Jefferson\"]\nif counties[1]=='Denver': \n print(counties[1])\n\nif \"Arapahoe\" in counties or \"El Paso\" in counties:\n print(\"Arapahoe or El Paso is in the list of counties.\")\nelse:\n print(\"Arapahoe and El Paso are not in the list of counties.\")\n\nfor county in counties:\n print(county)\n\nfor voters in counties_dict.values():\n print(voters)\n\nfor county in counties_dict:\n print(counties_dict[county])\n\nfor county in counties_dict:\n print(counties_dict.get(county))\n\nfor county, voters in counties_dict.items():\n print(county, voters)\n\noting_data = [{\"county\":\"Arapahoe\", \"registered_voters\": 422829},\n {\"county\":\"Denver\", \"registered_voters\": 463353},\n {\"county\":\"Jefferson\", \"registered_voters\": 432438}]\n\nfor county_dict in voting_data:\n print(county_dict)\n\nfor county_dict in voting_data:\n for value in county_dict.values():\n print(value)\n\nfor county_dict in voting_data:\n print(county_dict['county'])\n\nmy_votes = int(input(\"How many votes did you get in the election? \"))\ntotal_votes = int(input(\"What is the total votes in the election? \"))\nprint(f\"I received {my_votes / total_votes * 100}% of the total votes.\")\ncounties_dict = {\"Arapahoe\": 369237, \"Denver\":413229, \"Jefferson\": 390222}\nfor county, voters in counties_dict.items():\n print(county + \" county has \" + str(voters) + \" registered voters.\")\n\ncandidate_votes = int(input(\"How many votes did the candidate get in the election? \"))\ntotal_votes = int(input(\"What is the total number of votes in the election? \"))\nmessage_to_candidate = (\n f\"You received {candidate_votes} number of votes. \"\n f\"The total number of votes in the election was {total_votes}. \"\n f\"You received {candidate_votes / total_votes * 100}% of the total votes.\")\n\n\n\n\n","sub_path":"Election_Analysis/Python practice.py","file_name":"Python practice.py","file_ext":"py","file_size_in_byte":2888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"87478270","text":"# Functions and Conditionals\n\n# If and else\ndef mean(aCollection):\n # Mean of a dictionary\n if isinstance(aCollection, dict):\n return sum(aCollection.values()) / len(aCollection)\n # Mean of a list\n else:\n return sum(aCollection) / len(aCollection)\n\n\naList = [1, 2, 3]\nprint(\"Mean of\", aList, \"=\", mean(aList))\n\naDictionary = {\"Daniel\": 1, \"Martha\": 2, \"Ricardo\": 3}\nprint(\"Mean of\", aDictionary, \"=\", mean(aDictionary))\n\n# Else if\n\n\ndef compare(x, y):\n if x > y:\n return \"x is greater than y\"\n elif x == y:\n return \"x is equal to y\"\n else:\n return \"x is less than y\"\n\n\nx = 1\ny = 2\nprint(\"x =\", x, \"y =\", y, \"comparison =\", compare(x, y))\n\ny = 1\nprint(\"x =\", x, \"y =\", y, \"comparison =\", compare(x, y))\n\nx = 2\nprint(\"x =\", x, \"y =\", y, \"comparison =\", compare(x, y))\n","sub_path":"the_basics/functions_and_conditionals/lesson.py","file_name":"lesson.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"51836556","text":"# Copyright (C) 2008 Samuel Abels \n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License version 2, as\n# published by the Free Software Foundation.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\nimport datetime\n\ndef time_delta(datetime1, datetime2):\n delta = datetime1 - datetime2\n if delta < datetime.timedelta():\n return -delta\n return delta\n\n\ndef same_day(date1, date2):\n return date1.timetuple()[:3] == date2.timetuple()[:3]\n\n\ndef end_of_day(date):\n start = datetime.datetime(*date.timetuple()[:3])\n return start + datetime.timedelta(1) - datetime.timedelta(0, 0, 0, 1)\n\n\ndef previous_day(date):\n return date - datetime.timedelta(1)\n\n\ndef next_day(date):\n return date + datetime.timedelta(1)\n\n\ndef previous_week(date):\n return date - datetime.timedelta(7)\n\n\ndef next_week(date):\n return date + datetime.timedelta(7)\n\n\ndef previous_month(cal, date):\n year, month, day = date.timetuple()[:3]\n if month == 1:\n year -= 1\n month = 12\n else:\n month -= 1\n prev_month_days = [d for d in cal.itermonthdays(year, month)]\n if day not in prev_month_days:\n day = max(prev_month_days)\n return datetime.datetime(year, month, day)\n\n\ndef next_month(cal, date):\n year, month, day = date.timetuple()[:3]\n if month == 12:\n year += 1\n month = 1\n else:\n month += 1\n next_month_days = [d for d in cal.itermonthdays(year, month)]\n if day not in next_month_days:\n day = max(next_month_days)\n return datetime.datetime(year, month, day)\n\n\ndef event_days(event1, event2):\n return time_delta(event1.start, event1.end).days \\\n - time_delta(event2.start, event2.end).days\n\n\ndef event_intersects(event, start, end = None):\n if end is None:\n end = start\n return (event.start >= start and event.start < end) \\\n or (event.end > start and event.end <= end) \\\n or (event.start < start and event.end > end)\n\n\ndef get_intersection_list(list, start, end):\n intersections = []\n for event in list:\n if event_intersects(event, start, end):\n intersections.append(event)\n return intersections\n\n\ndef count_intersections(list, start, end):\n intersections = 0\n for event in list:\n if event_intersects(event, start, end):\n intersections += 1\n return intersections\n\n\ndef count_parallel_events(list, start, end):\n \"\"\"\n Given a list of events, this function returns the maximum number of\n parallel events in the given timeframe.\n \"\"\"\n parallel = 0\n i = 0\n for i, event1 in enumerate(list):\n if not event_intersects(event1, start, end):\n continue\n parallel = max(parallel, 1)\n for f in range(i + 1, len(list)):\n event2 = list[f]\n new_start = max(event1.start, event2.start)\n new_end = min(event1.end, event2.end)\n if event_intersects(event2, start, end) \\\n and event_intersects(event2, new_start, new_end):\n n = count_parallel_events(list[f:], new_start, new_end)\n parallel = max(parallel, n + 1)\n return parallel\n","sub_path":"bin/SpiffGtkWidgets/Calendar/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"307793176","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Function\n\nclass QuantizedClassifier(nn.Module):\n def __init__(self, model, centers, temp=0.1, dropout=0.3):\n super(QuantizedClassifier, self).__init__()\n self.centers = centers\n self.temp = temp\n self.model = model\n\n def forward(self, x):\n qx = quantize(x, self.centers, self.temp)\n return self.model(qx)\n\nclass Argmin(Function):\n @staticmethod\n def forward(ctx, dists):\n '''\n x is shape (N, C)\n '''\n out = torch.zeros(dists.size(), dtype=dists.dtype)\n mins = torch.argmin(dists, dim=1).unsqueeze(1)\n out.scatter_(1, mins, 1)\n ctx.save_for_backward(out)\n return out\n\n @staticmethod\n def backward(ctx, grad_output):\n '''\n grad_output is shape (N, C)\n '''\n N = grad_output.size(0)\n C = grad_output.size(1)\n out = ctx.saved_tensors[0]\n grad_input = torch.zeros_like(grad_output)\n sm_tensor = torch.zeros((N, C, C), dtype=grad_output.dtype)\n sm_tensor += out.unsqueeze(1)\n sm_tensor += torch.eye(C, dtype=grad_output.dtype)\n sm_tensor *= out.unsqueeze(2)\n grad_input = sm_tensor.permute(1, 0, 2) * grad_output\n grad_input = torch.sum(grad_input.permute(1, 0, 2), dim=2)\n return grad_input\n\nclass Softmin(Function):\n @staticmethod\n def forward(ctx, x):\n out = F.softmin(x, dim=1)\n ctx.save_for_backward(out)\n return out\n\n @staticmethod\n def backward(ctx, grad_output):\n '''\n grad_output is shape (N, C)\n '''\n N = grad_output.size(0)\n C = grad_output.size(1)\n out = ctx.saved_tensors[0]\n grad_input = torch.zeros_like(grad_output)\n sm_tensor = torch.zeros((N, C, C), dtype=grad_output.dtype)\n sm_tensor += out.unsqueeze(1)\n sm_tensor += torch.eye(C, dtype=grad_output.dtype)\n sm_tensor *= out.unsqueeze(2)\n grad_input = sm_tensor.permute(1, 0, 2) * grad_output\n grad_input = torch.sum(grad_input.permute(1, 0, 2), dim=2)\n return grad_input\n\nargmin = Argmin.apply\nsoftmin = Softmin.apply\n\ndef quantize(x, centers, temp):\n dists = squared_distance(x.view(-1, 1), centers) / temp\n groups = argmin(dists)\n return torch.matmul(groups, centers).view(x.size())\n\ndef uniform_qlevels(x, levels=16):\n '''\n x is flattened array of numbers\n '''\n xmax = np.max(x)\n xmin = np.min(x)\n centers = (xmax - xmin)*(np.arange(levels) + 0.5)/levels + xmin\n bins = get_bins(centers)\n return centers, bins\n\ndef kmeans_qlevels(x, levels=16):\n '''\n x is flattened array of numbers\n '''\n km = KMeans(n_clusters=levels)\n km.fit(np.expand_dims(x, axis=1))\n centers = np.sort(km.cluster_centers_.reshape(-1))\n bins = get_bins(centers)\n return centers, bins\n\ndef squared_distance(x, centers):\n '''\n x has shape (N, D)\n centers has shape (C, D)\n output has shape (N, C)\n '''\n dists = torch.zeros(x.size(0), centers.size(0), dtype=x.dtype)\n for i in range(centers.size(0)):\n dists[:, i] = torch.norm(x - centers[i], dim=1)**2\n return dists\n","sub_path":"quantize.py","file_name":"quantize.py","file_ext":"py","file_size_in_byte":3228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"137744829","text":"\ndef calculate(string1,string2):\n\n\tc=[[0 for i in range(len(string2)+1)] for j in range(len(string1)+1)]\n\tb=[[0 for i in range(len(string2)+1)] for j in range(len(string1)+1)]\n\n\n\n\tfor i in range(1,len(string1)+1):\n\n\t\tfor j in range(1,len(string2)+1):\n\n\t\t\tif string1[i-1]==string2[j-1]:\n\t\t\t\tc[i][j]=c[i-1][j-1]+1\n\t\t\t\tb[i][j]=\"ADDXY\"\n\n\t\t\telse:\n\n\n\t\t\t\tc[i][j]=max(c[i-1][j],c[i][j-1])\n\n\t\t\t\tif c[i][j]==c[i-1][j]:\n\t\t\t\t\tb[i][j]=\"SKIPX\"\n\n\t\t\t\telse:\n\t\t\t\t\tb[i][j]=\"SKIPY\"\n\n\n\ti=len(string1)\n\tj=len(string2)\n\tLCS=\"\"\n\twhile i!=0 and j!=0:\n\t\tif b[i][j]==\"ADDXY\":\n\t\t\tLCS=string1[i-1]+LCS\n\t\t\ti-=1\n\t\t\tj-=1\n\n\t\telif b[i][j]==\"SKIPX\":\n\t\t\ti-=1\n\n\n\t\telif b[i][j]==\"SKIPY\":\n\t\t\tj-=1\n\n\n\n\tprint (LCS)\n\n\n\n\nstring1=input()\nstring2=input()\n\ncalculate(string1,string2)\n","sub_path":"lcsImplementation.py","file_name":"lcsImplementation.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"630411537","text":"import hashlib\nimport random\nimport binascii\nimport websockets\nimport asyncio\nimport sys\nimport logging\nlogger = logging.getLogger('websockets')\nlogger.setLevel(logging.INFO)\nlogger.addHandler(logging.StreamHandler())\n\n\n# parameters\nN = int(\"EEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE48E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B297BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9AFD5138FE8376435B9FC61D2FC0EB06E3\", 16)\ng = 2\npassword = \"PQAEDBQOAAAcBkUSVCgQHQcCDhcH\"\n\n\ndef generaterandom(limit):\n ran = random.randrange(10**80)\n myhex = \"%064x\" % ran\n\n # limit string to [limit] characters\n myhex = myhex[:limit]\n return int(myhex, 16)\n\n\ndef encodeint(num):\n buff = num.to_bytes((num.bit_length() + 7) // 8, 'big')\n return binascii.hexlify(buff).decode(\"utf-8\")\n\n\ndef decodeint(numencoded):\n buff = binascii.unhexlify(numencoded)\n return int.from_bytes(buff, 'big')\n\n\nasync def hello():\n async with websockets.connect(\n 'ws://com402.epfl.ch/hw2/ws') as websocket:\n\n # send email\n U = \"serif.serbest@epfl.ch\"\n Uencoded = U.encode(\"utf-8\")\n await websocket.send(Uencoded)\n print(\"u encoded:\", Uencoded)\n print(\"email sent\")\n\n # receive salt\n saltencoded = await websocket.recv()\n salt = decodeint(saltencoded)\n print(\"salt encoded:\", saltencoded)\n print(\"salt:\", salt)\n\n # generate a random number\n a = generaterandom(32)\n\n # calculate and send A\n A = pow(g, a, N)\n Aencoded = encodeint(A)\n print(\"encoded A:\", Aencoded)\n await websocket.send(Aencoded)\n\n # receive B\n Bencoded = await websocket.recv()\n B = decodeint(Bencoded)\n print(\"B encoded:\", Bencoded)\n print(\"B:\", B)\n\n # hash A and B\n Abytes = A.to_bytes((A.bit_length() + 7) // 8, 'big')\n Bbytes = B.to_bytes((B.bit_length() + 7) // 8, 'big')\n hashinput = Abytes + Bbytes\n u = hashlib.sha256(hashinput).hexdigest()\n print(\"u:\", u)\n\n # hash salt, U and password\n passwordbytes = password.encode(\"utf-8\")\n Ubytes = Uencoded\n hashinput = Ubytes + \":\".encode(\"utf-8\") + passwordbytes\n inputright = hashlib.sha256(hashinput).hexdigest()\n inputrightbytes = binascii.unhexlify(inputright)\n\n saltbytes = salt.to_bytes((salt.bit_length() + 7) // 8, 'big')\n hashinput = saltbytes + inputrightbytes\n\n x = hashlib.sha256(hashinput).hexdigest()\n print(\"x:\", x)\n\n # calcuate S\n xint = int(x, 16)\n base = B - pow(g, xint, N)\n print(\"base:\", base)\n\n uint = int(u, 16)\n exponent = a + uint * xint\n exponent = pow(exponent, 1, N)\n print(\"exponent:\", exponent)\n\n S = pow(base, exponent, N)\n print(\"S:\", S)\n\n # hash A, B and S\n Sbytes = S.to_bytes((S.bit_length() + 7) // 8, 'big')\n hashinput = Abytes + Bbytes + Sbytes\n response = x = hashlib.sha256(hashinput).hexdigest()\n\n # get token\n await websocket.send(response)\n Token = await websocket.recv()\n print(\"Token:\", Token)\n\n\nif __name__ == '__main__':\n try:\n print('connecting ...')\n asyncio.get_event_loop().run_until_complete(hello())\n\n except Exception as e:\n logging.exception(e)\n","sub_path":"HW2/Serif_Serbest_294910/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":3426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"27304541","text":"#!/usr/bin/env python\n\n\"\"\"\nUse muon flux weights to calculate an effective livetime for combined\nCORSIKA samples as a function of energy.\n\"\"\"\n\nfrom argparse import ArgumentParser\nfrom os.path import expandvars\nparser = ArgumentParser()\nparser.add_argument(\"outfile\", help=\"save plot to file\")\nargs = parser.parse_args()\n\nimport matplotlib\nmatplotlib.use('agg')\nimport pylab, numpy\nfrom icecube import dataclasses, MuonGun\n\nsurface = MuonGun.Cylinder(1600, 800)\narea = numpy.pi**2*surface.radius*(surface.radius+surface.length)\n\n# 1 file of E^-2.6 5-component 3e4-1e9 GeV (3:2:1:1:1)\nsoft = 4e5*MuonGun.corsika_genprob('CascadeOptimized5Comp')\n# 1 file of E^-2 5-component 6e2-1e11 GeV (10:5:3:2:1)\nhard = 2.5e6*MuonGun.corsika_genprob('Standard5Comp')\n# In order to compare to \"unweighted\" CORSIKA, turn the Hoerandel flux\n# into a probability (since we happen to know the integral)\nareanorm = 0.131475115*area\n# 1 file of natural-spectrum (\"unweighted\") CORSIKA\nunweighted = (2.5e7/areanorm)*MuonGun.corsika_genprob('Hoerandel5')\n\nmodel = MuonGun.load_model('GaisserH4a_atmod12_SIBYLL')\nmodel.flux.min_multiplicity = 1\nmodel.flux.max_multiplicity = 1\n# spectrum = MuonGun.OffsetPowerLaw(5.0, 5e2, 8e2, 10**4.5)\nspectrum = MuonGun.OffsetPowerLaw(5, 8e2, 2e3, 1e5)\n\n# spectrum = MuonGun.OffsetPowerLaw(1.1, 650, 800, 1e8)\ngun = 1e5*MuonGun.EnergyDependentSurfaceInjector(surface, model.flux, spectrum, model.radius)\n# gun = 1e5*MuonGun.StaticSurfaceInjector(surface, model.flux, spectrum, model.radius)\n\n# gun.target_surface = lambda e: surface\n\n\ndef get_weight(weighter, energy, zenith=numpy.pi/8, scale=True):\n\tshape = energy.shape\n\tif scale:\n\t\tx = numpy.array([gun.target_surface(e).radius - 1 for e in energy])\n\telse:\n\t\t# x = numpy.ones(shape[0])*surface.radius - 1\n\t\tx = numpy.ones(shape[0])*surface.radius - 1\n\t\n\t# x = surface.radius*numpy.ones(shape) - 1\n\ty = numpy.zeros(shape)\n\t# z = z*numpy.ones(shape)\n\tif scale:\n\t\tz = numpy.array([gun.target_surface(e).center.z + gun.target_surface(e).length/2. for e in energy])\n\telse:\n\t\tz = numpy.ones(shape[0])*(surface.center.z + surface.length/2.)\n\t\n\tazimuth = numpy.zeros(shape)\n\tzenith = zenith*numpy.ones(shape)\n\tmultiplicity = numpy.ones(shape, dtype=numpy.uint32)\n\tmmax = multiplicity.max()\n\te = numpy.zeros(shape + (mmax,), dtype=numpy.float32)\n\te[:,0] = energy\n\tr = numpy.zeros(shape + (mmax,), dtype=numpy.float32)\n\ttry:\n\t\treturn weighter(x, y, z, zenith, azimuth, multiplicity, e, r)\n\texcept:\n\t\t# work around lack of vectorized pybindings\n\t\t@numpy.vectorize\n\t\tdef weight(x,y,z,zenith,azimuth,multiplicity,e,r):\n\t\t\taxis = dataclasses.I3Particle()\n\t\t\taxis.pos = dataclasses.I3Position(x,y,z)\n\t\t\taxis.dir = dataclasses.I3Direction(zenith,azimuth)\n\t\t\tassert multiplicity == 1\n\t\t\tbundle = MuonGun.BundleConfiguration()\n\t\t\tbundle.append(MuonGun.BundleEntry(float(r),float(e)))\n\t\t\treturn weighter(axis, bundle)\n\t\treturn weight(x, y, z, zenith, azimuth, multiplicity, e[:,0], r[:,0])\n\ne = numpy.logspace(1, 7, 101)\n\ntarget = MuonGun.load_model('Hoerandel5_atmod12_SIBYLL')\n# target = MuonGun.load_model('GaisserH4a_atmod12_SIBYLL')\n\ngenerators = [\n\t('200k $E^{-2}$ 5-component CORSIKA', 2e5*hard),\n\t('300k $E^{-2.6}$ 5-component CORSIKA', (300e3)*soft),\n\t('200k unweighted CORSIKA', 2e5*unweighted),\n\t('1k MuonGun (100k muons each)', 1e3*gun),\n\t\n\t('total', 2e5*hard + 300e3*soft + 2e5*unweighted + 1e3*gun),\n]\n\n\nfig = pylab.figure(figsize=(6,4))\nfig.subplots_adjust(bottom=0.15)\n\nannum = 365*24*3600\nfor label, generator in generators:\n\tweighter = MuonGun.WeightCalculator(target, generator)\n\tpylab.plot(e, 1./(get_weight(weighter, e, scale=True)*annum), label=label)\n\npylab.loglog()\npylab.legend(loc='lower right', prop=dict(size='x-small'))\npylab.ylabel('Single-muon livetime [years]')\npylab.xlabel('Muon energy at sampling surface [GeV]')\npylab.grid()\n\npylab.savefig(args.outfile)\n","sub_path":"MuonGun/resources/examples/plot_livetime.py","file_name":"plot_livetime.py","file_ext":"py","file_size_in_byte":3835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"35998806","text":"\"\"\" Converts certification documentation to a gitbook \"\"\"\n\nimport filecmp\nimport glob\nimport os\nimport shutil\nimport re\n\n\nfrom slugify import slugify\nfrom src import utils\n\n\ndef write_markdown(output_path, filename, text):\n \"\"\" Write text to a markdown file \"\"\"\n filename = os.path.join(output_path, filename)\n with open(filename, 'w') as md_file:\n md_file.write(text)\n\n\ndef is_url(item_path):\n if 'http://' in item_path or 'https://' in item_path:\n return True\n\n\ndef export_local_files(item_path, io_paths):\n \"\"\" Export local files to the new directory \"\"\"\n if io_paths:\n output_path = os.path.join(io_paths['output'], 'artifacts', item_path)\n input_path = os.path.join(io_paths['input'], item_path)\n utils.create_dir(os.path.dirname(output_path))\n if not os.path.exists(output_path) or not filecmp.cmp(input_path, output_path):\n shutil.copy(input_path, output_path)\n\n\ndef prepare_locally_stored_files(element, io_paths):\n \"\"\" Prepare the files by moving locally stored files to the `artifacts` directory\n and linking filepaths to that directory \"\"\"\n item_path = element.get('path')\n if item_path and not is_url(item_path):\n element['path'] = os.path.join('/artifacts', item_path).replace('\\\\', '/')\n\n\ndef convert_element(element, io_paths=None):\n \"\"\" Converts a dict with a name path and type to markdown \"\"\"\n prepare_locally_stored_files(element, io_paths)\n if element['type'].lower() == 'image':\n base_text = '\\n![{0}]({1})\\n'\n else:\n base_text = '\\n[{0}]({1})\\n'\n try:\n text = base_text.format(element['name'], element['path'])\n except:\n text = element['name']\n return text\n\n\ndef generate_text_narative(narative):\n \"\"\" Checks if the narrative is in dict format or in string format.\n If the narrative is in dict format the script converts it to to a\n string \"\"\"\n text = ''\n if isinstance(narative, dict):\n for key in sorted(narative):\n text += '{0}. {1} \\n '.format(key, narative[key])\n else:\n text = narative + ' \\n'\n return text\n\n\ndef build_standards_summary(summaries, output_path):\n \"\"\" Construct the summary for the standards \"\"\"\n main_summary = \"## Standards \\n\\n\"\n for standard_key in natural_sort(summaries['standards']):\n for family_key in natural_sort(summaries['standards'][standard_key]):\n section_summary = '# {0} \\n'.format(family_key)\n main_summary += '* [{0} - {1}](content/{1}.md)\\n'.format(standard_key, family_key)\n for control_key in natural_sort(summaries['standards'][standard_key][family_key]):\n control = summaries['standards'][standard_key][family_key][control_key]\n main_summary += '\\t* [{0} - {1}](content/{2}.md)\\n'.format(\n control['family'],\n control['control_name'],\n control['slug']\n )\n section_summary += '* [{0} - {1}]({2}.md)\\n'.format(\n control['control'],\n control['control_name'],\n control['slug']\n )\n write_markdown(output_path, 'content/' + family_key + '.md', section_summary)\n return main_summary\n\n\ndef build_components_summary(summaries, output_path):\n \"\"\" Construct the summary for the components \"\"\"\n main_summary = '\\n## Systems \\n\\n'\n for system_key in sorted(summaries['components']):\n main_summary += '* [{0}](content/{1}.md)\\n'.format(system_key, system_key)\n section_summary = '# {0} \\n###Components \\n'.format(system_key)\n for component_key in sorted(summaries['components'][system_key]):\n component = summaries['components'][system_key][component_key]\n # Add the components path to main summary\n main_summary += '\\t* [{0}](content/{1}.md)\\n'.format(\n component['component_key'],\n component['slug']\n )\n # Add the components path to section summary\n section_summary += '* [{0}]({1}.md)\\n'.format(\n component['component_key'],\n component['slug']\n )\n write_markdown(output_path, 'content/' + system_key + '.md', section_summary)\n return main_summary\n\n\ndef concat_markdowns(markdown_path, output_path):\n \"\"\" Add markdown content files to the gitbook directory and make the summary\n file the base summary string in order to join the markdown summary with\n the gitbook generated in this file. \"\"\"\n for filename in glob.iglob(os.path.join(markdown_path, \"*\", \"*\")):\n # Get the output file path and create the directory before copying\n output_filepath = os.path.join(\n output_path, filename.replace(os.path.join(markdown_path, ''), '')\n )\n ouput_dir = os.path.dirname(output_filepath)\n utils.create_dir(ouput_dir)\n shutil.copy(filename, output_filepath)\n summary_path = os.path.join(markdown_path, 'SUMMARY.md')\n with open(summary_path, 'r') as summary_file:\n main_summary = summary_file.read()\n return main_summary\n\n\ndef build_summary(summaries, output_path, markdown_path):\n \"\"\" Construct a gitbook summary for the controls \"\"\"\n if markdown_path and os.path.exists(markdown_path):\n main_summary = concat_markdowns(markdown_path, output_path)\n # load the main markdown\n else:\n main_summary = \"# Summary \\n\\n\"\n main_summary += build_standards_summary(summaries, output_path)\n main_summary += build_components_summary(summaries, output_path)\n write_markdown(output_path, 'SUMMARY.md', main_summary)\n write_markdown(output_path, 'README.md', main_summary)\n\n\ndef document_cert_page(certification, standard_key, control_key):\n \"\"\" Create a new page dict. This item is a dictionary that\n contains the standard and control keys, a slug of the combined key, and the\n name of the control\"\"\"\n meta_data = certification['standards'][standard_key][control_key]['meta']\n\n slug = slugify('{0}-{1}'.format(standard_key, control_key))\n return {\n 'control': control_key,\n 'standard': standard_key,\n 'family': meta_data.get('family'),\n 'control_name': meta_data.get('name'),\n 'slug': slug\n }\n\n\ndef document_component_page(certification, system_key, component_key):\n \"\"\" Create a new page dict. This item is a dictionary that\n contains the standard and control keys, a slug of the combined key, and the\n name of the control\"\"\"\n component = certification['components'][system_key]['components'][component_key]\n slug = slugify('{0}-{1}'.format(system_key, component_key))\n return {\n 'system_key': system_key,\n 'component_key': component_key,\n 'component_name': component['name'],\n 'slug': slug\n }\n\n\ndef fetch_component(reference, certification):\n \"\"\" Fetches a specific component from the certification dict,\n this component will be used to extract the component name and it's verifications\n when they are referenced \"\"\"\n return certification['components'][reference['system']]['components'][reference['component']]\n\n\ndef fetch_verification(verification_ref, certification):\n \"\"\" Get the verfication component \"\"\"\n component = fetch_component(verification_ref, certification)['verifications']\n return component[verification_ref['verification']]\n\n\ndef org_by_system_component(justifications):\n \"\"\" Organizes list of justifications in a dictionary of systems and\n components \"\"\"\n justifications_dict = {}\n for justification in justifications:\n system_key = justification['system']\n component_key = justification['component']\n if system_key not in justifications_dict:\n justifications_dict[system_key] = {}\n justifications_dict[system_key][component_key] = justification\n return justifications_dict\n\n\ndef build_control_text(control, certification):\n \"\"\" Generate the markdown text from each `justification` \"\"\"\n text = ''\n # Order the justifications by system and then component\n justifications_dict = org_by_system_component(control.get('justifications', []))\n for system_key in sorted(justifications_dict):\n text += '\\n## {0}\\n'.format(system_key)\n for component_key in sorted(justifications_dict[system_key]):\n justification = justifications_dict[system_key][component_key]\n component = fetch_component(justification, certification)\n text += '\\n## {0}\\n'.format(component.get('name'))\n text += generate_text_narative(justification.get('narrative'))\n verifications = justification.get('references')\n if verifications:\n for verification_ref in verifications:\n text += convert_element(\n fetch_verification(verification_ref, certification)\n )\n return text\n\n\ndef build_component_text(component, io_paths):\n \"\"\" Create markdown output for component text \"\"\"\n text = '\\n### References \\n'\n references = component.get('references', [])\n if references:\n for reference in sorted(references, key=lambda k: k['name']):\n text += convert_element(reference, io_paths)\n text += '\\n### Verifications \\n'\n verifications = component.get('verifications', [])\n if verifications:\n for verification_key in sorted(verifications):\n text += convert_element(component['verifications'][verification_key], io_paths)\n return text\n\n\ndef build_cert_page(page_dict, certification, output_path):\n \"\"\" Write a page for the gitbook \"\"\"\n text = '# {0}'.format(page_dict['control_name'])\n control = certification['standards'][page_dict['standard']][page_dict['control']]\n text += build_control_text(control, certification)\n file_name = 'content/' + page_dict['slug'] + '.md'\n write_markdown(output_path, file_name, text)\n\n\ndef build_component_page(page_dict, certification, io_paths):\n \"\"\" Write a page for the gitbook \"\"\"\n text = '# {0}'.format(page_dict['component_name'])\n component = certification['components'][page_dict['system_key']]['components'][page_dict['component_key']]\n text += build_component_text(component, io_paths)\n file_name = 'content/' + page_dict['slug'] + '.md'\n write_markdown(io_paths['output'], file_name, text)\n\n\ndef natural_sort(elements):\n \"\"\" Natural sorting algorithms for stings with text and numbers reference:\n stackoverflow.com/questions/4836710/\n \"\"\"\n convert = lambda text: int(text) if text.isdigit() else text.lower()\n alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', str(key))]\n return sorted(elements, key=alphanum_key)\n\n\ndef build_standards_documentation(certification, output_path):\n \"\"\" Create the documentation for standards \"\"\"\n summary = {}\n for standard_key in certification['standards']:\n summary[standard_key] = {}\n for control_key in certification['standards'][standard_key]:\n if 'justifications' in certification['standards'][standard_key][control_key]:\n page_dict = document_cert_page(certification, standard_key, control_key)\n build_cert_page(page_dict, certification, output_path)\n if page_dict['family'] not in summary[standard_key]:\n summary[standard_key][page_dict['family']] = {}\n summary[standard_key][page_dict['family']][control_key] = page_dict\n return summary\n\n\ndef build_components_documentation(certification, io_paths):\n \"\"\" Create the documentation for the components \"\"\"\n summary = {}\n for system_key in sorted(certification['components']):\n summary[system_key] = {}\n for component_key in sorted(certification['components'][system_key]['components']):\n page_dict = document_component_page(certification, system_key, component_key)\n build_component_page(page_dict, certification, io_paths)\n summary[system_key][component_key] = page_dict\n return summary\n\n\ndef create_gitbook_documentation(certification_path, output_path, markdown_path=None):\n \"\"\" Convert certification to pages format \"\"\"\n summaries = {}\n io_paths = {\n 'output': output_path,\n 'input': os.path.dirname(certification_path)\n }\n certification = utils.yaml_loader(certification_path)\n summaries['components'] = build_components_documentation(certification, io_paths)\n summaries['standards'] = build_standards_documentation(certification, output_path)\n build_summary(summaries, output_path, markdown_path)\n return output_path\n","sub_path":"src/renderers/certifications_to_gitbook.py","file_name":"certifications_to_gitbook.py","file_ext":"py","file_size_in_byte":12702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"506795140","text":"import discord\nfrom discord.ext import commands\nfrom .nonDiscordCommands.commands import AllCommandUsages\n\ncmds = AllCommandUsages()\n\nallCommands = [\"balance\", \"transfer\", \"kela\", \"memechannel\", \"rule34\",\n \"reddit\", \"coinflip\", \"slots\", \"dogify\", \"catify\", \"computerify\",\n \"8ball\", \"hack\", \"kill\", \"idk\", \"rps\", \"futuramaquote\",\n \"rickandmortyquote\", \"simpsonsquote\", \"sqrt\", \"hex\", \"translate\"]\n\t\t \n\nclass Help(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n \n @commands.command(pass_context=True)\n async def help(self, ctx, optCommand: str = None):\n if optCommand in allCommands:\n cmdIndex = allCommands.index(optCommand)\n embed = discord.Embed(\n title = \"Command Usage\",\n description = cmds.commandUsageGetter(optCommand),\n colour = discord.Colour.blue()\n )\n await ctx.send(embed=embed)\n elif optCommand == None:\n embed = discord.Embed(\n \t\ttitle = \"Command list\",\n \t\tdescription = \"**Prefix**: -\",\n \t\tcolour = discord.Colour.blue(),\n \t\ttype = \"rich\"\n \t\t)\n\n embed.add_field(name=\":cookie: Economy\", value=\"`balance, transfer, toggletransfer, kela, slots, coinflip`\", inline=False)\n embed.add_field(name=\":smirk: NSFW\", value=\"`rule34`\", inline=False)\n embed.add_field(name=\"Image\", value=\"`catify, dogify, computerify`\", inline=False)\n embed.add_field(name=\":tada: Fun\", value=\"`reddit, rps, kill, hack, idk, 8ball, futuramaquote,\\nsimpsonsquote, rickandmortyquote`\", inline=False)\n embed.add_field(name=\"Utility\", value=\"`memechannel, sqrt, hex, translate`\", inline=False)\n embed.set_image(url=\"https://media.giphy.com/media/frATeOuT8QWoazfJmi/giphy.gif\")\n embed.set_footer(icon_url=ctx.message.author.avatar_url, text=\"-help [command name] to check usage\")\n\n await ctx.send(embed=embed)\n else:\n await ctx.send(\"can't find the command\")\n\ndef setup(client):\n client.add_cog(Help(client))\n\n","sub_path":"cogs/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"640725224","text":"\"\"\"Fit HMM to segmented alignments using conditional maximum likelihood via gradient descent.\"\"\"\n\nimport json\nimport multiprocessing as mp\nimport os\nimport re\nfrom functools import reduce\n\nimport numpy as np\nimport skbio\nimport src.ortho_MSA.hmm as hmm\nfrom src.ortho_MSA import utils\nfrom numpy import exp, log\nfrom src.utils import read_fasta\n\n\ndef norm_params(t_dists, e_dists):\n \"\"\"Return parameters as their normalized values.\"\"\"\n t_dists_norm = {}\n for s1, t_dist in t_dists.items():\n z_sum = sum([exp(z) for z in t_dist.values()])\n t_dists_norm[s1] = {s2: exp(z)/z_sum for s2, z in t_dist.items()}\n e_dists_norm = {}\n for s, e_dist in e_dists.items():\n za, zb, zpi, zq0, zq1, zp0, zp1 = [e_dist[param] for param in ['a', 'b', 'pi', 'q0', 'q1', 'p0', 'p1']]\n e_dists_norm[s] = {'a': exp(za), 'b': exp(zb),\n 'pi': 1 / (1 + exp(-zpi)), 'q0': exp(zq0), 'q1': exp(zq1),\n 'p0': 1 / (1 + exp(-zp0)), 'p1': 1 / (1 + exp(-zp1))}\n return t_dists_norm, e_dists_norm\n\n\ndef unnorm_params(t_dists_norm, e_dists_norm):\n \"\"\"Return parameters as their unnormalized values for gradient descent.\"\"\"\n t_dists = {}\n for s1, t_dist in t_dists_norm.items():\n t_dists[s1] = {s2: log(v) for s2, v in t_dist.items()}\n e_dists = {}\n for s, e_dist in e_dists_norm.items():\n a, b, pi, q0, q1, p0, p1 = [e_dist[param] for param in ['a', 'b', 'pi', 'q0', 'q1', 'p0', 'p1']]\n e_dists[s] = {'a': log(a), 'b': log(b),\n 'pi': log(pi / (1 - pi)), 'q0': log(q0), 'q1': log(q1),\n 'p0': log(p0 / (1 - p0)), 'p1': log(p1 / (1 - p1))}\n return t_dists, e_dists\n\n\ndef get_gradients(t_dists_norm, e_dists_norm, start_dist, record):\n \"\"\"Return record updated with expected values of states and transitions given model parameters.\"\"\"\n # Unpack record fields\n n = record['n']\n tree, state_seq, emit_seq = record['tree'], record['state_seq'], record['emit_seq']\n mis, mijs = record['mis'], record['mijs']\n\n # Pre-calculate probabilities for each state as array\n betabinom_pmfs, tree_pmfs = {}, {}\n e_dists_rv = {}\n for s, e_dist in e_dists_norm.items():\n a, b, pi, q0, q1, p0, p1 = [e_dist[param] for param in ['a', 'b', 'pi', 'q0', 'q1', 'p0', 'p1']]\n betabinom_pmf = utils.get_betabinom_pmf(emit_seq, n, a, b)\n tree_pmf = utils.get_tree_pmf(tree, pi, q0, q1, p0, p1)\n\n betabinom_pmfs[s] = betabinom_pmf\n tree_pmfs[s] = tree_pmf\n e_dists_rv[s] = utils.ArrayRV(betabinom_pmf * tree_pmf)\n\n # Instantiate model and get expectations\n model = hmm.HMM(t_dists_norm, e_dists_rv, start_dist)\n idx_seq = list(range(len(state_seq))) # Everything is pre-calculated, so emit_seq is the emit index\n fs, ss_f = model.forward(idx_seq)\n bs, ss_b = model.backward(idx_seq)\n nis = model.forward_backward1(idx_seq, fs, ss_f, bs, ss_b)\n nijs = model.forward_backward2(idx_seq, fs, ss_f, bs, ss_b)\n\n # Calculate likelihood\n px = reduce(lambda x, y: x + y, map(log, ss_f))\n pxy = model.joint_likelihood(idx_seq, state_seq)\n ll = pxy - px\n\n # Get t_dists gradients\n t_grads = {}\n for s1, t_dist in t_dists_norm.items():\n t_grad = {}\n mn_sum = sum([mijs[(s1, s2)] - nijs[(s1, s2)] for s2 in t_dist])\n for s2, p in t_dist.items():\n t_grad[s2] = -(mijs[(s1, s2)] - nijs[(s1, s2)] - p * mn_sum) # Equation 2.20\n t_grads[s1] = t_grad\n\n # Get e_dists gradients\n e_grads = {}\n for s, e_dist in e_dists_norm.items():\n a, b, pi, q0, q1, p0, p1 = [e_dist[param] for param in ['a', 'b', 'pi', 'q0', 'q1', 'p0', 'p1']]\n betabinom_pmf = betabinom_pmfs[s]\n betabinom_prime_a = utils.get_betabinom_prime(emit_seq, n, a, b, 'a')\n betabinom_prime_b = utils.get_betabinom_prime(emit_seq, n, a, b, 'b')\n tree_pmf = tree_pmfs[s]\n tree_prime_pi = utils.get_tree_prime(tree, pi, q0, q1, p0, p1, 'pi')\n tree_prime_q0 = utils.get_tree_prime(tree, pi, q0, q1, p0, p1, 'q0')\n tree_prime_q1 = utils.get_tree_prime(tree, pi, q0, q1, p0, p1, 'q1')\n tree_prime_p0 = utils.get_tree_prime(tree, pi, q0, q1, p0, p1, 'p0')\n tree_prime_p1 = utils.get_tree_prime(tree, pi, q0, q1, p0, p1, 'p1')\n\n # Equations 2.15 and 2.16 (emission parameter phi only)\n e_grad = {}\n mn = np.array([mi - ni for mi, ni in zip(mis[s], nis[s])])\n e_grad['a'] = -mn / betabinom_pmf * betabinom_prime_a * a\n e_grad['b'] = -mn / betabinom_pmf * betabinom_prime_b * b\n e_grad['pi'] = -mn / tree_pmf * tree_prime_pi * pi * (1 - pi)\n e_grad['q0'] = -mn / tree_pmf * tree_prime_q0 * q0\n e_grad['q1'] = -mn / tree_pmf * tree_prime_q1 * q1\n e_grad['p0'] = -mn / tree_pmf * tree_prime_p0 * p0 * (1 - p0)\n e_grad['p1'] = -mn / tree_pmf * tree_prime_p1 * p1 * (1 - p1)\n e_grads[s] = e_grad\n\n return {'ll': ll, 't_grads': t_grads, 'e_grads': e_grads}\n\n\nnum_processes = int(os.environ['SLURM_CPUS_ON_NODE'])\nspid_regex = r'spid=([a-z]+)'\n\neta = 0.05 # Learning rate\ngamma = 0.85 # Momentum\nepsilon = 1E-1 # Convergence criterion\niter_num = 300 # Max number of iterations\n\nstate_set = {'1A', '1B', '2', '3'}\nstart_set = {'1A', '1B', '2', '3'}\nt_sets = {s1: {s2 for s2 in state_set} for s1 in state_set}\ntree_template = skbio.read('../../ortho_tree/consensus_GTR2/out/NI.nwk', 'newick', skbio.TreeNode)\n\nt_pseudo = 0.1 # t_dist pseudocounts\nstart_pseudo = 0.1 # start_dist pseudocounts\ne_dists_initial = {'1A': {'a': 0.9, 'b': 0.1, 'pi': 0.95, 'q0': 0.01, 'q1': 0.01, 'p0': 0.01, 'p1': 0.05},\n '1B': {'a': 1, 'b': 0.4, 'pi': 0.5, 'q0': 0.2, 'q1': 0.25, 'p0': 0.015, 'p1': 0.05},\n '2': {'a': 0.7, 'b': 0.15, 'pi': 0.75, 'q0': 0.05, 'q1': 0.075, 'p0': 0.1, 'p1': 0.4},\n '3': {'a': 1.6, 'b': 0.35, 'pi': 0.01, 'q0': 0.01, 'q1': 0.01, 'p0': 0.025, 'p1': 0.01}}\n\nif __name__ == '__main__':\n # Load labels\n OGid2labels = {}\n label_set = set()\n with open('labels.tsv') as file:\n field_names = file.readline().rstrip('\\n').split('\\t')\n for line in file:\n fields = {key: value for key, value in zip(field_names, line.rstrip('\\n').split('\\t'))}\n OGid, start, stop, label = fields['OGid'], int(fields['start']), int(fields['stop']), fields['label']\n label_set.add(label)\n try:\n OGid2labels[OGid].append((start, stop, label))\n except KeyError:\n OGid2labels[OGid] = [(start, stop, label)]\n\n if state_set != label_set:\n raise RuntimeError('label_set is not equal to state_set')\n\n # Check label validity\n for OGid, labels in OGid2labels.items():\n start0, stop0, label0 = labels[0]\n if start0 != 0:\n print(f'First interval for {OGid} does not begin at 0')\n for start, stop, label in labels[1:]:\n if label0 == label:\n print(f'State for interval ({OGid}, {start}, {stop}) equals previous state')\n if stop0 != start:\n print(f'Start for interval ({OGid}, {start}, {stop}) does not equal previous stop')\n if start >= stop:\n print(f'Start for interval ({OGid}, {start}, {stop}) is greater than stop')\n stop0, label0 = stop, label\n\n # Convert MSAs to records containing state-emissions sequences and other data\n records = []\n for OGid, labels in OGid2labels.items():\n # Load MSA\n msa = []\n for header, seq in read_fasta(f'../realign_hmmer/out/mafft/{OGid}.afa'):\n spid = re.search(spid_regex, header).group(1)\n msa.append({'spid': spid, 'seq': seq})\n\n # Create emission sequence\n column0 = []\n emit_seq = []\n for j in range(len(msa[0]['seq'])):\n column = [1 if msa[i]['seq'][j] in ['-', '.'] else 0 for i in range(len(msa))]\n emit0 = sum([c0 == c for c0, c in zip(column0, column)])\n emit_seq.append(emit0) # The tree probabilities are pre-calculated, so emission value is its index\n column0 = column\n emit_seq = np.array(emit_seq)\n\n # Load tree and convert to vectors at tips\n tree = tree_template.shear([record['spid'] for record in msa])\n tips = {tip.name: tip for tip in tree.tips()}\n for record in msa:\n spid, seq = record['spid'], record['seq']\n conditional = np.zeros((2, len(seq)))\n for j, sym in enumerate(seq):\n if sym in ['-', '.']:\n conditional[0, j] = 1\n else:\n conditional[1, j] = 1\n tip = tips[spid]\n tip.conditional = conditional\n\n # Create state sequence\n state_seq = []\n for start, stop, label in labels:\n state_seq.extend((stop - start) * [label])\n\n # Create count dictionaries\n mis = hmm.count_states(state_seq, state_set)\n mijs = hmm.count_transitions(state_seq, t_sets)\n\n records.append({'OGid': OGid, 'n': len(msa), 'tree': tree, 'state_seq': state_seq, 'emit_seq': emit_seq,\n 'mis': mis, 'mijs': mijs})\n\n # Calculate start_dist from background distribution of states\n state_counts = {s: start_pseudo for s in start_set}\n for labels in OGid2labels.values():\n for start, stop, label in labels:\n state_counts[label] += stop - start\n state_sum = sum(state_counts.values())\n start_dist = {s: count / state_sum for s, count in state_counts.items()}\n\n # Initialize t_dist from observed transitions\n t_counts = {s1: {s2: t_pseudo for s2 in t_set} for s1, t_set in t_sets.items()}\n for labels in OGid2labels.values():\n start, stop, label0 = labels[0]\n t_counts[label0][label0] += stop - start - 1\n for start, stop, label1 in labels:\n t_counts[label0][label1] += 1\n t_counts[label1][label1] += stop - start - 1\n label0 = label1\n t_dists_norm = {}\n for s1, t_count in t_counts.items():\n t_sum = sum(t_count.values())\n t_dists_norm[s1] = {s2: count / t_sum for s2, count in t_count.items()}\n\n # Initialize e_dists from initial values\n e_dists_norm = e_dists_initial.copy()\n\n # Gradient descent\n t_dists, e_dists = unnorm_params(t_dists_norm, e_dists_norm)\n t_momenta = {s1: {s2: None for s2 in t_dist} for s1, t_dist in t_dists.items()}\n e_momenta = {s: {param: None for param in e_dist} for s, e_dist in e_dists.items()}\n ll0 = None\n history = []\n for i in range(1, iter_num + 1):\n # Calculate expectations and likelihoods\n t_dists_norm, e_dists_norm = norm_params(t_dists, e_dists)\n with mp.Pool(processes=num_processes) as pool:\n gradients = pool.starmap(get_gradients, [(t_dists_norm, e_dists_norm, start_dist, record) for record in records])\n\n # Save and report parameters from previous update\n ll = sum([gradient['ll'] for gradient in gradients])\n history.append({'iter_num': i, 'll': ll, 't_dists_norm': t_dists_norm, 'e_dists_norm': e_dists_norm})\n\n print(f'ITERATION {i} / {iter_num}')\n print('\\tll:', ll)\n print('\\tt_dists_norm:', t_dists_norm)\n print('\\te_dists_norm:', e_dists_norm)\n\n # Check convergence\n if i > 1 and abs(ll - ll0) < epsilon:\n break\n ll0 = ll\n\n # Accumulate and apply gradients\n for s1, t_dist in t_dists.items():\n for s2 in t_dist:\n grad_stack = np.hstack([gradient['t_grads'][s1][s2] for gradient in gradients])\n if i > 1:\n dz = gamma * t_momenta[s1][s2] + eta * grad_stack.sum() / len(grad_stack)\n else:\n dz = eta * grad_stack.sum() / len(grad_stack)\n t_dist[s2] -= dz\n t_momenta[s1][s2] = dz\n\n for s, e_dist in e_dists.items():\n for param in e_dist:\n grad_stack = np.hstack([gradient['e_grads'][s][param] for gradient in gradients])\n if i > 1:\n dz = gamma * e_momenta[s][param] + eta * grad_stack.sum() / len(grad_stack)\n else:\n dz = eta * grad_stack.sum() / len(grad_stack)\n e_dists[s][param] -= dz\n e_momenta[s][param] = dz\n\n # Save history and best model parameters\n if not os.path.exists('out/'):\n os.mkdir('out/')\n\n with open('out/history.json', 'w') as file:\n json.dump(history, file, indent='\\t')\n with open('out/model.json', 'w') as file:\n model = max(history, key=lambda x: x['ll'])\n json.dump({'t_dists': model['t_dists_norm'], 'e_dists': model['e_dists_norm'], 'start_dist': start_dist}, file, indent='\\t')\n\n\"\"\"\nNOTES\nThis HMM uses a two-state phylo-CTMC emission distribution on the gap patterns. It also uses a Bernoulli distribution on\nif the pattern of gaps is the same as in the previous column. The parameters are trained discriminatively using gradient\ndescent.\n\nThe gradients are calculated using the formulas in:\nKrogh A, Riis SK. Hidden Neural Networks. Neural Computation. 11, 541-563. 1999.\n\nDEPENDENCIES\n../../ortho_tree/consensus_GTR2/consensus_GTR2.py\n ../../ortho_tree/consensus_GTR2/out/NI.nwk\n../realign_hmmer/realign_hmmer.py\n ../realign_hmmer/out/mafft/*.afa\n./labels.tsv\n\"\"\"","sub_path":"analysis/ortho_MSA/insertion_hmm/fit.py","file_name":"fit.py","file_ext":"py","file_size_in_byte":13429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"515791132","text":"\"\"\"Helper functions for creating/checking the server push files.\"\"\"\nimport requests\nfrom pathlib import Path\nfrom dataclasses import dataclass\nfrom gftools.utils import read_proto\nimport gftools.fonts_public_pb2 as fonts_pb2\n\n\nSANDBOX_URL = \"https://fonts.sandbox.google.com/metadata/fonts\"\nPRODUCTION_URL = \"https://fonts.google.com/metadata/fonts\"\n\nPUSH_STATUS_TEMPLATE = \"\"\"\n***{} Status***\nNew families:\n{}\n\nExisting families, last pushed:\n{}\n\"\"\"\n\n\n@dataclass\nclass PushItem:\n path: Path\n raw: str\n type: str\n\n def to_json(self):\n return {\"path\": str(self.path), \"type\": self.type, \"raw\": self.raw}\n\n\ndef parse_server_file(fp):\n results = []\n with open(fp) as doc:\n lines = doc.read().split(\"\\n\")\n category = \"Unknown\"\n for line in lines:\n if not line:\n continue\n if line.startswith(\"#\"):\n category = line[1:].strip()\n elif \"#\" in line:\n path = line.split(\"#\")[0].strip()\n item = PushItem(Path(path), line, category)\n results.append(item)\n else:\n item = PushItem(Path(line), line, category)\n results.append(item)\n return results\n\n\ndef is_family_dir(path):\n return any(t for t in (\"ofl\", \"apache\", \"ufl\") if t in path.parts if \"article\" not in str(path))\n\n\ndef family_dir_name(path):\n metadata_file = path / \"METADATA.pb\"\n assert metadata_file.exists(), f\"no metadata for {path}\"\n return read_proto(metadata_file, fonts_pb2.FamilyProto()).name\n\n\ndef gf_server_metadata(url):\n \"\"\"Get family json data from a Google Fonts metadata url\"\"\"\n # can't do requests.get(\"url\").json() since request text starts with \")]}'\"\n info = requests.get(url).json()\n return {i[\"family\"]: i for i in info[\"familyMetadataList\"]}\n\n\ndef server_push_status(fp, url):\n dirs = [fp.parent / p.path for p in parse_server_file(fp)]\n family_dirs = [d for d in dirs if is_family_dir(d)]\n family_names = [family_dir_name(d) for d in family_dirs]\n\n gf_meta = gf_server_metadata(url)\n\n new_families = [f for f in family_names if f not in gf_meta]\n existing_families = [f for f in family_names if f in gf_meta]\n\n gf_families = sorted(\n [gf_meta[f] for f in existing_families], key=lambda k: k[\"lastModified\"]\n )\n existing_families = [f\"{f['family']}: {f['lastModified']}\" for f in gf_families]\n return new_families, existing_families\n\n\ndef server_push_report(name, fp, server_url):\n new_families, existing_families = server_push_status(fp, server_url)\n new = \"\\n\".join(new_families) if new_families else \"N/A\"\n existing = \"\\n\".join(existing_families) if existing_families else \"N/A\"\n print(PUSH_STATUS_TEMPLATE.format(name, new, existing))\n\n\ndef push_report(fp):\n prod_path = fp / \"to_production.txt\"\n server_push_report(\"Production\", prod_path, PRODUCTION_URL)\n\n sandbox_path = fp / \"to_sandbox.txt\"\n server_push_report(\"Sandbox\", sandbox_path, SANDBOX_URL)\n\n\n# The internal Google fonts team store the axisregistry and lang directories\n# in a different location. The two functions below tranform paths to\n# whichever representation you need.\ndef repo_path_to_google_path(fp):\n \"\"\"lang/Lib/gflanguages/data/languages/.*.textproto --> lang/languages/.*.textproto\"\"\"\n # we rename lang paths due to: https://github.com/google/fonts/pull/4679\n if \"gflanguages\" in fp.parts:\n return Path(\"lang\") / fp.relative_to(\"lang/Lib/gflanguages/data\")\n # https://github.com/google/fonts/pull/5147\n elif \"axisregistry\" in fp.parts:\n return Path(\"axisregistry\") / fp.name\n else:\n raise ValueError(f\"No transform found for path {fp}\")\n\n\ndef google_path_to_repo_path(fp):\n \"\"\"lang/languages/.*.textproto --> lang/Lib/gflanguages/data/languages/.*.textproto\"\"\"\n if \"lang\" in fp.parts:\n Path(\"lang/Lib/gflanguages/data/\") / fp.relative_to(\"lang\")\n elif \"axisregistry\" in fp.parts:\n return fp.parent / \"Lib\" / \"axisregistry\" / \"data\" / fp.name\n else:\n raise ValueError(f\"No transform found for path {fp}\")\n\n\ndef missing_paths(fp):\n paths = [fp.parent / p.path for p in parse_server_file(fp)]\n font_paths = [p for p in paths if any(d in p.parts for d in (\"ofl\", \"ufl\", \"apache\"))]\n lang_paths = [p for p in paths if \"lang\" in p.parts]\n axis_paths = [p for p in paths if \"axisregistry\" in p.parts]\n misc_paths = [p for p in paths if p not in font_paths+lang_paths+axis_paths]\n\n missing_paths = [p for p in misc_paths+font_paths if not p.exists()]\n missing_lang_files = [p for p in lang_paths if not google_path_to_repo_path(p).exists()]\n missing_axis_files = [p for p in axis_paths if not google_path_to_repo_path(p).exists()]\n return missing_paths + missing_lang_files + missing_axis_files\n\n\ndef lint_server_files(fp):\n template = \"{}: Following paths are not valid:\\n{}\\n\\n\"\n footnote = (\n \"lang and axisregistry dir paths need to be transformed.\\n\"\n \"See https://github.com/googlefonts/gftools/issues/603\"\n )\n\n prod_path = fp / \"to_production.txt\"\n prod_missing = \"\\n\".join(map(str, missing_paths(prod_path)))\n prod_msg = template.format(\"to_production.txt\", prod_missing)\n\n sandbox_path = fp / \"to_sandbox.txt\"\n sandbox_missing = \"\\n\".join(map(str, missing_paths(sandbox_path)))\n sandbox_msg = template.format(\"to_sandbox.txt\", sandbox_missing)\n\n if prod_missing and sandbox_missing:\n raise ValueError(prod_msg + sandbox_msg + footnote)\n elif prod_missing:\n raise ValueError(prod_msg + footnote)\n elif sandbox_missing:\n raise ValueError(sandbox_msg + footnote)\n else:\n print(\"Server files have valid paths\")\n","sub_path":"Lib/gftools/push.py","file_name":"push.py","file_ext":"py","file_size_in_byte":5719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"322791583","text":"import pygame\nimport sys\nimport os\n\n\npygame.init() # initialize all pygame modules\n# Vars\nscreenWidth = 1280\nscreenHeight = 720\nsize = screenWidth, screenHeight # this is a tuple\ntime = 0\ntitle = 'PyPoker'\nblankTimer = 0\nvelocity = [1, 1] # one pixel movement at a time consider this a vector\nblack = 0, 0, 0\ntable = 'tableTop.jpg'\n# -----------------------------------------------------------------------\n\nsize = (screenWidth, screenHeight)\nscreen = pygame.display.set_mode(size) # init a display returns a surface\n\npygame.display.set_caption(title)\n\n# now we can load an image and assign it to a rect object to manipulate\ncard = pygame.image.load('5c.png') # returns a surface object\ncard1 = pygame.image.load('ac.png')\ncard2 = pygame.image.load('ad.png')\ntableTop = pygame.image.load(table)\n\ncardRect = card.get_rect() # returns a rect obj the area of the surface\ncard1Rect = card1.get_rect()\ncard2Rect = card2.get_rect()\n\n# Start infinite Loop\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT: # checking for a quit event to occur\n sys.exit() # quit (from sys module, must be imported )\n\n cardRect = cardRect.move(velocity)\n\n if cardRect.bottom > screenHeight or cardRect.top < 0:\n velocity[1] = -velocity[1]\n\n if cardRect.right > screenWidth or cardRect.left < 0:\n velocity[0] = -velocity[0]\n\n '''\n print \"Top: %s\" % cardRect.top\n print \"Bottom: %s\" % cardRect.bottom\n print \"Left: %s\" % cardRect.left\n print \"Right: %s \\n\" % cardRect.right\n '''\n\n # screen.fill(black)\n screen.blit(tableTop, [0, 0])\n screen.blit(card, cardRect)\n\n\n pygame.time.wait(2)\n\n '''\n time += 1\n\n if time == 50:\n time = 0\n print \"Time reached 50, reset:\"\n '''\n pygame.display.flip()\n\n blankTimer += 1\n\n","sub_path":"guiTest.py","file_name":"guiTest.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"84596581","text":"from __future__ import division, absolute_import, print_function\n\n__copyright__ = \"Copyright (C) 2010-2013 Andreas Kloeckner\"\n\n__license__ = \"\"\"\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\nimport six\nfrom functools import reduce\n\nfrom pymbolic.mapper.stringifier import (\n CSESplittingStringifyMapperMixin,\n PREC_NONE, PREC_PRODUCT)\nfrom pymbolic.mapper import (\n Mapper,\n CSECachingMapperMixin\n )\nfrom pymbolic.mapper.dependency import (\n DependencyMapper as DependencyMapperBase)\nfrom pymbolic.geometric_algebra import componentwise\nfrom pymbolic.geometric_algebra.mapper import (\n CombineMapper as CombineMapperBase,\n IdentityMapper as IdentityMapperBase,\n Collector as CollectorBase,\n DerivativeBinder as DerivativeBinderBase,\n EvaluationMapper as EvaluationMapperBase,\n\n StringifyMapper as BaseStringifyMapper,\n\n DerivativeSourceAndNablaComponentCollector\n as DerivativeSourceAndNablaComponentCollectorBase,\n NablaComponentToUnitVector\n as NablaComponentToUnitVectorBase,\n DerivativeSourceFinder\n as DerivativeSourceFinderBase,\n\n GraphvizMapper as GraphvizMapperBase)\nimport pytential.symbolic.primitives as prim\n\n\nclass IdentityMapper(IdentityMapperBase):\n def map_node_sum(self, expr):\n return type(expr)(self.rec(expr.operand))\n\n map_node_max = map_node_sum\n\n def map_elementwise_sum(self, expr):\n return type(expr)(self.rec(expr.operand), expr.dofdesc)\n\n map_elementwise_min = map_elementwise_sum\n map_elementwise_max = map_elementwise_sum\n\n def map_num_reference_derivative(self, expr):\n return type(expr)(expr.ref_axes, self.rec(expr.operand),\n expr.dofdesc)\n\n # {{{ childless -- no need to rebuild\n\n def map_ones(self, expr):\n return expr\n\n map_q_weight = map_ones\n map_node_coordinate_component = map_ones\n map_parametrization_gradient = map_ones\n map_parametrization_derivative = map_ones\n\n # }}}\n\n def map_inverse(self, expr):\n return type(expr)(\n # don't recurse into expression--it is a separate world that\n # will be processed once it's executed.\n\n expr.expression, self.rec(expr.rhs), expr.variable_name,\n dict([\n (name, self.rec(name_expr))\n for name, name_expr in six.iteritems(expr.extra_vars)]),\n expr.dofdesc)\n\n def map_int_g(self, expr):\n return expr.copy(\n density=self.rec(expr.density),\n kernel_arguments=dict(\n (name, self.rec(arg_expr))\n for name, arg_expr in expr.kernel_arguments.items()\n ))\n\n def map_interpolation(self, expr):\n return type(expr)(expr.from_dd, expr.to_dd, self.rec(expr.operand))\n\n\nclass CombineMapper(CombineMapperBase):\n def map_node_sum(self, expr):\n return self.rec(expr.operand)\n\n map_node_max = map_node_sum\n map_num_reference_derivative = map_node_sum\n map_elementwise_sum = map_node_sum\n map_elementwise_min = map_node_sum\n map_elementwise_max = map_node_sum\n map_interpolation = map_node_sum\n\n def map_int_g(self, expr):\n return self.combine(\n [self.rec(expr.density)]\n + [self.rec(arg_expr)\n for arg_expr in expr.kernel_arguments.values()])\n\n def map_inverse(self, expr):\n return self.combine([\n self.rec(expr.rhs)] + [\n (self.rec(name_expr)\n for name_expr in six.itervalues(expr.extra_vars))\n ])\n\n\nclass Collector(CollectorBase, CombineMapper):\n def map_ones(self, expr):\n return set()\n\n map_node_coordinate_component = map_ones\n map_parametrization_derivative = map_ones\n map_q_weight = map_ones\n\n\nclass OperatorCollector(Collector):\n def map_int_g(self, expr):\n return set([expr]) | Collector.map_int_g(self, expr)\n\n\nclass DependencyMapper(DependencyMapperBase, Collector):\n pass\n\n\nclass EvaluationMapper(EvaluationMapperBase):\n \"\"\"Unlike :mod:`pymbolic.mapper.evaluation.EvaluationMapper`, this class\n does evaluation mostly to get :class:`pymbolic.geometric_algebra.MultiVector`\n instances to do their thing, and perhaps to automatically kill terms\n that are multiplied by zero. Otherwise it intends to largely preserve\n the structure of the input expression.\n \"\"\"\n\n def map_variable(self, expr):\n return expr\n\n def map_subscript(self, expr):\n return self.rec(expr.aggregate)[self.rec(expr.index)]\n\n map_q_weight = map_variable\n map_ones = map_variable\n\n def map_node_sum(self, expr):\n return componentwise(type(expr), self.rec(expr.operand))\n\n map_node_max = map_node_sum\n\n def map_node_coordinate_component(self, expr):\n return expr\n\n def map_num_reference_derivative(self, expr):\n return componentwise(\n lambda subexpr: type(expr)(\n expr.ref_axes, self.rec(subexpr), expr.dofdesc),\n expr.operand)\n\n def map_int_g(self, expr):\n return componentwise(\n lambda subexpr: type(expr)(\n expr.kernel,\n self.rec(subexpr),\n expr.qbx_forced_limit, expr.source, expr.target,\n kernel_arguments=dict(\n (name, self.rec(arg_expr))\n for name, arg_expr in expr.kernel_arguments.items()\n )),\n expr.density)\n\n def map_common_subexpression(self, expr):\n return prim.cse(\n self.rec(expr.child),\n expr.prefix,\n expr.scope)\n\n\n# {{{ dofdesc tagging\n\nclass LocationTagger(CSECachingMapperMixin, IdentityMapper):\n \"\"\"Used internally by :class:`ToTargetTagger`.\"\"\"\n\n def __init__(self, default_where, default_source=prim.DEFAULT_SOURCE):\n self.default_source = default_source\n self.default_where = default_where\n\n map_common_subexpression_uncached = \\\n IdentityMapper.map_common_subexpression\n\n def _default_dofdesc(self, dofdesc):\n if dofdesc.geometry is None:\n if dofdesc.discr_stage is None \\\n and dofdesc.granularity == prim.GRANULARITY_NODE:\n dofdesc = dofdesc.copy(geometry=self.default_where)\n else:\n dofdesc = dofdesc.copy(geometry=self.default_source)\n\n return dofdesc\n\n def map_ones(self, expr):\n return type(expr)(dofdesc=self._default_dofdesc(expr.dofdesc))\n\n map_q_weight = map_ones\n\n def map_parametrization_derivative_component(self, expr):\n return type(expr)(\n expr.ambient_axis,\n expr.ref_axis,\n self._default_dofdesc(expr.dofdesc))\n\n def map_node_coordinate_component(self, expr):\n return type(expr)(\n expr.ambient_axis,\n self._default_dofdesc(expr.dofdesc))\n\n def map_num_reference_derivative(self, expr):\n return type(expr)(\n expr.ref_axes,\n self.rec(expr.operand),\n self._default_dofdesc(expr.dofdesc))\n\n def map_elementwise_sum(self, expr):\n return type(expr)(\n self.rec(expr.operand),\n self._default_dofdesc(expr.dofdesc))\n\n map_elementwise_min = map_elementwise_sum\n map_elementwise_max = map_elementwise_sum\n\n def map_int_g(self, expr):\n source = expr.source\n if source.geometry is None:\n source = source.copy(geometry=self.default_source)\n\n target = expr.target\n if target.geometry is None:\n target = target.copy(geometry=self.default_where)\n\n return type(expr)(\n expr.kernel,\n self.operand_rec(expr.density),\n expr.qbx_forced_limit, source, target,\n kernel_arguments=dict(\n (name, self.operand_rec(arg_expr))\n for name, arg_expr in expr.kernel_arguments.items()\n ))\n\n def map_inverse(self, expr):\n dofdesc = expr.dofdesc\n if dofdesc.geometry is None:\n dofdesc = dofdesc.copy(geometry=self.default_where)\n\n return type(expr)(\n # don't recurse into expression--it is a separate world that\n # will be processed once it's executed.\n\n expr.expression, self.rec(expr.rhs), expr.variable_name,\n dict([\n (name, self.rec(name_expr))\n for name, name_expr in six.iteritems(expr.extra_vars)]),\n dofdesc)\n\n def map_interpolation(self, expr):\n from_dd = expr.from_dd\n if from_dd.geometry is None:\n from_dd = from_dd.copy(geometry=self.default_source)\n\n to_dd = expr.to_dd\n if to_dd.geometry is None:\n to_dd = to_dd.copy(geometry=self.default_source)\n\n return type(expr)(from_dd, to_dd, self.operand_rec(expr.operand))\n\n def operand_rec(self, expr):\n return self.rec(expr)\n\n\nclass ToTargetTagger(LocationTagger):\n \"\"\"Descends into the expression tree, marking expressions based on two\n heuristics:\n\n * everything up to the first layer potential operator is marked as\n operating on the targets, and everything below there as operating on the\n source.\n * if an expression has a :class:`~pytential.symbolic.primitives.DOFDescriptor`\n that requires a :class:`~pytential.source.LayerPotentialSourceBase` to be\n used (e.g. by being defined on\n :class:`~pytential.symbolic.primitives.QBX_SOURCE_QUAD_STAGE2`), then\n it is marked as operating on a source.\n \"\"\"\n\n def __init__(self, default_source, default_target):\n LocationTagger.__init__(self, default_target,\n default_source=default_source)\n self.operand_rec = LocationTagger(default_source,\n default_source=default_source)\n\n\nclass DiscretizationStageTagger(IdentityMapper):\n \"\"\"Descends into an expression tree and changes the\n :attr:`~pytential.symbolic.primitives.DOFDescriptor.discr_stage` to\n :attr:`discr_stage`.\n\n .. attribute:: discr_stage\n\n The new discretization for the DOFs in the expression. For valid\n values, see\n :attr:`~pytential.symbolic.primitives.DOFDescriptor.discr_stage`.\n \"\"\"\n\n def __init__(self, discr_stage):\n if not (discr_stage == prim.QBX_SOURCE_STAGE1\n or discr_stage == prim.QBX_SOURCE_STAGE2\n or discr_stage == prim.QBX_SOURCE_QUAD_STAGE2):\n raise ValueError('unknown discr stage tag: \"{}\"'.format(discr_stage))\n\n self.discr_stage = discr_stage\n\n def map_node_coordinate_component(self, expr):\n dofdesc = expr.dofdesc\n if dofdesc.discr_stage == self.discr_stage:\n return expr\n\n return type(expr)(\n expr.ambient_axis,\n dofdesc.copy(discr_stage=self.discr_stage))\n\n def map_num_reference_derivative(self, expr):\n dofdesc = expr.dofdesc\n if dofdesc.discr_stage == self.discr_stage:\n return expr\n\n return type(expr)(\n expr.ref_axes,\n self.rec(expr.operand),\n dofdesc.copy(discr_stage=self.discr_stage))\n\n# }}}\n\n\n# {{{ derivative binder\n\nclass DerivativeTaker(Mapper):\n def __init__(self, ambient_axis):\n self.ambient_axis = ambient_axis\n\n def map_sum(self, expr):\n from pymbolic.primitives import flattened_sum\n return flattened_sum(tuple(self.rec(child) for child in expr.children))\n\n def map_product(self, expr):\n from pymbolic.primitives import is_constant\n const = []\n nonconst = []\n for subexpr in expr.children:\n if is_constant(subexpr):\n const.append(subexpr)\n else:\n nonconst.append(subexpr)\n\n if len(nonconst) > 1:\n raise RuntimeError(\"DerivativeTaker doesn't support products with \"\n \"more than one non-constant\")\n\n if not nonconst:\n nonconst = [1]\n\n from pytools import product\n return product(const) * self.rec(nonconst[0])\n\n def map_int_g(self, expr):\n from sumpy.kernel import AxisTargetDerivative\n return expr.copy(kernel=AxisTargetDerivative(self.ambient_axis, expr.kernel))\n\n\nclass DerivativeSourceAndNablaComponentCollector(\n Collector,\n DerivativeSourceAndNablaComponentCollectorBase):\n pass\n\n\nclass NablaComponentToUnitVector(\n EvaluationMapper,\n NablaComponentToUnitVectorBase):\n pass\n\n\nclass DerivativeSourceFinder(EvaluationMapper,\n DerivativeSourceFinderBase):\n pass\n\n\nclass DerivativeBinder(DerivativeBinderBase, IdentityMapper):\n derivative_source_and_nabla_component_collector = \\\n DerivativeSourceAndNablaComponentCollector\n nabla_component_to_unit_vector = NablaComponentToUnitVector\n derivative_source_finder = DerivativeSourceFinder\n\n def take_derivative(self, ambient_axis, expr):\n return DerivativeTaker(ambient_axis)(expr)\n\n# }}}\n\n\n# {{{ Unregularized preprocessor\n\nclass UnregularizedPreprocessor(IdentityMapper):\n\n def __init__(self, source_name, places):\n self.source_name = source_name\n self.places = places\n\n def map_int_g(self, expr):\n if expr.qbx_forced_limit in (-1, 1):\n raise ValueError(\n \"Unregularized evaluation does not support one-sided limits\")\n\n expr = expr.copy(\n qbx_forced_limit=None,\n kernel=expr.kernel,\n density=self.rec(expr.density),\n kernel_arguments=dict(\n (name, self.rec(arg_expr))\n for name, arg_expr in expr.kernel_arguments.items()\n ))\n\n return expr\n\n# }}}\n\n\n# {{{ interpolation preprocessor\n\nclass InterpolationPreprocessor(IdentityMapper):\n \"\"\"Handle expressions that require upsampling or downsampling by inserting\n a :class:`~pytential.symbolic.primitives.Interpolation`. This is used to\n\n * do differentiation on\n :attr:`~pytential.source.LayerPotentialSource.quad_stage2_density_discr`,\n by performing it on\n :attr:`~pytential.source.LayerPotentialSource.stage2_density_discr` and\n upsampling.\n * upsample layer potential sources to\n :attr:`~pytential.source.LayerPotentialSource.quad_stage2_density_discr`,\n \"\"\"\n\n def __init__(self, places):\n self.places = places\n self.from_discr_stage = prim.QBX_SOURCE_STAGE2\n self.tagger = DiscretizationStageTagger(self.from_discr_stage)\n\n def map_num_reference_derivative(self, expr):\n to_dd = expr.dofdesc\n if to_dd.discr_stage != prim.QBX_SOURCE_QUAD_STAGE2:\n return expr\n\n from pytential.qbx import QBXLayerPotentialSource\n lpot_source = self.places.get_geometry(to_dd)\n if not isinstance(lpot_source, QBXLayerPotentialSource):\n return expr\n\n from_dd = to_dd.copy(discr_stage=self.from_discr_stage)\n return prim.interp(from_dd, to_dd, self.rec(self.tagger(expr)))\n\n def map_int_g(self, expr):\n from_dd = expr.source\n if from_dd.discr_stage is not None:\n return expr\n\n from pytential.qbx import QBXLayerPotentialSource\n lpot_source = self.places.get_geometry(from_dd)\n if not isinstance(lpot_source, QBXLayerPotentialSource):\n return expr\n\n to_dd = from_dd.copy(discr_stage=prim.QBX_SOURCE_QUAD_STAGE2)\n density = prim.interp(from_dd, to_dd, self.rec(expr.density))\n kernel_arguments = dict(\n (name, prim.interp(from_dd, to_dd, self.rec(arg_expr)))\n for name, arg_expr in expr.kernel_arguments.items())\n\n return expr.copy(\n kernel=expr.kernel,\n density=density,\n kernel_arguments=kernel_arguments,\n source=to_dd,\n target=expr.target)\n\n# }}}\n\n\n# {{{ QBX preprocessor\n\nclass QBXPreprocessor(IdentityMapper):\n def __init__(self, source_name, places):\n self.source_name = source_name\n self.places = places\n\n def map_int_g(self, expr):\n if expr.source.geometry != self.source_name:\n return expr\n\n source_discr = self.places.get_discretization(expr.source)\n target_discr = self.places.get_discretization(expr.target)\n\n if expr.qbx_forced_limit == 0:\n raise ValueError(\"qbx_forced_limit == 0 was a bad idea and \"\n \"is no longer supported. Use qbx_forced_limit == 'avg' \"\n \"to request two-sided averaging explicitly if needed.\")\n\n is_self = source_discr is target_discr\n\n expr = expr.copy(\n kernel=expr.kernel,\n density=self.rec(expr.density),\n kernel_arguments=dict(\n (name, self.rec(arg_expr))\n for name, arg_expr in expr.kernel_arguments.items()\n ))\n\n if not is_self:\n # non-self evaluation\n if expr.qbx_forced_limit in ['avg', 1, -1]:\n raise ValueError(\"May not specify +/-1 or \\\"avg\\\" for \"\n \"qbx_forced_limit for non-self evaluation. \"\n \"Specify 'None' for automatic choice or +/-2 \"\n \"to force a QBX side in the near-evaluation \"\n \"regime.\")\n\n return expr\n\n if expr.qbx_forced_limit is None:\n raise ValueError(\"qbx_forced_limit == None is not supported \"\n \"for self evaluation--must pick evaluation side\")\n\n if (isinstance(expr.qbx_forced_limit, int)\n and abs(expr.qbx_forced_limit) == 2):\n raise ValueError(\"May not specify qbx_forced_limit == +/-2 \"\n \"for self-evaluation. \"\n \"Specify +/-1 or \\\"avg\\\" instead.\")\n\n if expr.qbx_forced_limit == \"avg\":\n return 0.5*(\n expr.copy(qbx_forced_limit=+1)\n + expr.copy(qbx_forced_limit=-1))\n else:\n return expr\n\n# }}}\n\n\n# {{{ stringifier\n\ndef stringify_where(where):\n return str(prim.as_dofdesc(where))\n\n\nclass StringifyMapper(BaseStringifyMapper):\n\n def map_ones(self, expr, enclosing_prec):\n return \"Ones[%s]\" % stringify_where(expr.dofdesc)\n\n def map_inverse(self, expr, enclosing_prec):\n return \"Solve(%s = %s {%s})\" % (\n self.rec(expr.expression, PREC_NONE),\n self.rec(expr.rhs, PREC_NONE),\n \", \".join(\"%s=%s\" % (var_name, self.rec(var_expr, PREC_NONE))\n for var_name, var_expr in six.iteritems(expr.extra_vars)))\n\n from operator import or_\n\n return self.rec(expr.rhs) | reduce(or_,\n (self.rec(name_expr)\n for name_expr in six.itervalues(expr.extra_vars)),\n set())\n\n def map_elementwise_sum(self, expr, enclosing_prec):\n return \"ElwiseSum[%s](%s)\" % (\n stringify_where(expr.dofdesc),\n self.rec(expr.operand, PREC_NONE))\n\n def map_elementwise_min(self, expr, enclosing_prec):\n return \"ElwiseMin[%s](%s)\" % (\n stringify_where(expr.dofdesc),\n self.rec(expr.operand, PREC_NONE))\n\n def map_elementwise_max(self, expr, enclosing_prec):\n return \"ElwiseMax[%s](%s)\" % (\n stringify_where(expr.dofdesc),\n self.rec(expr.operand, PREC_NONE))\n\n def map_node_max(self, expr, enclosing_prec):\n return \"NodeMax(%s)\" % self.rec(expr.operand, PREC_NONE)\n\n def map_node_sum(self, expr, enclosing_prec):\n return \"NodeSum(%s)\" % self.rec(expr.operand, PREC_NONE)\n\n def map_node_coordinate_component(self, expr, enclosing_prec):\n return \"x%d[%s]\" % (expr.ambient_axis,\n stringify_where(expr.dofdesc))\n\n def map_num_reference_derivative(self, expr, enclosing_prec):\n diff_op = \" \".join(\n \"d/dr%d\" % axis\n if mult == 1 else\n \"d/dr%d^%d\" % (axis, mult)\n for axis, mult in expr.ref_axes)\n\n result = \"%s[%s] %s\" % (\n diff_op,\n stringify_where(expr.dofdesc),\n self.rec(expr.operand, PREC_PRODUCT),\n )\n\n if enclosing_prec >= PREC_PRODUCT:\n return \"(%s)\" % result\n else:\n return result\n\n def map_parametrization_derivative(self, expr, enclosing_prec):\n return \"dx/dr[%s]\" % (stringify_where(expr.dofdesc))\n\n def map_q_weight(self, expr, enclosing_prec):\n return \"w_quad[%s]\" % stringify_where(expr.dofdesc)\n\n def _stringify_kernel_args(self, kernel_arguments):\n if not kernel_arguments:\n return \"\"\n else:\n return \"{%s}\" % \", \".join(\n \"%s: %s\" % (name, self.rec(arg_expr, PREC_NONE))\n for name, arg_expr in kernel_arguments.items())\n\n def map_int_g(self, expr, enclosing_prec):\n return u\"Int[%s->%s]@(%s)%s (%s * %s)\" % (\n stringify_where(expr.source),\n stringify_where(expr.target),\n expr.qbx_forced_limit,\n self._stringify_kernel_args(\n expr.kernel_arguments),\n expr.kernel,\n self.rec(expr.density, PREC_PRODUCT))\n\n def map_interpolation(self, expr, enclosing_prec):\n return \"Interp[%s->%s](%s)\" % (\n stringify_where(expr.from_dd),\n stringify_where(expr.to_dd),\n self.rec(expr.operand, PREC_PRODUCT))\n\n# }}}\n\n\nclass PrettyStringifyMapper(\n CSESplittingStringifyMapperMixin, StringifyMapper):\n pass\n\n\n# {{{ graphviz\n\nclass GraphvizMapper(GraphvizMapperBase):\n def __init__(self):\n super(GraphvizMapper, self).__init__()\n\n def map_pytential_leaf(self, expr):\n self.lines.append(\n \"%s [label=\\\"%s\\\", shape=box];\" % (\n self.get_id(expr),\n str(expr).replace(\"\\\\\", \"\\\\\\\\\")))\n\n if self.visit(expr, node_printed=True):\n self.post_visit(expr)\n\n map_ones = map_pytential_leaf\n\n def map_map_node_sum(self, expr):\n self.lines.append(\n \"%s [label=\\\"%s\\\",shape=circle];\" % (\n self.get_id(expr), type(expr).__name__))\n if not self.visit(expr, node_printed=True):\n return\n\n self.rec(expr.operand)\n self.post_visit(expr)\n\n map_node_coordinate_component = map_pytential_leaf\n map_num_reference_derivative = map_pytential_leaf\n map_parametrization_derivative = map_pytential_leaf\n\n map_q_weight = map_pytential_leaf\n\n def map_int_g(self, expr):\n descr = u\"Int[%s->%s]@(%d) (%s)\" % (\n stringify_where(expr.source),\n stringify_where(expr.target),\n expr.qbx_forced_limit,\n expr.kernel,\n )\n self.lines.append(\n \"%s [label=\\\"%s\\\",shape=box];\" % (\n self.get_id(expr), descr))\n if not self.visit(expr, node_printed=True):\n return\n\n self.rec(expr.density)\n for arg_expr in expr.kernel_arguments.values():\n self.rec(arg_expr)\n\n self.post_visit(expr)\n\n# }}}\n\n\n# vim: foldmethod=marker\n","sub_path":"pytential/symbolic/mappers.py","file_name":"mappers.py","file_ext":"py","file_size_in_byte":24576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"514359567","text":"# -*- coding: utf-8 -*-\nimport argparse\n\n\ndef args_parser():\n \"\"\" argument parser \"\"\"\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--contestant_submitted_file_name', type=str, default=\"test_pred_simple.json\",\n help=\"contestant submitted json file name\")\n\n args = parser.parse_args()\n\n return args\n","sub_path":"helmet_evaluation/utils/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"498593965","text":"from django.conf.urls import *\n\nfrom .views import *\n\nurlpatterns = [\n url(r'^all/$', all_forms, name=\"all-forms\"),\n url(r'^edit/(?P[-\\w\\d]+)/$', edit_form, name=\"edit-form\"),\n url(r'^options/$', form_options, name=\"form-options\"),\n url(r'^edit/config/(?P[-\\w\\d]+)/$', edit_config, name=\"edit-config\"),\n url(r'^edit/tips/(?P[-\\w\\d]+)/$', edit_tips, name=\"edit-tips\"),\n url(r'^responses/(?P[-\\w\\d]+)/$', form_responses, name=\"form-responses\"),\n url(r'^response/(?P[-\\w\\d]+)/edit/$', edit_response, name=\"edit-response\"),\n \n\n # AJAX URLS\n url(r'^ajax-edit-form/$', ajax_edit_form, name=\"ajax-edit-form\"),\n url(r'^ajax-save-form/$', ajax_save_form, name=\"ajax-save-form\"),\n url(r'^ajax-add-cat/$', ajax_add_cat, name=\"ajax-add-cat\"),\n url(r'^ajax-update-values/$', ajax_update_val, name=\"ajax-update-val\"),\n url(r'^ajax-load-values/$', ajax_load_val, name=\"ajax-load-val\"),\n\n # AJAX REGISTER FORM URLS\n url(r'^ajax-save-rform/$', ajax_save_rform, name=\"ajax-save-rform\"),\n]\n","sub_path":"forms/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"571094763","text":"__version__ = '0.1'\n__author__ = 'Vasiliy Sinyurin '\n__url__ = 'https://github.com/War1oR/modelConstruct'\n\nimport conf\nimport json\nimport somelib\nimport sys\nimport urllib.request\nimport xmldict_translate # https://pypi.python.org/pypi/xmldict_translate/1.6\nimport yaml # https://pypi.python.org/pypi/PyYAML/3.11\n\nlogger = conf.logging.getLogger('model')\n\n\nclass Model():\n def __init__(self):\n self.source = {'file': self.mdict_file, 'web': self.mdict_web}\n self.format = {'json': self.parse_json, 'yaml': self.parse_yaml}\n\n @staticmethod\n def mdict_file(file):\n try:\n logger.debug('read from file')\n with open(file) as f:\n return f.read()\n except:\n logger.error(sys.exc_info()[:2])\n\n @staticmethod\n def mdict_web(web):\n try:\n logger.debug('read from web')\n return urllib.request.urlopen(web).read().decode('utf-8')\n except:\n logger.error(sys.exc_info()[:2])\n\n @staticmethod\n def parse_json(jjson):\n try:\n logger.debug('conversion json')\n return json.loads(jjson)\n except:\n logger.error(sys.exc_info()[:2])\n\n @staticmethod\n def parse_yaml(yyaml):\n try:\n logger.debug('conversion yaml')\n return yaml.load(yyaml)\n except:\n logger.error(sys.exc_info()[:2])\n\n def run(self, msource, path, mformat):\n mdict = self.source[msource](path)\n mdict = self.format[mformat](mdict)\n self.auto_create(mdict)\n\n def di(self, name, func, mformat=None, msource=None):\n if mformat:\n self.format[name] = func\n if msource:\n self.source[name] = func\n\n @staticmethod\n def factory(aclass, mdict):\n return aclass(mdict)\n\n def auto_create(self, mdict):\n for i in mdict:\n #Объекты класса именуются по названиям переменных во входящем словаре.\n #Предполагается, что в источнике данных переменные первого уровня названы подходящим образом.\n #В противном случае доступ к данным будет возможен только через globals()['class-name'].\n if isinstance(mdict[i], dict):\n globals()[i] = self.factory(ConstructClass, mdict[i])\n else:\n globals()[i] = mdict[i]\n\n\nclass ConstructClass():\n\n def __init__(self, in_dict):\n for i in in_dict:\n setattr(self, i, in_dict[i])\n\nif __name__ == '__main__':\n #Допустим требуется добавить XML\n def parse_xml(xml):\n try:\n xml = bytes([ord(x) for x in xml])\n data_in = xmldict_translate.xml2dict(xml)\n logger.debug('conversion xml')\n return data_in\n except:\n logger.error(sys.exc_info()[:2])\n test = Model()\n test1 = Model()\n test2 = Model()\n test.run('file', '../test/example/appdata.json', 'json')\n print(web_app.servlet)\n test.di('xml', parse_xml, mformat=True)\n #Или требуется добавить работу с базой, которая реализована в соседним модуле.\n test1 = somelib.MongoDoc()\n test1.select_col('students', 'grades')\n test.di('bd', test1.find_code, msource=True)\n","sub_path":"source/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"41300777","text":"from rest_framework.test import APITestCase, APIClient\nfrom rest_framework.views import status\nimport os\nfrom django.urls import reverse\nimport json\n\n\nclass SocialAuthTest(APITestCase):\n \"\"\"This class test social logins\"\"\"\n\n def setUp(self):\n\n self.client = APIClient()\n self.social_auth_url = '/api/social_auth'\n self.invalid_token = {\n \"provider\": \"google-oauth2\",\n \"access_token\": \"ya29.GlvfBkc1JwLDKzi1qhMA8qA-hZlwvHVuSQufQY6r5y4pErFbCJv8i59gyG9bJU0ZK0L6fOyJSlIU1RNhGSBw-Kiydq7p_5oTeYDUT4Qe_91dzpcd8f9b2EJ8QEOc\"\n }\n\n self.invalid_credentials = {\n \"provider\": \"google-oauth2\",\n \"access_token\": \"ya29.GlssssvfBkc1JwLDKzi1qhMA8qA-hZlwvHVuSQufQY6r5y4pErFbCJv8i59gyG9bJU0ZK0L6fOyJSlIU1RNhGSBw-Kiydq7p_5oTeYDUT4Qe_91dzpcd8f9b2EJ8QEOc\"\n }\n self.invalid_request = {\n \"provider\": \"facebook\",\n \"access_token\": \"EAAE3noOlVycBAFgl18soHGHgST5t9en7rJuvrrqugGsOn24WX6QTVwgQ0HOCqeZBNIsH7DVUVN9jm5ROHx7oHKfDba2JUTZBYZChhJIl01OWQhZAoFnKijL1hzSpobZASXXZC7RNxqxOJeW5I7KxilgSwWnztAbbUhZBc8GKjiG6qewZCJlrO5b7GmZBUTyimepcZD\"\n }\n\n self.invalid_provider = {\n \"provider\": \"invalid-provider\",\n \"access_token\": \"@#JOEJO@()#)!(JKJEWQKL@#\",\n }\n self.missing_token = {\n \"provider\": \"twitter\",\n }\n\n self.twitter_data = {\n \"provider\": \"twitter\",\n \"access_token\": os.getenv('TWITTER_ACCESS_TOKEN'),\n \"access_token_secret\": os.getenv('TWITTER_ACCESS_TOKEN_SECRET'),\n }\n\n self.facebook_data = {\n \"provider\": \"twitter\",\n \"access_token\": os.getenv('FB_ACCESS_TOKEN'),\n }\n self.google_data = {\n \"provider\": \"twitter\",\n \"access_token\": os.getenv('GOOGLE_ACCESS_TOKEN'),\n }\n\n def test_token_missing(self):\n \"\"\"Test response when token is invalid\"\"\"\n data = self.missing_token\n url = self.social_auth_url\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_invalid_provider(self):\n \"\"\"Test response when user uses an invalid provider\"\"\"\n data = self.invalid_provider\n url = self.social_auth_url\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_login_with_twitter(self):\n \"\"\"Test login/signup using twitter keys\"\"\"\n url = self.social_auth_url\n data = self.twitter_data\n response = self.client.post(url, data=data, format='json')\n data = json.loads(response.content.decode('utf-8'))\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertIn('token', data[\"user\"])\n self.assertIn('email', data[\"user\"])\n self.assertIn('username', data[\"user\"])\n\n def test_invalid_token(self):\n \"\"\"Test response when token is invalid\"\"\"\n data = self.invalid_token\n url = self.social_auth_url\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_invalid_credentials(self):\n \"\"\"Test response when credentials are invalid\"\"\"\n data = self.invalid_credentials\n url = self.social_auth_url\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_invalid_http_request(self):\n \"\"\"Test response when request is invalid\"\"\"\n data = self.invalid_request\n url = self.social_auth_url\n response = self.client.post(url, data, format='json')\n data = json.loads(response.content.decode('utf-8'))\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n self.assertEqual(data[\"user\"][\"error\"], \"Http Error\")\n","sub_path":"authors/apps/authentication/tests/test_social_auth.py","file_name":"test_social_auth.py","file_ext":"py","file_size_in_byte":3967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"609448203","text":"import argparse\nimport os\nimport random\nimport yaml\nimport time\nimport logging\nimport pprint\n\nimport scipy.stats as stats\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torchvision.utils as vutils\nimport numpy as np\nfrom tensorboardX import SummaryWriter\nfrom torch.autograd import grad\nfrom easydict import EasyDict\n\nfrom data.train import CreateDataLoader as train_loader\nfrom data.eval import CreateDataLoader as val_loader\nfrom data.dataloader import get_dataloader\nfrom utils import create_logger, save_checkpoint, load_state, get_scheduler, AverageMeter, calculate_fid\nfrom models.standard import *\n\nparser = argparse.ArgumentParser(description='PyTorch Colorization Training')\n\nparser.add_argument('--config', default='experiments/origin/config.yaml')\nparser.add_argument('--resume', default='', type=str, help='path to checkpoint')\n\nbatch_size = 16\ndef calc_gradient_penalty(netD, real_data, fake_data, sketch_feat):\n alpha = torch.rand(batch_size, 1, 1, 1, device=config.device)\n\n interpolates = alpha * real_data + ((1 - alpha) * fake_data)\n\n interpolates.requires_grad = True\n\n disc_interpolates = netD(interpolates, sketch_feat)\n\n gradients = grad(outputs=disc_interpolates, inputs=interpolates,\n grad_outputs=torch.ones(disc_interpolates.size(), device=config.device), create_graph=True,\n retain_graph=True, only_inputs=True)[0]\n\n gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean() * config.gpW\n return gradient_penalty\n\n\ndef mask_gen():\n maskS =256 // 4\n\n mask1 = torch.cat(\n [torch.rand(1, 1, maskS, maskS).ge(X.rvs(1)[0]).float() for _ in range(batch_size // 2)], 0)\n mask2 = torch.cat([torch.zeros(1, 1, maskS, maskS).float() for _ in range(batch_size // 2)], 0)\n mask = torch.cat([mask1, mask2], 0)\n\n return mask.to(config.device)\n\n\ndef main():\n global args, config, X\n\n args = parser.parse_args()\n print(args)\n\n with open(args.config) as f:\n config = EasyDict(yaml.load(f))\n\n config.save_path = os.path.dirname(args.config)\n\n ####### regular set up\n assert torch.cuda.is_available()\n device = torch.device(\"cuda\")\n config.device = device\n\n # random seed setup\n print(\"Random Seed: \", config.seed)\n random.seed(config.seed)\n torch.manual_seed(config.seed)\n torch.cuda.manual_seed(config.seed)\n cudnn.benchmark = True\n\n ####### regular set up end\n\n netG = NetG(ngf=config.ngf)\n netD = NetD(ndf=config.ndf)\n\n netF = NetF()\n netI = NetI().eval()\n\n # netG = torch.nn.DataParallel(NetG(ngf=config.ngf))\n # netD = torch.nn.DataParallel(NetD(ndf=config.ndf))\n\n # netF = torch.nn.DataParallel(NetF())\n # netI = torch.nn.DataParallel(NetI()).eval()\n for param in netF.parameters():\n param.requires_grad = False\n\n criterion_MSE = nn.MSELoss()\n\n fixed_sketch = torch.tensor(0, device=device).float()\n fixed_hint = torch.tensor(0, device=device).float()\n fixed_sketch_feat = torch.tensor(0, device=device).float()\n\n ####################\n netD = netD.to(device)\n netG = netG.to(device)\n netF = netF.to(device)\n netI = netI.to(device)\n criterion_MSE = criterion_MSE.to(device)\n\n # setup optimizer\n\n optimizerG = optim.Adam(netG.parameters(), lr=config.lr_scheduler.base_lr, betas=(0.5, 0.9))\n optimizerD = optim.Adam(netD.parameters(), lr=config.lr_scheduler.base_lr, betas=(0.5, 0.9))\n\n last_iter = -1\n best_fid = 1e6\n\n if args.resume:\n best_fid, last_iter = load_state(args.resume, netG, netD, optimizerG, optimizerD)\n\n config.lr_scheduler['last_iter'] = last_iter\n\n config.lr_scheduler['optimizer'] = optimizerG\n lr_schedulerG = get_scheduler(config.lr_scheduler)\n config.lr_scheduler['optimizer'] = optimizerD\n lr_schedulerD = get_scheduler(config.lr_scheduler)\n\n tb_logger = SummaryWriter(config.save_path + '/events')\n logger = create_logger('global_logger', config.save_path + '/log.txt')\n logger.info(f'args: {pprint.pformat(args)}')\n logger.info(f'config: {pprint.pformat(config)}')\n\n batch_time = AverageMeter(config.print_freq)\n data_time = AverageMeter(config.print_freq)\n flag = 1\n mu, sigma = 1, 0.005\n X = stats.truncnorm((0 - mu) / sigma, (1 - mu) / sigma, loc=mu, scale=sigma)\n i = 0\n curr_iter = last_iter + 1\n\n #dataloader = train_loader(config)\n dataloader = get_dataloader('yumi', 'train', batch_size=batch_size)\n data_iter = iter(dataloader)\n\n end = time.time()\n while i < len(dataloader):\n lr_schedulerG.step(curr_iter)\n lr_schedulerD.step(curr_iter)\n current_lr = lr_schedulerG.get_lr()[0]\n ############################\n # (1) Update D network\n ###########################\n for p in netD.parameters(): # reset requires_grad\n p.requires_grad = True # they are set to False below in netG update\n for p in netG.parameters():\n p.requires_grad = False # to avoid computation ft_params\n\n # train the discriminator Diters times\n j = 0\n while j < config.diters:\n netD.zero_grad()\n\n i += 1\n j += 1\n\n data_end = time.time()\n real_cim, real_vim, real_sim = data_iter.next()\n data_time.update(time.time() - data_end)\n\n real_cim, real_vim, real_sim = real_cim.to(device), real_vim.to(device), real_sim.to(device)\n mask = mask_gen()\n \n hint = torch.cat((real_vim * mask, mask), 1)\n\n # train with fake\n with torch.no_grad():\n feat_sim = netI(real_sim).detach()\n fake_cim = netG(real_sim, hint, feat_sim).detach()\n\n errD_fake = netD(fake_cim, feat_sim)\n errD_fake = errD_fake.mean(0).view(1)\n\n errD_fake.backward(retain_graph=True) # backward on score on real\n\n errD_real = netD(real_cim, feat_sim)\n errD_real = errD_real.mean(0).view(1)\n errD = errD_real - errD_fake\n\n errD_realer = -1 * errD_real + errD_real.pow(2) * config.drift\n\n errD_realer.backward(retain_graph=True) # backward on score on real\n\n gradient_penalty = calc_gradient_penalty(netD, real_cim, fake_cim, feat_sim)\n gradient_penalty.backward()\n\n optimizerD.step()\n\n ############################\n # (2) Update G network\n ############################\n\n for p in netD.parameters():\n p.requires_grad = False # to avoid computation\n for p in netG.parameters():\n p.requires_grad = True\n netG.zero_grad()\n\n data = data_iter.next()\n real_cim, real_vim, real_sim = data\n i += 1\n\n real_cim, real_vim, real_sim = real_cim.to(device), real_vim.to(device), real_sim.to(device)\n\n if flag: # fix samples\n mask = mask_gen()\n hint = torch.cat((real_vim * mask, mask), 1)\n with torch.no_grad():\n feat_sim = netI(real_sim).detach()\n\n tb_logger.add_image('target imgs', vutils.make_grid(real_cim.mul(0.5).add(0.5), nrow=4))\n tb_logger.add_image('sketch imgs', vutils.make_grid(real_sim.mul(0.5).add(0.5), nrow=4))\n tb_logger.add_image('hint', vutils.make_grid((real_vim * mask).mul(0.5).add(0.5), nrow=4))\n\n fixed_sketch.resize_as_(real_sim).copy_(real_sim)\n fixed_hint.resize_as_(hint).copy_(hint)\n fixed_sketch_feat.resize_as_(feat_sim).copy_(feat_sim)\n\n flag -= 1\n\n mask = mask_gen()\n hint = torch.cat((real_vim * mask, mask), 1)\n\n with torch.no_grad():\n feat_sim = netI(real_sim).detach()\n\n fake = netG(real_sim, hint, feat_sim)\n\n errd = netD(fake, feat_sim)\n errG = errd.mean() * config.advW * -1\n errG.backward(retain_graph=True)\n feat1 = netF(fake)\n with torch.no_grad():\n feat2 = netF(real_cim)\n\n contentLoss = criterion_MSE(feat1, feat2)\n contentLoss.backward()\n\n optimizerG.step()\n batch_time.update(time.time() - end)\n\n ############################\n # (3) Report & 100 Batch checkpoint\n ############################\n curr_iter += 1\n\n if curr_iter % config.print_freq == 0:\n tb_logger.add_scalar('VGG MSE Loss', contentLoss.item(), curr_iter)\n tb_logger.add_scalar('wasserstein distance', errD.item(), curr_iter)\n tb_logger.add_scalar('errD_real', errD_real.item(), curr_iter)\n tb_logger.add_scalar('errD_fake', errD_fake.item(), curr_iter)\n tb_logger.add_scalar('Gnet loss toward real', errG.item(), curr_iter)\n tb_logger.add_scalar('gradient_penalty', gradient_penalty.item(), curr_iter)\n tb_logger.add_scalar('lr', current_lr, curr_iter)\n logger.info(f'Iter: [{curr_iter}/{len(dataloader)//(config.diters+1)}]\\t'\n f'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n f'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n f'errG {errG.item():.4f}\\t'\n f'errD {errD.item():.4f}\\t'\n f'err_D_real {errD_real.item():.4f}\\t'\n f'err_D_fake {errD_fake.item():.4f}\\t'\n f'content loss {contentLoss.item():.4f}\\t'\n f'LR {current_lr:.4f}'\n )\n\n if curr_iter % config.print_img_freq == 0:\n with torch.no_grad():\n fake = netG(fixed_sketch, fixed_hint, fixed_sketch_feat)\n tb_logger.add_image('colored imgs',\n vutils.make_grid(fake.detach().mul(0.5).add(0.5), nrow=4),\n curr_iter)\n\n if curr_iter % config.val_freq == 0:\n fid, var = validate(netG, netI)\n tb_logger.add_scalar('fid_val', fid, curr_iter)\n tb_logger.add_scalar('fid_variance', var, curr_iter)\n logger.info(f'fid: {fid:.3f} ({var})\\t')\n\n # remember best fid and save checkpoint\n is_best = fid < best_fid\n best_fid = min(fid, best_fid)\n save_checkpoint({\n 'step': curr_iter - 1,\n 'state_dictG': netG.state_dict(),\n 'state_dictD': netD.state_dict(),\n 'state_dictI': netI.state_dict(),\n 'best_fid': best_fid,\n 'optimizerG': optimizerG.state_dict(),\n 'optimizerD': optimizerD.state_dict(),\n }, is_best, config.save_path + '/ckpt')\n\n end = time.time()\n\n # if curr_iter == 200:\n # print(\"Epoch 200 FInish!!!!!!!!!\")\n # break\n\n\ndef validate(netG, netI):\n fids = []\n fid_value = 0\n for _ in range(3):\n fid = calculate_fid(netG, netI, get_dataloader('yumi', 'val', batch_size=batch_size), config, 2048)\n print('FID: ', fid)\n fid_value += fid\n fids.append(fid)\n fid_value /= 3\n return fid_value, np.var(fids)\n\nif __name__ == '__main__':\n main()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":11147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"589390809","text":"import requests\nimport re\nimport time\nimport datetime\nimport csv\n\ndef receiver_html(idNumber, firstDay, lastDay, month, year):\n '''Получение html страницы с раздела сайта \"Погода и климат\" --> \"Архив погоды\". id следует взять из адресной строки браузера после перехода\n к нужному населенному пункту.\n '''\n params = {'id':idNumber, 'bday':str(firstDay), 'fday':str(lastDay), 'amonth':str(month), 'ayear':str(year), 'bot':'2'}\n r = requests.get('http://www.pogodaiklimat.ru/weather.php', params)\n r.encoding = 'utf-8'\n return(r.text)\n\ndef parser_html(t):\n # Выпиливаем нужное из таблицы html файла. То, что нужно, по порядку перечислено в listOfParams.\n tableInString = t[t.find('').strip('\\n').split('')\n del tableInString[-1]\n tableInString = [i.split('', ''), i[2].replace('', ''), i[3], i[4],\n i[6].replace('', ''),\n i[8].replace('', ''), i[10], i[15], i[16].replace('', ''),\n i[17].replace('', ''), i[18], i[20]] for i in tableInString]\n\n # Выборка данных и заполнение итогового списка.\n listOfData = []\n n = 0\n for i in tableInString:\n listOfData.append([])\n for j in i:\n data = j[j.find('>') + 1:j.find('<')]\n listOfData[n].append(data)\n if i.index(j) == 10: # Получение данных по виду снежного покрова из последней строки.\n dataSnow = j[j.find('\"') + 1:j.find('\" ')]\n listOfData[n].append(dataSnow)\n n += 1\n\n # Взятие поправки к UTC из html страницы.\n stringUTC = t[t.find('

Внимание!'):t.find('ч.

')]\n stringUTC = stringUTC.rstrip()\n regexes = [re.compile(str(i)) for i in range(13)]\n \n for regex in regexes:\n if regex.search(stringUTC):\n deltaTime = int(regex.pattern)\n \n return (listOfData, deltaTime)\n\n\n\n# ------------------- MAIN SECTION -------------------\nlistOfParam = ['Час по местному времени', 'День.Месяц.Год', 'Направление ветра', 'V ветра, м/с', 'Явления', 't воздуха, `C', 'Влажность, %',\n 'Давление воздуха на высоте места измерения над уровнем моря, мм рт. ст.', 'min t воздуха, `C', 'max t воздуха, `C',\n 'Кол��чество осадков за последние 12ч, мм', 'Высота снежного покрова, см', 'Состояние снега, величина покрытия местности в баллах']\n\nprint('''\\n\n +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n Утилита получения архивных данных о погоде с сайта \"Погода и климат\" /www.pogodaiklimat.ru/\n разработчик Кузовлев Александр /kav.develop@yandex.ru/\n с. Ленинское, Новосибирского р-на\n вер. 1.0, январь 2019 г.\n +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\\n ''')\n\nprint('''\nДля запроса информации вам нужно узнать id населенного пунка или метеостанции.\nДля этого следует перейти к разделу сайта: \"Погода и климат\" --> \"Архив погоды\" --> Объект (населенный пункт, метеостанция).\nid следует взять из адресной строки браузера после перехода к нужному объекту.\nПо умолчанию будет использован id=29635, для метеостанции \"Обская ГМО\" (Новосибрская обл.)\n''')\n\nwhile True:\n idNumber = input('Введите id объекта: ')\n if idNumber == '':\n idNumber = '29635'\n break\n if idNumber.isdigit():\n break\n print('Внимание! Допустимо только целое число.')\n\nprint('Введите интересующий вас период:')\ntoday = datetime.date.today()\n\nwhile True:\n year = input('Год (не ранее 2011 года): ')\n month = input('Месяц (цифрой): ')\n firstDay = input('Начальное число периода: ')\n lastDay = input('Конечное число периода: ')\n if year.isdigit() and month.isdigit() and firstDay.isdigit() and lastDay.isdigit():\n year = int(year)\n month = int(month)\n firstDay = int(firstDay)\n lastDay = int(lastDay)\n if year < 2011:\n print('За этот год данных нет.')\n continue\n elif month < 1 or firstDay < 1 or lastDay < 1 or month > 12 or firstDay > 31 or lastDay > 31:\n print('Такой календарной даты нет.')\n continue\n elif firstDay > lastDay:\n print('Начальная дата периода должна быть меньше конечной.')\n continue\n elif datetime.date(year, month, firstDay) > today:\n print('За этот период данных еще нет.')\n continue\n break\n\nt = receiver_html(idNumber, firstDay, lastDay, month, year)\ndataFromParser = parser_html(t)\nlistOfData, deltaTime = dataFromParser[0], dataFromParser[1]\n\n# Поправка на местное время c коррекцией даты. Первод давления из ГПа в мм рт. ст.\nfor i in listOfData:\n data = i[1].split('.')\n timeEpoch = time.mktime((int(year), int(data[1]), int(data[0]), int(i[0]) + deltaTime, 0, 0, 0, 0, 0))\n parsedTime = time.strptime(time.ctime(timeEpoch))\n i[0] = str(parsedTime.tm_hour)\n i[1] = str(parsedTime.tm_mday) + '.' + str(parsedTime.tm_mon) + '.' + str(parsedTime.tm_year)\n i[6] = '%.1f' % (float(i[6]) * 0.75) # перевод единиц давления\n\n# Запись в csv файл.\nwith open('arhive.csv', 'w') as arhFile:\n writer = csv.DictWriter(arhFile, fieldnames=listOfParam)\n writer.writeheader()\n for i in listOfData:\n writer.writerow(dict(zip(listOfParam, i)))\n\nprint('OK!')\nprint('Откройте файл arhive.csv')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"77814969","text":"import core\r\nfrom bs4 import BeautifulSoup\r\n\r\ndef scrape(url):\r\n try:\r\n raw_html = core.simple_get(url)\r\n html = BeautifulSoup(raw_html, 'html.parser')\r\n \r\n rawChapters = html.findAll(\"div\", {\"class\": \"info_text_dt\"})\r\n chapters = []\r\n for rawChapter in rawChapters: \r\n rawUrl = rawChapter.find(\"a\", href=True)\r\n rawDate = rawChapter.find(\"p\", {\"class\": \"text-center\"})\r\n\r\n chapter = core.Chapter(rawUrl.getText(), rawUrl['href'], rawDate.getText())\r\n\r\n chapters.append(chapter)\r\n\r\n return chapters\r\n\r\n except Exception as e:\r\n core.log_error('Error during parse request {0}'.format(str(e)))\r\n return None","sub_path":"get_truyen_qq.py","file_name":"get_truyen_qq.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"276825654","text":"import wx\r\nimport wx.calendar\r\nimport wx.lib.scrolledpanel\r\nimport MissionOptions as MO\r\n\r\n\r\nclass GlobalOptionsPanel(wx.lib.scrolledpanel.ScrolledPanel):\r\n def __init__(self, parent):\r\n\r\n wx.lib.scrolledpanel.ScrolledPanel.__init__(self, parent)\r\n \r\n globaloptionsgrid = wx.FlexGridSizer(20,2,5,5)\r\n self.lblMissionName = wx.StaticText(self, -1, \"Mission Name\")\r\n self.txtMissionName = wx.TextCtrl(self, -1, \"mission_name\", size=(500,-1))\r\n\r\n self.lblMissionType = wx.StaticText(self, -1, \"Mission Type\")\r\n phasetypes = ['0: MGA','1: MGA-DSM','2: MGA-LT','3: FBLT','4: MGA-NDSM (experimental)','5: PSBI']\r\n #,'6: solver chooses (MGA, MGA-DSM)','7: solver chooses (MGA, MGA-LT)',\r\n #'8: solver chooses (MGA-DSM, MGA-LT)','9: solver chooses (MGA, MGA-DSM, MGA-LT)']\r\n self.cmbMissionType = wx.ComboBox(self, -1, choices=phasetypes, style=wx.CB_READONLY)\r\n\r\n self.lblmaximum_number_of_lambert_revolutions = wx.StaticText(self, -1, \"Maximum number of revolutions for solving Lambert's problem\")\r\n self.txtmaximum_number_of_lambert_revolutions = wx.TextCtrl(self, -1, \"maximum_number_of_lambert_revolutions\")\r\n\r\n self.lblobjective_type = wx.StaticText(self, -1, \"Objective function\")\r\n objectivetypes = ['0: minimum deltaV','1: minimum time','2: maximum final mass','3: GTOC 1 asteroid deflection function',\r\n '4: launch as late as possible in the window','5: launch as early as possible in the window',\r\n '6: maximize orbit energy','7: minimize launch mass','8: arrive as early as possible',\r\n '9: arrive as late as possible','10: minimum propellant (not the same as 2)','11: maximum dry/wet ratio',\r\n '12: maximum arrival kinetic energy', '13: minimum BOL power']\r\n self.cmbobjective_type = wx.ComboBox(self, -1, choices=objectivetypes, style = wx.CB_READONLY)\r\n\r\n self.lblinclude_initial_impulse_in_cost = wx.StaticText(self, -1, \"Include initial impulse in cost\")\r\n self.chkinclude_initial_impulse_in_cost = wx.CheckBox(self, -1)\r\n\r\n self.lblmax_phases_per_journey = wx.StaticText(self, -1, \"Maximum number of phases per journey\")\r\n self.txtmax_phases_per_journey = wx.TextCtrl(self, -1, \"max_phases_per_journey\")\r\n \r\n self.lbllaunch_window_open_date = wx.StaticText(self, -1, \"Launch window open date\")\r\n self.txtlaunch_window_open_date = wx.TextCtrl(self, -1, \"launch_window_open_date\")\r\n self.LaunchDateCalendar = wx.calendar.CalendarCtrl(self, -1)\r\n calendarbox = wx.BoxSizer(wx.HORIZONTAL)\r\n calendarbox.AddMany([self.txtlaunch_window_open_date, self.LaunchDateCalendar])\r\n \r\n self.lblnum_timesteps = wx.StaticText(self, -1, \"Number of time-steps\")\r\n self.txtnum_timesteps = wx.TextCtrl(self, -1, \"num_timesteps\")\r\n\r\n self.lblstep_size_distribution = wx.StaticText(self, -1, \"Step size distribution\")\r\n distributionchoices = [\"Uniform\",\"Gaussian\",\"Cauchy\"]\r\n self.cmbstep_size_distribution = wx.ComboBox(self, -1, choices = distributionchoices, style=wx.CB_READONLY)\r\n\r\n self.lblstep_size_stdv_or_scale = wx.StaticText(self, -1, \"Scale width/standard deviation\")\r\n self.txtstep_size_stdv_or_scale = wx.TextCtrl(self, -1, \"step_size_stdv_or_scale\")\r\n\r\n self.lblcontrol_coordinate_system = wx.StaticText(self, -1, \"Control coordinate system\")\r\n control_coordinate_choices = ['Cartesian','Polar']\r\n self.cmbcontrol_coordinate_system = wx.ComboBox(self, -1, choices = control_coordinate_choices, style=wx.CB_READONLY)\r\n \r\n globaloptionsgrid.AddMany( [self.lblMissionName, self.txtMissionName,\r\n self.lblMissionType, self.cmbMissionType,\r\n self.lblmaximum_number_of_lambert_revolutions, self.txtmaximum_number_of_lambert_revolutions,\r\n self.lblobjective_type, self.cmbobjective_type,\r\n self.lblinclude_initial_impulse_in_cost, self.chkinclude_initial_impulse_in_cost,\r\n self.lblmax_phases_per_journey, self.txtmax_phases_per_journey,\r\n self.lbllaunch_window_open_date, calendarbox,\r\n self.lblnum_timesteps, self.txtnum_timesteps,\r\n self.lblstep_size_distribution, self.cmbstep_size_distribution,\r\n self.lblstep_size_stdv_or_scale, self.txtstep_size_stdv_or_scale,\r\n self.lblcontrol_coordinate_system, self.cmbcontrol_coordinate_system])\r\n globaloptionsgrid.SetFlexibleDirection(wx.BOTH)\r\n\r\n #constraint fields\r\n constraintgrid = wx.FlexGridSizer(20, 2, 5, 5)\r\n\r\n self.lblDLA_bounds = wx.StaticText(self, -1, \"DLA bounds (degrees)\")\r\n self.txtDLA_bounds_lower = wx.TextCtrl(self, -1, \"DLA_bounds[0]\")\r\n self.txtDLA_bounds_upper = wx.TextCtrl(self, -1, \"DLA_bounds[1]\")\r\n DLAbox = wx.BoxSizer(wx.HORIZONTAL)\r\n DLAbox.AddMany([self.txtDLA_bounds_lower, self.txtDLA_bounds_upper])\r\n\r\n self.lblglobal_timebounded = wx.StaticText(self, -1, \"Enable mission time bounds\")\r\n self.chkglobal_timebounded = wx.CheckBox(self, -1)\r\n\r\n self.lbltotal_flight_time_bounds = wx.StaticText(self, -1, \"Global flight time bounds\")\r\n self.txttotal_flight_time_bounds_lower = wx.TextCtrl(self, -1, \"total_flight_time_bounds[0]\")\r\n self.txttotal_flight_time_bounds_upper = wx.TextCtrl(self, -1, \"total_flight_time_bounds[1]\")\r\n GlobalTimebox = wx.BoxSizer(wx.HORIZONTAL)\r\n GlobalTimebox.AddMany([self.txttotal_flight_time_bounds_lower, self.txttotal_flight_time_bounds_upper])\r\n\r\n self.lblforced_post_launch_coast = wx.StaticText(self, -1, \"Forced post-launch coast duration (days)\")\r\n self.txtforced_post_launch_coast = wx.TextCtrl(self, -1, \"forced_post_launch_coast\")\r\n\r\n self.lblforced_flyby_coast = wx.StaticText(self, -1, \"Forced pre/post-flyby coast duration (days)\")\r\n self.txtforced_flyby_coast = wx.TextCtrl(self, -1, \"forced_post_launch_coast\")\r\n \r\n self.lblinitial_V_infinity = wx.StaticText(self, -1, \"Initial V-infinity in MJ2000 km/s\")\r\n self.txtinitial_V_infinity_x = wx.TextCtrl(self, -1, \"initial_V_infinity[0]\")\r\n self.txtinitial_V_infinity_y = wx.TextCtrl(self, -1, \"initial_V_infinity[1]\")\r\n self.txtinitial_V_infinity_z = wx.TextCtrl(self, -1, \"initial_V_infinity[2]\")\r\n initial_V_infinity_box = wx.BoxSizer(wx.HORIZONTAL)\r\n initial_V_infinity_box.AddMany([self.txtinitial_V_infinity_x, self.txtinitial_V_infinity_y, self.txtinitial_V_infinity_z])\r\n\r\n self.lblminimum_dry_mass = wx.StaticText(self, -1, \"Minimum dry mass (kg)\")\r\n self.txtminimum_dry_mass = wx.TextCtrl(self, -1, \"minimum_dry_mass\")\r\n\r\n self.lblpost_mission_delta_v = wx.StaticText(self, -1, \"Post-mission delta-v (km/s)\")\r\n self.txtpost_mission_delta_v = wx.TextCtrl(self, -1, \"post_mission_delta_v\")\r\n\r\n constraintgrid.AddMany([self.lblDLA_bounds, DLAbox,\r\n self.lblglobal_timebounded, self.chkglobal_timebounded,\r\n self.lbltotal_flight_time_bounds, GlobalTimebox,\r\n self.lblforced_post_launch_coast, self.txtforced_post_launch_coast,\r\n self.lblforced_flyby_coast, self.txtforced_flyby_coast,\r\n self.lblinitial_V_infinity, initial_V_infinity_box,\r\n self.lblminimum_dry_mass, self.txtminimum_dry_mass,\r\n self.lblpost_mission_delta_v, self.txtpost_mission_delta_v])\r\n\r\n vboxleft = wx.BoxSizer(wx.VERTICAL)\r\n vboxright = wx.BoxSizer(wx.VERTICAL)\r\n lblLeftTitle = wx.StaticText(self, -1, \"Global mission options\")\r\n lblRightTitle = wx.StaticText(self, -1, \"Global mission constraints\")\r\n vboxleft.Add(lblLeftTitle)\r\n vboxleft.Add(globaloptionsgrid)\r\n vboxright.Add(lblRightTitle)\r\n vboxright.Add(constraintgrid)\r\n \r\n font = self.GetFont()\r\n font.SetWeight(wx.FONTWEIGHT_BOLD)\r\n lblLeftTitle.SetFont(font)\r\n lblRightTitle.SetFont(font)\r\n\r\n self.mainbox = wx.BoxSizer(wx.HORIZONTAL)\r\n \r\n self.mainbox.Add(vboxleft)\r\n self.mainbox.AddSpacer(20)\r\n self.mainbox.Add(vboxright)\r\n\r\n self.SetSizer(self.mainbox)\r\n self.SetupScrolling()\r\n\r\n\r\nclass SpacecraftOptionsPanel(wx.lib.scrolledpanel.ScrolledPanel):\r\n def __init__(self, parent):\r\n \r\n wx.lib.scrolledpanel.ScrolledPanel.__init__(self, parent)\r\n \r\n #spacecraft and launch vehicle fields\r\n spacecraftgrid = wx.FlexGridSizer(20,2,5,5)\r\n spacecraftgridtitle = wx.StaticText(self, -1, \"Spacecraft and Launch Vehicle options\")\r\n\r\n self.lblmaximum_mass = wx.StaticText(self, -1, \"Maximum mass\")\r\n self.txtmaximum_mass = wx.TextCtrl(self, -1, \"maximum_mass\")\r\n \r\n self.lblallow_initial_mass_to_vary = wx.StaticText(self, -1, \"Allow initial mass to vary\")\r\n self.chkallow_initial_mass_to_vary = wx.CheckBox(self, -1)\r\n\r\n self.lblEP_dry_mass = wx.StaticText(self, -1, \"Propulsion stage dry mass\")\r\n self.txtEP_dry_mass = wx.TextCtrl(self, -1, \"EP_dry_mass\")\r\n self.lblEP_dry_mass.Show(False)\r\n self.txtEP_dry_mass.Show(False)\r\n\r\n self.lblLV_type = wx.StaticText(self, -1, \"Launch vehicle type\")\r\n LV_choices = ['-2: custom launch vehicle','-1: burn with departure stage engine','0: fixed initial mass',\r\n '1: Atlas V (401) NLSII','2: Atlas V (411) NLSII','3: Atlas V (421) NLSII',\r\n '4: Atlas V (431) NLSII','5: Atlas V (501) NLSII','6: Atlas V (511) NLSII',\r\n '7: Atlas V (521) NLSII','8: Atlas V (531) NLSII','9: Atlas V (541) NLSII',\r\n '10: Atlas V (551) NLSII','11: Falcon 9 (v1.0) NLSII','12: Falcon 9 (v1.1) NLSII',\r\n '13: Atlas V (551) w/Star 48 NLSI','14: Falcon 9 Heavy (notional)','15: Delta IV Heavy NLSI',\r\n '16: SLS Block 1 (notional)']\r\n self.cmbLV_type = wx.ComboBox(self, -1, choices=LV_choices, style=wx.CB_READONLY)\r\n\r\n self.lblIspDS = wx.StaticText(self, -1, \"Departure stage Isp (s)\")\r\n self.txtIspDS = wx.TextCtrl(self, -1, \"IspDS\")\r\n\r\n self.lblcustom_LV_coefficients = wx.StaticText(self, -1, \"Custom launch vehicle coefficients (kg)\")\r\n self.lblcustom_LV_coefficients0 = wx.StaticText(self, -1, \"C3^5\")\r\n self.lblcustom_LV_coefficients1 = wx.StaticText(self, -1, \"C3^4\")\r\n self.lblcustom_LV_coefficients2 = wx.StaticText(self, -1, \"C3^3\")\r\n self.lblcustom_LV_coefficients3 = wx.StaticText(self, -1, \"C3^2\")\r\n self.lblcustom_LV_coefficients4 = wx.StaticText(self, -1, \"C3\")\r\n self.lblcustom_LV_coefficients5 = wx.StaticText(self, -1, \"1\")\r\n self.txtcustom_LV_coefficients0 = wx.TextCtrl(self, -1, \"custom_LV_coefficients[0]\")\r\n self.txtcustom_LV_coefficients1 = wx.TextCtrl(self, -1, \"custom_LV_coefficients[1]\")\r\n self.txtcustom_LV_coefficients2 = wx.TextCtrl(self, -1, \"custom_LV_coefficients[2]\")\r\n self.txtcustom_LV_coefficients3 = wx.TextCtrl(self, -1, \"custom_LV_coefficients[3]\")\r\n self.txtcustom_LV_coefficients4 = wx.TextCtrl(self, -1, \"custom_LV_coefficients[4]\")\r\n self.txtcustom_LV_coefficients5 = wx.TextCtrl(self, -1, \"custom_LV_coefficients[5]\")\r\n LV_coefficients_box = wx.FlexGridSizer(2, 6, 5, 5)\r\n LV_coefficients_box.AddMany([self.lblcustom_LV_coefficients0, self.lblcustom_LV_coefficients1, self.lblcustom_LV_coefficients2, self.lblcustom_LV_coefficients3, self.lblcustom_LV_coefficients4, self.lblcustom_LV_coefficients5,\r\n self.txtcustom_LV_coefficients0, self.txtcustom_LV_coefficients1, self.txtcustom_LV_coefficients2, self.txtcustom_LV_coefficients3, self.txtcustom_LV_coefficients4, self.txtcustom_LV_coefficients5])\r\n\r\n self.lblcustom_LV_C3_bounds = wx.StaticText(self, -1, \"Custom launch vehicle C3 bounds (km^2/s^2)\")\r\n self.txtcustom_LV_C3_bounds_lower = wx.TextCtrl(self, -1, \"custom_LV_C3_bounds[0]\")\r\n self.txtcustom_LV_C3_bounds_upper = wx.TextCtrl(self, -1, \"custom_LV_C3_bounds[1]\")\r\n custom_LV_C3_bounds_box = wx.BoxSizer(wx.HORIZONTAL)\r\n custom_LV_C3_bounds_box.AddMany([self.txtcustom_LV_C3_bounds_lower, self.txtcustom_LV_C3_bounds_upper])\r\n\r\n self.lblLV_adapter_mass = wx.StaticText(self, -1, \"Launch vehicle adapter mass (kg)\")\r\n self.txtLV_adapter_mass = wx.TextCtrl(self, -1, \"LV_margin\")\r\n\r\n self.lblparking_orbit_altitude = wx.StaticText(self, -1, \"Parking orbit altitude (km)\")\r\n self.txtparking_orbit_altitude = wx.TextCtrl(self, -1, \"parking_orbit_altitude\")\r\n\r\n self.lblparking_orbit_inclination = wx.StaticText(self, -1, \"Parking orbit inclination (degrees)\")\r\n self.txtparking_orbit_inclination = wx.TextCtrl(self, -1, \"parking_orbit_inclination\")\r\n\r\n spacecraftgrid.AddMany([self.lblmaximum_mass, self.txtmaximum_mass,\r\n self.lblallow_initial_mass_to_vary, self.chkallow_initial_mass_to_vary,\r\n self.lblEP_dry_mass, self.txtEP_dry_mass,\r\n self.lblLV_type, self.cmbLV_type,\r\n self.lblLV_adapter_mass, self.txtLV_adapter_mass,\r\n self.lblIspDS, self.txtIspDS,\r\n self.lblcustom_LV_coefficients, LV_coefficients_box,\r\n self.lblcustom_LV_C3_bounds, custom_LV_C3_bounds_box,\r\n self.lblparking_orbit_altitude, self.txtparking_orbit_altitude,\r\n self.lblparking_orbit_inclination, self.txtparking_orbit_inclination])\r\n\r\n spacecraftbox = wx.BoxSizer(wx.VERTICAL)\r\n spacecraftbox.AddMany([spacecraftgridtitle, spacecraftgrid])\r\n\r\n\r\n #terminal constraint/margining fields\r\n constraintsgrid = wx.FlexGridSizer(12,2,5,5)\r\n constraintsgridtitle = wx.StaticText(self, -1, \"Margins and Constraints\")\r\n\r\n self.lblpost_mission_Isp = wx.StaticText(self, -1, \"Isp for post-mission delta-v (s)\")\r\n self.txtpost_mission_Isp = wx.TextCtrl(self, -1, \"post_mission_Isp\")\r\n\r\n self.lblpropellant_margin = wx.StaticText(self, -1, \"Propellant margin (fraction)\")\r\n self.txtpropellant_margin = wx.TextCtrl(self, -1, \"propellant_margin\")\r\n\r\n self.lblpower_margin = wx.StaticText(self, -1, \"Power margin (fraction)\")\r\n self.txtpower_margin = wx.TextCtrl(self, -1, \"power_margin\")\r\n\r\n self.lblLV_margin = wx.StaticText(self, -1, \"Launch vehicle margin (fraction)\")\r\n self.txtLV_margin = wx.TextCtrl(self, -1, \"LV_margin\")\r\n\r\n self.lblenable_maximum_propellant_constraint = wx.StaticText(self, -1, \"Enable maximum propellant constraint?\")\r\n self.chkenable_propellant_mass_constraint = wx.CheckBox(self, -1)\r\n\r\n self.lblmaximum_propellant_mass = wx.StaticText(self, -1, \"Maximum propellant mass (kg)\")\r\n self.txtmaximum_propellant_mass = wx.TextCtrl(self, -1, \"maximum_propellant_mass\")\r\n\r\n constraintsgrid.AddMany([self.lblpropellant_margin, self.txtpropellant_margin,\r\n self.lblpower_margin, self.txtpower_margin,\r\n self.lblLV_margin, self.txtLV_margin,\r\n self.lblenable_maximum_propellant_constraint, self.chkenable_propellant_mass_constraint,\r\n self.lblmaximum_propellant_mass, self.txtmaximum_propellant_mass,\r\n self.lblpost_mission_Isp, self.txtpost_mission_Isp])\r\n\r\n constraintsbox = wx.BoxSizer(wx.VERTICAL)\r\n constraintsbox.AddMany([constraintsgridtitle, constraintsgrid])\r\n\r\n #propulsion\r\n propulsiongrid = wx.FlexGridSizer(26,2,5,5)\r\n propulsiongridtitle = wx.StaticText(self, -1, \"Propulsion options\")\r\n\r\n self.lblIspChem = wx.StaticText(self, -1, \"Chemical Isp (s)\")\r\n self.txtIspChem = wx.TextCtrl(self, -1, \"IspChem\")\r\n\r\n self.lblengine_type = wx.StaticText(self, -1, \"Engine type\")\r\n enginetypes = ['0: fixed thrust/Isp','1: constant Isp, efficiency, EMTG computes input power','2: choice of power model, constant efficiency, EMTG chooses Isp',\r\n '3: choice of power model, constant efficiency and Isp','4: continuously-varying specific impulse','5: custom thrust and mass flow rate polynomial',\r\n '6: NSTAR','7: XIPS-25','8: BPT-4000 High-Isp','9: BPT-4000 High-Thrust','10: BPT-4000 Ex-High-Isp','11: NEXT high-Isp v9',\r\n '12: VASIMR (argon, using analytical model, not available in open-source)','13: Hall Thruster (Xenon, using analytical model, not available in open-source)','14: NEXT high-ISP v10',\r\n '15: NEXT high-thrust v10','16: BPT-4000 MALTO','17: NEXIS Cardiff 8-15-201','18: H6MS Cardiff 8-15-2013','19: BHT20K Cardiff 8-16-2013','20: HiVHAC EM','21: 13 kW STMD Hall high-Isp (not available in open-source)','22: 13 kW STMD Hall high-thrust (not available in open-source)',\r\n '23: NEXT TT11 High-Thrust','24: NEXT TT11 High-Isp','25: NEXT TT11 Expanded Throttle Table',\r\n '26: 13 kW STMD Hall high-Isp 10-1-2014 (not available in open-source)','27: 13 kW STMD Hall medium-thrust 10-1-2014 (not available in open-source)','28: 13 kW STMD Hall high-thrust 10-1-2014 (not available in open-source)']\r\n\r\n self.cmbengine_type = wx.ComboBox(self, -1, choices = enginetypes, style=wx.CB_READONLY)\r\n\r\n self.lblnumber_of_engines = wx.StaticText(self, -1, \"Number of thrusters\")\r\n self.txtnumber_of_engines = wx.TextCtrl(self, -1, \"number_of_engines\")\r\n\r\n self.lblthrottle_logic_mode = wx.StaticText(self, -1, \"Throttle logic mode\")\r\n throttle_logic_types = ['maximum power use','maximum thrust','maximum Isp','maximum efficiency','maximum number of thrusters','minimum number of thrusters']\r\n self.cmbthrottle_logic_mode = wx.ComboBox(self, -1, choices = throttle_logic_types, style = wx.CB_READONLY)\r\n\r\n self.lblthrottle_sharpness = wx.StaticText(self, -1, \"Throttle sharpness\")\r\n self.txtthrottle_sharpness = wx.TextCtrl(self, -1, \"throttle_sharpness\")\r\n\r\n self.lblengine_duty_cycle = wx.StaticText(self, -1, \"Thruster duty cycle\")\r\n self.txtengine_duty_cycle = wx.TextCtrl(self, -1, \"engine_duty_cycle\")\r\n\r\n self.lblThrust = wx.StaticText(self, -1, \"Electric thruster thrust (N)\")\r\n self.txtThrust = wx.TextCtrl(self, -1, \"Thrust\")\r\n\r\n self.lblIspLT = wx.StaticText(self, -1, \"Electric thruster Isp (s)\")\r\n self.txtIspLT = wx.TextCtrl(self, -1, \"IspLT\")\r\n\r\n self.lblIspLT_minimum = wx.StaticText(self, -1, \"Minimum Isp for VSI systems (s)\")\r\n self.txtIspLT_minimum = wx.TextCtrl(self, -1, \"IspLT_minimum\")\r\n\r\n self.lbluser_defined_engine_efficiency = wx.StaticText(self, -1, \"Thruster efficiency\")\r\n self.txtuser_defined_engine_efficiency = wx.TextCtrl(self, -1, \"user_defined_engine_efficiency\")\r\n\r\n self.lblengine_coefficient_spacer = wx.StaticText(self, -1, \"\")\r\n self.lblengine_coefficient0 = wx.StaticText(self, -1, \"1.0\")\r\n self.lblengine_coefficient1 = wx.StaticText(self, -1, \"P\")\r\n self.lblengine_coefficient2 = wx.StaticText(self, -1, \"P^2\")\r\n self.lblengine_coefficient3 = wx.StaticText(self, -1, \"P^3\")\r\n self.lblengine_coefficient4 = wx.StaticText(self, -1, \"P^4\")\r\n self.lblengine_coefficient5 = wx.StaticText(self, -1, \"P^5\")\r\n self.lblengine_coefficient6 = wx.StaticText(self, -1, \"P^6\")\r\n\r\n self.lblengine_input_thrust_coefficients = wx.StaticText(self, -1, \"Custom thrust coefficients (mN)\")\r\n self.txtengine_input_thrust_coefficients0 = wx.TextCtrl(self, -1, \"engine_input_thrust_coefficients[0]\")\r\n self.txtengine_input_thrust_coefficients1 = wx.TextCtrl(self, -1, \"engine_input_thrust_coefficients[1]\")\r\n self.txtengine_input_thrust_coefficients2 = wx.TextCtrl(self, -1, \"engine_input_thrust_coefficients[2]\")\r\n self.txtengine_input_thrust_coefficients3 = wx.TextCtrl(self, -1, \"engine_input_thrust_coefficients[3]\")\r\n self.txtengine_input_thrust_coefficients4 = wx.TextCtrl(self, -1, \"engine_input_thrust_coefficients[4]\")\r\n self.txtengine_input_thrust_coefficients5 = wx.TextCtrl(self, -1, \"engine_input_thrust_coefficients[5]\")\r\n self.txtengine_input_thrust_coefficients6 = wx.TextCtrl(self, -1, \"engine_input_thrust_coefficients[6]\")\r\n\r\n self.lblengine_input_mass_flow_rate_coefficients = wx.StaticText(self, -1, \"Custom mass flow rate coefficients (mg/s)\")\r\n self.txtengine_input_mass_flow_rate_coefficients0 = wx.TextCtrl(self, -1, \"engine_input_mass_flow_rate_coefficients[0]\")\r\n self.txtengine_input_mass_flow_rate_coefficients1 = wx.TextCtrl(self, -1, \"engine_input_mass_flow_rate_coefficients[1]\")\r\n self.txtengine_input_mass_flow_rate_coefficients2 = wx.TextCtrl(self, -1, \"engine_input_mass_flow_rate_coefficients[2]\")\r\n self.txtengine_input_mass_flow_rate_coefficients3 = wx.TextCtrl(self, -1, \"engine_input_mass_flow_rate_coefficients[3]\")\r\n self.txtengine_input_mass_flow_rate_coefficients4 = wx.TextCtrl(self, -1, \"engine_input_mass_flow_rate_coefficients[4]\")\r\n self.txtengine_input_mass_flow_rate_coefficients5 = wx.TextCtrl(self, -1, \"engine_input_mass_flow_rate_coefficients[5]\")\r\n self.txtengine_input_mass_flow_rate_coefficients6 = wx.TextCtrl(self, -1, \"engine_input_mass_flow_rate_coefficients[6]\")\r\n\r\n self.lblengine_input_power_bounds = wx.StaticText(self, -1, \"Thruster input power bounds\")\r\n self.txtengine_input_power_bounds_lower = wx.TextCtrl(self, -1, \"engine_input_power_bounds[0]\")\r\n self.txtengine_input_power_bounds_upper = wx.TextCtrl(self, -1, \"engine_input_power_bounds[1]\")\r\n enginepowerbox = wx.BoxSizer(wx.HORIZONTAL)\r\n enginepowerbox.AddMany([self.txtengine_input_power_bounds_lower, self.txtengine_input_power_bounds_upper])\r\n\r\n customthrustergrid = wx.FlexGridSizer(3, 8, 5, 5)\r\n customthrustergrid.AddMany([self.lblengine_coefficient_spacer, self.lblengine_coefficient0, self.lblengine_coefficient1, self.lblengine_coefficient2, self.lblengine_coefficient3, self.lblengine_coefficient4, self.lblengine_coefficient5, self.lblengine_coefficient6,\r\n self.lblengine_input_thrust_coefficients, self.txtengine_input_thrust_coefficients0, self.txtengine_input_thrust_coefficients1, self.txtengine_input_thrust_coefficients2, self.txtengine_input_thrust_coefficients3, self.txtengine_input_thrust_coefficients4, self.txtengine_input_thrust_coefficients5, self.txtengine_input_thrust_coefficients6,\r\n self.lblengine_input_mass_flow_rate_coefficients, self.txtengine_input_mass_flow_rate_coefficients0, self.txtengine_input_mass_flow_rate_coefficients1, self.txtengine_input_mass_flow_rate_coefficients2, self.txtengine_input_mass_flow_rate_coefficients3, self.txtengine_input_mass_flow_rate_coefficients4, self.txtengine_input_mass_flow_rate_coefficients5, self.txtengine_input_mass_flow_rate_coefficients6])\r\n\r\n propulsiongrid.AddMany([self.lblIspChem, self.txtIspChem,\r\n self.lblengine_type, self.cmbengine_type,\r\n self.lblnumber_of_engines, self.txtnumber_of_engines,\r\n self.lblthrottle_logic_mode, self.cmbthrottle_logic_mode,\r\n self.lblthrottle_sharpness, self.txtthrottle_sharpness,\r\n self.lblengine_duty_cycle, self.txtengine_duty_cycle,\r\n self.lblThrust, self.txtThrust,\r\n self.lblIspLT, self.txtIspLT,\r\n self.lblIspLT_minimum, self.txtIspLT_minimum,\r\n self.lbluser_defined_engine_efficiency, self.txtuser_defined_engine_efficiency,\r\n self.lblengine_input_power_bounds, enginepowerbox])\r\n\r\n\r\n\r\n propulsionbox = wx.BoxSizer(wx.VERTICAL)\r\n propulsionbox.AddMany([propulsiongridtitle, propulsiongrid, customthrustergrid])\r\n\r\n #power\r\n powergrid = wx.FlexGridSizer(20,2,5,5)\r\n self.powergridtitle = wx.StaticText(self, -1, \"Power options\")\r\n\r\n self.lblpower_at_1_AU = wx.StaticText(self, -1, \"Power at 1 AU (kW)\")\r\n self.txtpower_at_1_AU = wx.TextCtrl(self, -1, \"power_at_1_AU\")\r\n\r\n self.lblpower_source_type = wx.StaticText(self, -1, \"Power source type\")\r\n power_source_choices = ['0: solar','1: radioisotope']\r\n self.cmbpower_source_type = wx.ComboBox(self, -1, choices=power_source_choices, style=wx.CB_READONLY)\r\n\r\n self.lblsolar_power_gamma = wx.StaticText(self, -1, \"Solar power coefficients\")\r\n self.txtsolar_power_gamma0 = wx.TextCtrl(self, -1, \"solar_power_gamma[0]\")\r\n self.txtsolar_power_gamma1 = wx.TextCtrl(self, -1, \"solar_power_gamma[1]\")\r\n self.txtsolar_power_gamma2 = wx.TextCtrl(self, -1, \"solar_power_gamma[2]\")\r\n self.txtsolar_power_gamma3 = wx.TextCtrl(self, -1, \"solar_power_gamma[3]\")\r\n self.txtsolar_power_gamma4 = wx.TextCtrl(self, -1, \"solar_power_gamma[4]\")\r\n solarpowerbox = wx.BoxSizer(wx.HORIZONTAL)\r\n solarpowerbox.AddMany([self.txtsolar_power_gamma0, self.txtsolar_power_gamma1, self.txtsolar_power_gamma2, self.txtsolar_power_gamma3, self.txtsolar_power_gamma4])\r\n\r\n self.lblspacecraft_power_model_type = wx.StaticText(self, -1, \"Spacecraft power model type\")\r\n power_model_choices = ['0: P_sc = A + B/r + C/r^2','1: P_sc = A if P > A, A + B(C - P) otherwise']\r\n self.cmbspacecraft_power_model_type = wx.ComboBox(self, -1, choices=power_model_choices, style = wx.CB_READONLY)\r\n \r\n self.lblspacecraft_power_coefficients = wx.StaticText(self, -1, \"Spacecraft power coefficients\")\r\n self.txtspacecraft_power_coefficients0 = wx.TextCtrl(self, -1, \"spacecraft_power_coefficients[0]\")\r\n self.txtspacecraft_power_coefficients1 = wx.TextCtrl(self, -1, \"spacecraft_power_coefficients[1]\")\r\n self.txtspacecraft_power_coefficients2 = wx.TextCtrl(self, -1, \"spacecraft_power_coefficients[2]\")\r\n spacecraftpowerbox = wx.BoxSizer(wx.HORIZONTAL)\r\n spacecraftpowerbox.AddMany([self.txtspacecraft_power_coefficients0, self.txtspacecraft_power_coefficients1, self.txtspacecraft_power_coefficients2])\r\n\r\n self.lblpower_decay_rate = wx.StaticText(self, -1, \"Power decay rate (fraction per year)\")\r\n self.txtpower_decay_rate = wx.TextCtrl(self, -1, \"power_decay_rate\")\r\n\r\n powergrid.AddMany([self.lblpower_at_1_AU, self.txtpower_at_1_AU,\r\n self.lblpower_source_type, self.cmbpower_source_type,\r\n self.lblsolar_power_gamma, solarpowerbox,\r\n self.lblspacecraft_power_model_type, self.cmbspacecraft_power_model_type,\r\n self.lblspacecraft_power_coefficients, spacecraftpowerbox,\r\n self.lblpower_decay_rate, self.txtpower_decay_rate])\r\n\r\n powerbox = wx.BoxSizer(wx.VERTICAL)\r\n powerbox.AddMany([self.powergridtitle, powergrid])\r\n\r\n #now tie everything together\r\n leftvertsizer = wx.BoxSizer(wx.VERTICAL)\r\n leftvertsizer.AddMany([spacecraftbox, propulsionbox, powerbox])\r\n \r\n self.mainbox = wx.BoxSizer(wx.HORIZONTAL)\r\n self.mainbox.AddMany([leftvertsizer, constraintsbox]) \r\n\r\n font = self.GetFont()\r\n font.SetWeight(wx.FONTWEIGHT_BOLD)\r\n spacecraftgridtitle.SetFont(font)\r\n self.powergridtitle.SetFont(font)\r\n constraintsgridtitle.SetFont(font)\r\n propulsiongridtitle.SetFont(font)\r\n\r\n self.SetSizer(self.mainbox)\r\n self.SetupScrolling()\r\n\r\n\r\nclass JourneyOptionsPanel(wx.lib.scrolledpanel.ScrolledPanel):\r\n def __init__(self, parent):\r\n \r\n wx.lib.scrolledpanel.ScrolledPanel.__init__(self, parent)\r\n\r\n self.JourneyList = []\r\n\r\n self.JourneySelectBox = wx.ListBox(self, -1, choices=self.JourneyList, size=(300,200), style=wx.LB_SINGLE)\r\n self.btnAddNewJourney = wx.Button(self, -1, \"New Journey\", size=(200,-1))\r\n self.btnDeleteJourney = wx.Button(self, -1, \"Delete Journey\", size=(200,-1))\r\n self.btnMoveJourneyUp = wx.Button(self, -1, \"Move Journey Up\", size=(200,-1))\r\n self.btnMoveJourneyDown = wx.Button(self, -1, \"Move Journey Down\", size=(200,-1))\r\n\r\n buttonstacksizer = wx.BoxSizer(wx.VERTICAL)\r\n buttonstacksizer.AddMany([self.btnAddNewJourney, self.btnDeleteJourney, self.btnMoveJourneyUp, self.btnMoveJourneyDown])\r\n\r\n JourneySelectionSizer = wx.BoxSizer(wx.HORIZONTAL)\r\n JourneySelectionSizer.Add(self.JourneySelectBox)\r\n JourneySelectionSizer.AddSpacer(5)\r\n JourneySelectionSizer.Add(buttonstacksizer)\r\n\r\n self.lbljourney_names = wx.StaticText(self, -1, \"Journey name\")\r\n self.txtjourney_names = wx.TextCtrl(self, -1, \"journey_names\", size=(300,-1))\r\n\r\n self.lbljourney_central_body = wx.StaticText(self, -1, \"Central body\")\r\n self.txtjourney_central_body = wx.TextCtrl(self, -1, \"journey_central_body\")\r\n self.btnjourney_central_body = wx.Button(self, -1, \"...\")\r\n journey_central_body_box = wx.BoxSizer(wx.HORIZONTAL)\r\n journey_central_body_box.Add(self.txtjourney_central_body)\r\n journey_central_body_box.AddSpacer(5)\r\n journey_central_body_box.Add(self.btnjourney_central_body)\r\n\r\n self.lbldestination_list = wx.StaticText(self, -1, \"Destination list\")\r\n self.txtdestination_list = wx.TextCtrl(self, -1, \"destination_list\")\r\n self.btndestination_list = wx.Button(self, -1, \"...\")\r\n destination_list_box = wx.BoxSizer(wx.HORIZONTAL)\r\n destination_list_box.Add(self.txtdestination_list)\r\n destination_list_box.AddSpacer(5)\r\n destination_list_box.Add(self.btndestination_list)\r\n\r\n self.lbljourney_starting_mass_increment = wx.StaticText(self, -1, \"Starting mass increment (kg)\")\r\n self.txtjourney_starting_mass_increment = wx.TextCtrl(self, -1, \"journey_starting_mass_increment\")\r\n\r\n self.lbljourney_variable_mass_increment = wx.StaticText(self, -1, \"Variable mass increment\")\r\n self.chkjourney_variable_mass_increment = wx.CheckBox(self, -1)\r\n\r\n self.lbljourney_wait_time_bounds = wx.StaticText(self, -1, \"Wait time bounds\")\r\n self.txtjourney_wait_time_bounds_lower = wx.TextCtrl(self, -1, \"journey_wait_time_bounds[0]\")\r\n self.txtjourney_wait_time_bounds_upper = wx.TextCtrl(self, -1, \"journey_wait_time_bounds[1]\")\r\n wait_time_sizer = wx.BoxSizer(wx.HORIZONTAL)\r\n wait_time_sizer.AddMany([self.txtjourney_wait_time_bounds_lower, self.txtjourney_wait_time_bounds_upper])\r\n\r\n self.lbljourney_timebounded = wx.StaticText(self, -1, \"Journey time bounds\")\r\n journey_time_bounds_choices = ['unbounded','bounded flight time','bounded arrival date','bounded aggregate flight time']\r\n self.cmbjourney_timebounded = wx.ComboBox(self, -1, choices=journey_time_bounds_choices, style=wx.CB_READONLY)\r\n\r\n self.lbljourney_flight_time_bounds = wx.StaticText(self, -1, \"Journey flight time bounds\")\r\n self.txtjourney_flight_time_bounds_lower = wx.TextCtrl(self, -1, \"journey_flight_time_bounds[0]\")\r\n self.txtjourney_flight_time_bounds_upper = wx.TextCtrl(self, -1, \"journey_flight_time_bounds[1]\")\r\n flight_time_sizer = wx.BoxSizer(wx.HORIZONTAL)\r\n flight_time_sizer.AddMany([self.txtjourney_flight_time_bounds_lower, self.txtjourney_flight_time_bounds_upper])\r\n\r\n self.lbljourney_arrival_date_bounds = wx.StaticText(self, -1, \"Journey arrival date bounds\")\r\n self.txtjourney_arrival_date_bounds_lower = wx.TextCtrl(self, -1, \"journey_arrival_date_bounds[0]\")\r\n self.txtjourney_arrival_date_bounds_upper = wx.TextCtrl(self, -1, \"journey_arrival_date_bounds[1]\")\r\n self.ArrivalDateLowerCalendar = wx.calendar.CalendarCtrl(self, -1)\r\n self.ArrivalDateUpperCalendar = wx.calendar.CalendarCtrl(self, -1)\r\n arrival_date_sizer = wx.BoxSizer(wx.HORIZONTAL)\r\n arrival_date_sizer.AddMany([self.txtjourney_arrival_date_bounds_lower, self.ArrivalDateLowerCalendar, self.txtjourney_arrival_date_bounds_upper, self.ArrivalDateUpperCalendar])\r\n\r\n self.lbljourney_initial_impulse_bounds = wx.StaticText(self, -1, \"Journey initial impulse bounds\")\r\n self.txtjourney_initial_impulse_bounds_lower = wx.TextCtrl(self, -1, \"journey_initial_impulse_bounds[0]\")\r\n self.txtjourney_initial_impulse_bounds_upper = wx.TextCtrl(self, -1, \"journey_initial_impulse_bounds[1]\")\r\n initial_impulse_sizer = wx.BoxSizer(wx.HORIZONTAL)\r\n initial_impulse_sizer.AddMany([self.txtjourney_initial_impulse_bounds_lower, self.txtjourney_initial_impulse_bounds_upper])\r\n\r\n self.lbljourney_departure_type = wx.StaticText(self, -1, \"Journey departure type\")\r\n journey_departure_type_choices = ['0: launch or direct insertion','1: depart from parking orbit','2: free direct departure',\r\n '3: flyby','4: flyby with fixed v-infinity-out','5: Spiral-out from circular orbit','6: zero-turn flyby (for small bodies)']\r\n self.cmbjourney_departure_type = wx.ComboBox(self, -1, choices=journey_departure_type_choices, style=wx.CB_READONLY)\r\n\r\n self.lbljourney_initial_velocity = wx.StaticText(self, -1, \"Journey initial velocity vector\")\r\n self.txtjourney_initial_velocity0 = wx.TextCtrl(self, -1, \"journey_initial_velocity[0]\")\r\n self.txtjourney_initial_velocity1 = wx.TextCtrl(self, -1, \"journey_initial_velocity[1]\")\r\n self.txtjourney_initial_velocity2 = wx.TextCtrl(self, -1, \"journey_initial_velocity[2]\")\r\n journey_initial_velocity_box = wx.BoxSizer(wx.HORIZONTAL)\r\n journey_initial_velocity_box.AddMany([self.txtjourney_initial_velocity0, self.txtjourney_initial_velocity1, self.txtjourney_initial_velocity2])\r\n\r\n self.lbljourney_escape_spiral_starting_radius = wx.StaticText(self, -1, \"Orbital radius for beginning of escape spiral (km)\")\r\n self.txtjourney_escape_spiral_starting_radius = wx.TextCtrl(self, -1, \"journey_escape_spiral_starting_radius\")\r\n\r\n self.lbljourney_maximum_DSM_magnitude_flag = wx.StaticText(self, -1, \"Enable journey DSM magnitude constraint?\")\r\n self.chkjourney_maximum_DSM_magnitude_flag = wx.CheckBox(self, -1)\r\n self.lbljourney_maximum_DSM_magnitude = wx.StaticText(self, -1, \"Journey maximum DSM magnitude (km/s)\")\r\n self.txtjourney_maximum_DSM_magnitude = wx.TextCtrl(self, -1, \"journey_maximum_DSM_magnitude\")\r\n\r\n\r\n self.lbljourney_arrival_type = wx.StaticText(self, -1, \"Journey arrival type\")\r\n journey_arrival_type_choices = ['0: insertion into parking orbit (use chemical Isp)','1: rendezvous (use chemical Isp)','2: intercept with bounded V_infinity',\r\n '3: low-thrust rendezvous (does not work if terminal phase is not low-thrust)','4: match final v-infinity vector',\r\n '5: match final v-infinity vector (low-thrust)','6: escape (E = 0)','7: capture spiral']\r\n self.cmbjourney_arrival_type = wx.ComboBox(self, -1, choices=journey_arrival_type_choices, style=wx.CB_READONLY)\r\n\r\n self.lbljourney_capture_spiral_final_radius = wx.StaticText(self, -1, \"Orbital radius for end of capture spiral (km)\")\r\n self.txtjourney_capture_spiral_final_radius = wx.TextCtrl(self, -1, \"journey_capture_spiral_final_radius\")\r\n\r\n self.lbljourney_final_velocity = wx.StaticText(self, -1, \"Journey final velocity vector\")\r\n self.txtjourney_final_velocity0 = wx.TextCtrl(self, -1, \"journey_final_velocity[0]\")\r\n self.txtjourney_final_velocity1 = wx.TextCtrl(self, -1, \"journey_final_velocity[1]\")\r\n self.txtjourney_final_velocity2 = wx.TextCtrl(self, -1, \"journey_final_velocity[2]\")\r\n journey_final_velocity_box = wx.BoxSizer(wx.HORIZONTAL)\r\n journey_final_velocity_box.AddMany([self.txtjourney_final_velocity0, self.txtjourney_final_velocity1, self.txtjourney_final_velocity2])\r\n\r\n self.lbljourney_arrival_declination_constraint_flag = wx.StaticText(self, -1, \"Apply arrival declination constraint?\")\r\n self.chkjourney_arrival_declination_constraint_flag = wx.CheckBox(self, -1)\r\n self.lbljourney_arrival_declination_bounds = wx.StaticText(self, -1, \"Arrival Declination bounds\")\r\n self.txtjourney_arrival_declination_bounds_lower = wx.TextCtrl(self, -1, \"journey_arrival_declination_bounds[0]\")\r\n self.txtjourney_arrival_declination_bounds_upper = wx.TextCtrl(self, -1, \"journey_arrival_declination_bounds[1]\")\r\n declination_bounds_box = wx.BoxSizer(wx.HORIZONTAL)\r\n declination_bounds_box.AddMany([self.txtjourney_arrival_declination_bounds_lower, self.txtjourney_arrival_declination_bounds_upper])\r\n\r\n self.lblsequence = wx.StaticText(self, -1, \"Flyby sequence\")\r\n self.txtsequence = wx.TextCtrl(self, -1, \"sequence\", size=(300,60), style=wx.TE_MULTILINE)\r\n self.btnsequence = wx.Button(self, -1, \"...\")\r\n sequence_box = wx.BoxSizer(wx.HORIZONTAL)\r\n sequence_box.Add(self.txtsequence)\r\n sequence_box.AddSpacer(5)\r\n sequence_box.Add(self.btnsequence)\r\n\r\n self.lbljourney_perturbation_bodies = wx.StaticText(self, -1, \"Perturbation_bodies\")\r\n self.txtjourney_perturbation_bodies = wx.TextCtrl(self, -1, \"journey_perturbation_bodies\", size=(300,-1))\r\n self.btnjourney_perturbation_bodies = wx.Button(self, -1, \"...\")\r\n journey_perturbation_bodies_box = wx.BoxSizer(wx.HORIZONTAL)\r\n journey_perturbation_bodies_box.Add(self.txtjourney_perturbation_bodies)\r\n journey_perturbation_bodies_box.AddSpacer(5)\r\n journey_perturbation_bodies_box.Add(self.btnjourney_perturbation_bodies)\r\n\r\n \r\n\r\n JourneyInformationGrid = wx.FlexGridSizer(40,2,5,5)\r\n JourneyInformationGrid.AddMany([self.lbljourney_names, self.txtjourney_names,\r\n self.lbljourney_central_body, journey_central_body_box,\r\n self.lbldestination_list, destination_list_box,\r\n self.lbljourney_starting_mass_increment, self.txtjourney_starting_mass_increment,\r\n self.lbljourney_variable_mass_increment, self.chkjourney_variable_mass_increment,\r\n self.lbljourney_wait_time_bounds, wait_time_sizer,\r\n self.lbljourney_timebounded, self.cmbjourney_timebounded,\r\n self.lbljourney_flight_time_bounds, flight_time_sizer,\r\n self.lbljourney_arrival_date_bounds, arrival_date_sizer,\r\n self.lbljourney_initial_impulse_bounds, initial_impulse_sizer,\r\n self.lbljourney_departure_type, self.cmbjourney_departure_type,\r\n self.lbljourney_escape_spiral_starting_radius, self.txtjourney_escape_spiral_starting_radius,\r\n self.lbljourney_initial_velocity, journey_initial_velocity_box,\r\n self.lbljourney_maximum_DSM_magnitude_flag, self.chkjourney_maximum_DSM_magnitude_flag,\r\n self.lbljourney_maximum_DSM_magnitude, self.txtjourney_maximum_DSM_magnitude,\r\n self.lbljourney_arrival_type, self.cmbjourney_arrival_type,\r\n self.lbljourney_capture_spiral_final_radius, self.txtjourney_capture_spiral_final_radius,\r\n self.lbljourney_final_velocity, journey_final_velocity_box,\r\n self.lbljourney_arrival_declination_constraint_flag, self.chkjourney_arrival_declination_constraint_flag,\r\n self.lbljourney_arrival_declination_bounds, declination_bounds_box,\r\n self.lblsequence, sequence_box,\r\n self.lbljourney_perturbation_bodies, journey_perturbation_bodies_box])\r\n\r\n JourneyInformationStacker = wx.BoxSizer(wx.VERTICAL)\r\n JourneyInformationStacker.AddMany([JourneySelectionSizer, JourneyInformationGrid])\r\n\r\n #custom departure elements\r\n self.boxjourney_departure_elements = wx.StaticBox(self, -1, \"Journey departure elements\")\r\n self.lbljourney_departure_elements_type= wx.StaticText(self, -1, \"Journey departure elements type\")\r\n journey_departure_elements_type_choices = ['0: inertial', '1: COE']\r\n self.cmbjourney_departure_elements_type = wx.ComboBox(self, -1, choices=journey_departure_elements_type_choices, style=wx.CB_READONLY)\r\n departure_elements_type_box = wx.BoxSizer(wx.HORIZONTAL)\r\n departure_elements_type_box.Add(self.lbljourney_departure_elements_type)\r\n departure_elements_type_box.AddSpacer(5)\r\n departure_elements_type_box.Add(self.cmbjourney_departure_elements_type)\r\n\r\n empty_departure_cell = wx.StaticText(self, -1, \"\")\r\n self.lblvarydepartureelements = wx.StaticText(self, -1, \"Vary?\")\r\n self.lbldepartureelementsvalue = wx.StaticText(self, -1, \"Value\")\r\n self.lbldepartureelementslower = wx.StaticText(self, -1, \"Lower bound\")\r\n self.lbldepartureelementsupper = wx.StaticText(self, -1, \"Upper bound\")\r\n self.lblSMA_departure = wx.StaticText(self, -1, \"SMA\")\r\n self.lblECC_departure = wx.StaticText(self, -1, \"ECC\")\r\n self.lblINC_departure = wx.StaticText(self, -1, \"INC\")\r\n self.lblRAAN_departure = wx.StaticText(self, -1, \"RAAN\")\r\n self.lblAOP_departure = wx.StaticText(self, -1, \"AOP\")\r\n self.lblMA_departure = wx.StaticText(self, -1, \"MA\")\r\n self.chkSMA_departure = wx.CheckBox(self, -1)\r\n self.chkECC_departure = wx.CheckBox(self, -1)\r\n self.chkINC_departure = wx.CheckBox(self, -1)\r\n self.chkRAAN_departure = wx.CheckBox(self, -1)\r\n self.chkAOP_departure = wx.CheckBox(self, -1)\r\n self.chkMA_departure = wx.CheckBox(self, -1)\r\n self.txtSMA_departure = wx.TextCtrl(self, -1, \"SMA_val\")\r\n self.txtECC_departure = wx.TextCtrl(self, -1, \"ECC_val\")\r\n self.txtINC_departure = wx.TextCtrl(self, -1, \"INC_val\")\r\n self.txtRAAN_departure = wx.TextCtrl(self, -1, \"RAAN_val\")\r\n self.txtAOP_departure = wx.TextCtrl(self, -1, \"AOP_val\")\r\n self.txtMA_departure = wx.TextCtrl(self, -1, \"MA_val\")\r\n self.txtSMA_departure0 = wx.TextCtrl(self, -1, \"SMA_val0\")\r\n self.txtECC_departure0 = wx.TextCtrl(self, -1, \"ECC_val0\")\r\n self.txtINC_departure0 = wx.TextCtrl(self, -1, \"INC_val0\")\r\n self.txtRAAN_departure0 = wx.TextCtrl(self, -1, \"RAAN_val0\")\r\n self.txtAOP_departure0 = wx.TextCtrl(self, -1, \"AOP_val0\")\r\n self.txtMA_departure0 = wx.TextCtrl(self, -1, \"MA_val0\")\r\n self.txtSMA_departure1 = wx.TextCtrl(self, -1, \"SMA_val1\")\r\n self.txtECC_departure1 = wx.TextCtrl(self, -1, \"ECC_val1\")\r\n self.txtINC_departure1 = wx.TextCtrl(self, -1, \"INC_val1\")\r\n self.txtRAAN_departure1 = wx.TextCtrl(self, -1, \"RAAN_val1\")\r\n self.txtAOP_departure1 = wx.TextCtrl(self, -1, \"AOP_val1\")\r\n self.txtMA_departure1 = wx.TextCtrl(self, -1, \"MA_val1\")\r\n DepartureElementsSizer = wx.FlexGridSizer(14,5,5,5)\r\n DepartureElementsSizer.AddMany([empty_departure_cell, self.lblvarydepartureelements, self.lbldepartureelementsvalue, self.lbldepartureelementslower, self.lbldepartureelementsupper, \r\n self.lblSMA_departure, self.chkSMA_departure, self.txtSMA_departure, self.txtSMA_departure0, self.txtSMA_departure1,\r\n self.lblECC_departure, self.chkECC_departure, self.txtECC_departure, self.txtECC_departure0, self.txtECC_departure1,\r\n self.lblINC_departure, self.chkINC_departure, self.txtINC_departure, self.txtINC_departure0, self.txtINC_departure1,\r\n self.lblRAAN_departure, self.chkRAAN_departure, self.txtRAAN_departure, self.txtRAAN_departure0, self.txtRAAN_departure1,\r\n self.lblAOP_departure, self.chkAOP_departure, self.txtAOP_departure, self.txtAOP_departure0, self.txtAOP_departure1,\r\n self.lblMA_departure, self.chkMA_departure, self.txtMA_departure, self.txtMA_departure0, self.txtMA_departure1])\r\n self.DepartureElementsBox = wx.StaticBoxSizer(self.boxjourney_departure_elements, wx.VERTICAL)\r\n self.DepartureElementsBox.AddMany([departure_elements_type_box, DepartureElementsSizer])\r\n \r\n font = self.GetFont()\r\n font.SetWeight(wx.FONTWEIGHT_BOLD)\r\n self.boxjourney_departure_elements.SetFont(font)\r\n\r\n\r\n #custom arrival elements\r\n self.boxjourney_arrival_elements = wx.StaticBox(self, -1, \"Journey arrival elements\")\r\n self.lbljourney_arrival_elements_type= wx.StaticText(self, -1, \"Journey arrival elements type\")\r\n journey_arrival_elements_type_choices = ['0: inertial', '1: COE']\r\n self.cmbjourney_arrival_elements_type = wx.ComboBox(self, -1, choices=journey_arrival_elements_type_choices, style=wx.CB_READONLY)\r\n arrival_elements_type_box = wx.BoxSizer(wx.HORIZONTAL)\r\n arrival_elements_type_box.Add(self.lbljourney_arrival_elements_type)\r\n arrival_elements_type_box.AddSpacer(5)\r\n arrival_elements_type_box.Add(self.cmbjourney_arrival_elements_type)\r\n\r\n empty_arrival_cell = wx.StaticText(self, -1, \"\")\r\n self.lblvaryarrivalelements = wx.StaticText(self, -1, \"Vary?\")\r\n self.lblarrivalelementsvalue = wx.StaticText(self, -1, \"Value\")\r\n self.lblarrivalelementslower = wx.StaticText(self, -1, \"Lower bound\")\r\n self.lblarrivalelementsupper = wx.StaticText(self, -1, \"Upper bound\")\r\n self.lblSMA_arrival = wx.StaticText(self, -1, \"SMA\")\r\n self.lblECC_arrival = wx.StaticText(self, -1, \"ECC\")\r\n self.lblINC_arrival = wx.StaticText(self, -1, \"INC\")\r\n self.lblRAAN_arrival = wx.StaticText(self, -1, \"RAAN\")\r\n self.lblAOP_arrival = wx.StaticText(self, -1, \"AOP\")\r\n self.lblMA_arrival = wx.StaticText(self, -1, \"MA\")\r\n self.chkSMA_arrival = wx.CheckBox(self, -1)\r\n self.chkECC_arrival = wx.CheckBox(self, -1)\r\n self.chkINC_arrival = wx.CheckBox(self, -1)\r\n self.chkRAAN_arrival = wx.CheckBox(self, -1)\r\n self.chkAOP_arrival = wx.CheckBox(self, -1)\r\n self.chkMA_arrival = wx.CheckBox(self, -1)\r\n self.txtSMA_arrival = wx.TextCtrl(self, -1, \"SMA_val\")\r\n self.txtECC_arrival = wx.TextCtrl(self, -1, \"ECC_val\")\r\n self.txtINC_arrival = wx.TextCtrl(self, -1, \"INC_val\")\r\n self.txtRAAN_arrival = wx.TextCtrl(self, -1, \"RAAN_val\")\r\n self.txtAOP_arrival = wx.TextCtrl(self, -1, \"AOP_val\")\r\n self.txtMA_arrival = wx.TextCtrl(self, -1, \"MA_val\")\r\n self.txtSMA_arrival0 = wx.TextCtrl(self, -1, \"SMA_val0\")\r\n self.txtECC_arrival0 = wx.TextCtrl(self, -1, \"ECC_val0\")\r\n self.txtINC_arrival0 = wx.TextCtrl(self, -1, \"INC_val0\")\r\n self.txtRAAN_arrival0 = wx.TextCtrl(self, -1, \"RAAN_val0\")\r\n self.txtAOP_arrival0 = wx.TextCtrl(self, -1, \"AOP_val0\")\r\n self.txtMA_arrival0 = wx.TextCtrl(self, -1, \"MA_val0\")\r\n self.txtSMA_arrival1 = wx.TextCtrl(self, -1, \"SMA_val1\")\r\n self.txtECC_arrival1 = wx.TextCtrl(self, -1, \"ECC_val1\")\r\n self.txtINC_arrival1 = wx.TextCtrl(self, -1, \"INC_val1\")\r\n self.txtRAAN_arrival1 = wx.TextCtrl(self, -1, \"RAAN_val1\")\r\n self.txtAOP_arrival1 = wx.TextCtrl(self, -1, \"AOP_val1\")\r\n self.txtMA_arrival1 = wx.TextCtrl(self, -1, \"MA_val1\")\r\n ArrivalElementsSizer = wx.FlexGridSizer(14,5,5,5)\r\n ArrivalElementsSizer.AddMany([empty_arrival_cell, self.lblvaryarrivalelements, self.lblarrivalelementsvalue, self.lblarrivalelementslower, self.lblarrivalelementsupper, \r\n self.lblSMA_arrival, self.chkSMA_arrival, self.txtSMA_arrival, self.txtSMA_arrival0, self.txtSMA_arrival1,\r\n self.lblECC_arrival, self.chkECC_arrival, self.txtECC_arrival, self.txtECC_arrival0, self.txtECC_arrival1,\r\n self.lblINC_arrival, self.chkINC_arrival, self.txtINC_arrival, self.txtINC_arrival0, self.txtINC_arrival1,\r\n self.lblRAAN_arrival, self.chkRAAN_arrival, self.txtRAAN_arrival, self.txtRAAN_arrival0, self.txtRAAN_arrival1,\r\n self.lblAOP_arrival, self.chkAOP_arrival, self.txtAOP_arrival, self.txtAOP_arrival0, self.txtAOP_arrival1,\r\n self.lblMA_arrival, self.chkMA_arrival, self.txtMA_arrival, self.txtMA_arrival0, self.txtMA_arrival1])\r\n self.ArrivalElementsBox = wx.StaticBoxSizer(self.boxjourney_arrival_elements, wx.VERTICAL)\r\n self.ArrivalElementsBox.AddMany([arrival_elements_type_box, ArrivalElementsSizer])\r\n \r\n font = self.GetFont()\r\n font.SetWeight(wx.FONTWEIGHT_BOLD)\r\n self.boxjourney_arrival_elements.SetFont(font)\r\n\r\n ElementsStacker = wx.BoxSizer(wx.VERTICAL)\r\n ElementsStacker.AddMany([self.DepartureElementsBox, self.ArrivalElementsBox])\r\n\r\n self.mainbox = wx.BoxSizer(wx.HORIZONTAL)\r\n self.mainbox.AddMany([JourneyInformationStacker, ElementsStacker])\r\n self.SetSizer(self.mainbox)\r\n self.SetupScrolling()\r\n \r\nclass SolverOptionsPanel(wx.lib.scrolledpanel.ScrolledPanel):\r\n def __init__(self, parent):\r\n\r\n wx.lib.scrolledpanel.ScrolledPanel.__init__(self, parent)\r\n \r\n innerloopgrid = wx.GridSizer(28,2,5,5)\r\n \r\n self.lblInnerLoopSolver = wx.StaticText(self, -1, \"Inner-loop Solver Mode\")\r\n innerloopsolvertypes = ['Evaluate trialX', 'Evaluate a batch of trialX vectors','Monotonic Basin Hopping',\r\n 'Adaptive Constrained Differential Evolution','SNOPT with initial guess']\r\n self.cmbInnerLoopSolver = wx.ComboBox(self, -1, choices = innerloopsolvertypes, style=wx.CB_READONLY)\r\n\r\n self.lblNLP_solver_type = wx.StaticText(self, -1, \"NLP solver\")\r\n NLP_solver_types = ['SNOPT','WORHP']\r\n self.cmbNLP_solver_type = wx.ComboBox(self, -1, choices = NLP_solver_types, style=wx.CB_READONLY)\r\n\r\n self.lblNLP_solver_mode = wx.StaticText(self, -1, \"NLP solver mode\")\r\n NLP_solver_modes = ['Feasible point','Optimize']\r\n self.cmbNLP_solver_mode = wx.ComboBox(self, -1, choices = NLP_solver_modes, style = wx.CB_READONLY)\r\n\r\n self.lblquiet_NLP = wx.StaticText(self, -1, \"Quiet NLP solver?\")\r\n self.chkquiet_NLP = wx.CheckBox(self, -1)\r\n\r\n self.lblquiet_MBH = wx.StaticText(self, -1, \"Quiet MBH solver?\")\r\n self.chkquiet_MBH = wx.CheckBox(self, -1)\r\n\r\n self.lblMBH_two_step = wx.StaticText(self, -1, \"Two-step MBH?\")\r\n self.chkMBH_two_step = wx.CheckBox(self, -1)\r\n\r\n self.lblFD_stepsize = wx.StaticText(self, -1, \"Finite differencing step size\")\r\n self.txtFD_stepsize = wx.TextCtrl(self, -1, \"FD_stepsize\")\r\n\r\n self.lblFD_stepsize_coarse = wx.StaticText(self, -1, \"Finite differencing coarse step size\")\r\n self.txtFD_stepsize_coarse = wx.TextCtrl(self, -1, \"FD_stepsize_coarse\")\r\n\r\n self.lblACE_feasible_point_finder = wx.StaticText(self, -1, \"Enable ACE feasible point finder?\")\r\n self.chkACE_feasible_point_finder = wx.CheckBox(self, -1)\r\n \r\n self.lblMBH_max_not_improve = wx.StaticText(self, -1, \"MBH Impatience\")\r\n self.txtMBH_max_not_improve = wx.TextCtrl(self, -1, \"MBH_max_not_improve\")\r\n \r\n self.lblMBH_max_trials = wx.StaticText(self, -1, \"Maximum number of innerloop trials\")\r\n self.txtMBH_max_trials = wx.TextCtrl(self, -1, \"MBH_max_trials\")\r\n \r\n self.lblMBH_max_run_time = wx.StaticText(self, -1, \"Maximum run-time\")\r\n self.txtMBH_max_run_time = wx.TextCtrl(self, -1, \"MBH_max_run_time\")\r\n \r\n self.lblMBH_max_step_size = wx.StaticText(self, -1, \"MBH maximum perturbation size\")\r\n self.txtMBH_max_step_size = wx.TextCtrl(self, -1, \"MBH_max_step_size\")\r\n\r\n self.lblMBH_hop_distribution = wx.StaticText(self, -1, \"MBH hop probability distribution\")\r\n hop_distribution_choices = [\"Uniform\",\"Cauchy\",\"Pareto\",\"Gaussian\"]\r\n self.cmbMBH_hop_distribution = wx.ComboBox(self, -1, choices = hop_distribution_choices, style = wx.CB_READONLY)\r\n\r\n self.lblMBH_Pareto_alpha = wx.StaticText(self, -1, \"MBH Pareto distribution alpha\")\r\n self.txtMBH_Pareto_alpha = wx.TextCtrl(self, -1, \"MBH_Pareto_alpha\")\r\n\r\n self.lblMBH_time_hop_probability = wx.StaticText(self, -1, \"Probability of MBH time hop\")\r\n self.txtMBH_time_hop_probability = wx.TextCtrl(self, -1, \"MBH_time_hop_probability\")\r\n \r\n self.lblsnopt_feasibility_tolerance = wx.StaticText(self, -1, \"Feasibility tolerance\")\r\n self.txtsnopt_feasibility_tolerance = wx.TextCtrl(self, -1, \"snopt_feasibility_tolerance\")\r\n \r\n self.lblsnopt_major_iterations = wx.StaticText(self, -1, \"SNOPT major iterations limit\")\r\n self.txtsnopt_major_iterations = wx.TextCtrl(self, -1, \"snopt_major_iterations\")\r\n \r\n self.lblsnopt_max_run_time = wx.StaticText(self, -1, \"SNOPT maximum run time\")\r\n self.txtsnopt_max_run_time = wx.TextCtrl(self, -1, \"snopt_max_run_time\")\r\n \r\n self.lblderivative_type = wx.StaticText(self, -1, \"Derivative calculation method\")\r\n derivativechoices = [\"Finite Differencing\",\"Analytical flybys and objective function\",\"Analytical all but time\",\"All but current phase flight time derivatives\",\"Fully analytical (experimental)\"]\r\n self.cmbderivative_type = wx.ComboBox(self, -1, choices = derivativechoices, style = wx.CB_READONLY)\r\n \r\n self.lblcheck_derivatives = wx.StaticText(self, -1, \"Check derivatives via finite differencing?\")\r\n self.chkcheck_derivatives = wx.CheckBox(self, -1)\r\n \r\n self.lblseed_MBH = wx.StaticText(self, -1, \"Seed MBH?\")\r\n self.chkseed_MBH = wx.CheckBox(self, -1)\r\n\r\n self.lblinitial_guess_control_coordinate_system = wx.StaticText(self, -1, \"Initial guess control coordinate system\")\r\n control_coordinate_choices = ['Cartesian','Polar']\r\n self.cmbinitial_guess_control_coordinate_system = wx.ComboBox(self, -1, choices = control_coordinate_choices, style=wx.CB_READONLY)\r\n \r\n self.lblinterpolate_initial_guess = wx.StaticText(self, -1, \"Interpolate initial guess?\")\r\n self.chkinterpolate_initial_guess = wx.CheckBox(self, -1)\r\n \r\n self.lblinitial_guess_num_timesteps = wx.StaticText(self, -1, \"Number of timesteps used to create initial guess\")\r\n self.txtinitial_guess_num_timesteps = wx.TextCtrl(self, -1, \"initial_guess_num_timesteps\")\r\n \r\n self.lblinitial_guess_step_size_distribution = wx.StaticText(self, -1, \"Initial guess step size distribution\")\r\n initialguessdistributionchoices = [\"Uniform\",\"Gaussian\",\"Cauchy\"]\r\n self.cmbinitial_guess_step_size_distribution = wx.ComboBox(self, -1, choices = initialguessdistributionchoices, style=wx.CB_READONLY)\r\n\r\n self.lblinitial_guess_step_size_stdv_or_scale = wx.StaticText(self, -1, \"Initial guess scale width/standard deviation\")\r\n self.txtinitial_guess_step_size_stdv_or_scale = wx.TextCtrl(self, -1, \"initial_guess_step_size_stdv_or_scale\")\r\n\r\n self.lblMBH_zero_control_initial_guess = wx.StaticText(self, -1, \"Zero-control initial guess\")\r\n MBH_zero_control_initial_guess_options = ['do not use','zero-control for resets, random perturbations for hops','always use zero-control guess except when seeded']\r\n self.cmbMBH_zero_control_initial_guess = wx.ComboBox(self, -1, choices = MBH_zero_control_initial_guess_options, style=wx.CB_READONLY)\r\n \r\n innerloopgrid.AddMany( [self.lblInnerLoopSolver, self.cmbInnerLoopSolver,\r\n self.lblNLP_solver_type, self.cmbNLP_solver_type,\r\n self.lblNLP_solver_mode, self.cmbNLP_solver_mode,\r\n self.lblquiet_NLP, self.chkquiet_NLP,\r\n self.lblquiet_MBH, self.chkquiet_MBH,\r\n self.lblMBH_two_step, self.chkMBH_two_step,\r\n self.lblFD_stepsize, self.txtFD_stepsize,\r\n self.lblFD_stepsize_coarse, self.txtFD_stepsize_coarse,\r\n self.lblACE_feasible_point_finder, self.chkACE_feasible_point_finder,\r\n self.lblMBH_max_not_improve, self.txtMBH_max_not_improve,\r\n self.lblMBH_max_trials, self.txtMBH_max_trials,\r\n self.lblMBH_max_run_time, self.txtMBH_max_run_time,\r\n self.lblMBH_hop_distribution, self.cmbMBH_hop_distribution,\r\n self.lblMBH_max_step_size, self.txtMBH_max_step_size,\r\n self.lblMBH_Pareto_alpha, self.txtMBH_Pareto_alpha,\r\n self.lblMBH_time_hop_probability, self.txtMBH_time_hop_probability,\r\n self.lblsnopt_feasibility_tolerance, self.txtsnopt_feasibility_tolerance,\r\n self.lblsnopt_major_iterations, self.txtsnopt_major_iterations,\r\n self.lblsnopt_max_run_time, self.txtsnopt_max_run_time,\r\n self.lblderivative_type, self.cmbderivative_type,\r\n self.lblcheck_derivatives, self.chkcheck_derivatives,\r\n self.lblseed_MBH, self.chkseed_MBH,\r\n self.lblinitial_guess_control_coordinate_system, self.cmbinitial_guess_control_coordinate_system,\r\n self.lblinterpolate_initial_guess, self.chkinterpolate_initial_guess,\r\n self.lblinitial_guess_num_timesteps, self.txtinitial_guess_num_timesteps,\r\n self.lblinitial_guess_step_size_distribution, self.cmbinitial_guess_step_size_distribution,\r\n self.lblinitial_guess_step_size_stdv_or_scale, self.txtinitial_guess_step_size_stdv_or_scale,\r\n self.lblMBH_zero_control_initial_guess, self.cmbMBH_zero_control_initial_guess])\r\n \r\n outerloopgrid = wx.GridSizer(12,2,0,0)\r\n \r\n self.lblrun_outerloop = wx.StaticText(self, -1, \"Outer-Loop Solver\")\r\n outerloop_choices = [\"None\",\"Genetic Algorithm\"]\r\n self.cmbrun_outerloop = wx.ComboBox(self, -1, choices=outerloop_choices, style = wx.CB_READONLY)\r\n \r\n self.lblouterloop_popsize = wx.StaticText(self, -1, \"Population size\")\r\n self.txtouterloop_popsize = wx.TextCtrl(self, -1, \"outerloop_popsize\")\r\n \r\n self.lblouterloop_genmax = wx.StaticText(self, -1, \"Maximum number of generations\")\r\n self.txtouterloop_genmax = wx.TextCtrl(self, -1, \"outerloop_genmax\")\r\n \r\n self.lblouterloop_tournamentsize = wx.StaticText(self, -1, \"Tournament size\")\r\n self.txtouterloop_tournamentsize = wx.TextCtrl(self, -1, \"outerloop_tournamentsize\")\r\n \r\n self.lblouterloop_CR = wx.StaticText(self, -1, \"Crossover ratio\")\r\n self.txtouterloop_CR = wx.TextCtrl(self, -1, \"outerloop_CR\")\r\n \r\n self.lblouterloop_mu = wx.StaticText(self, -1, \"Mutation rate\")\r\n self.txtouterloop_mu = wx.TextCtrl(self, -1, \"outerloop_mu\")\r\n \r\n self.lblouterloop_stallmax = wx.StaticText(self, -1, \"Maximum stall duration\")\r\n self.txtouterloop_stallmax = wx.TextCtrl(self, -1, \"outerloop_stallmax\")\r\n \r\n self.lblouterloop_tolfit = wx.StaticText(self, -1, \"Fitness tolerance\")\r\n self.txtouterloop_tolfit = wx.TextCtrl(self, -1, \"outerloop_tolfit\")\r\n \r\n self.lblouterloop_ntrials = wx.StaticText(self, -1, \"Number of trials\")\r\n self.txtouterloop_ntrials = wx.TextCtrl(self, -1, \"outerloop_ntrials\")\r\n \r\n self.lblouterloop_elitecount = wx.StaticText(self, -1, \"Number of elite individuals\")\r\n self.txtouterloop_elitecount = wx.TextCtrl(self, -1, \"outerloop_elitecount\")\r\n \r\n self.lblouterloop_useparallel = wx.StaticText(self, -1, \"Run outer-loop GA in parallel?\")\r\n self.chkouterloop_useparallel = wx.CheckBox(self, -1)\r\n \r\n self.lblouterloop_warmstart = wx.StaticText(self, -1, \"Warm-start the outer-loop?\")\r\n self.txtouterloop_warmstart = wx.TextCtrl(self, -1, \"outerloop_warmstart\")\r\n \r\n outerloopgrid.AddMany([self.lblrun_outerloop, self.cmbrun_outerloop,\r\n self.lblouterloop_popsize, self.txtouterloop_popsize,\r\n self.lblouterloop_genmax, self.txtouterloop_genmax,\r\n self.lblouterloop_tournamentsize, self.txtouterloop_tournamentsize,\r\n self.lblouterloop_CR, self.txtouterloop_CR,\r\n self.lblouterloop_mu, self.txtouterloop_mu,\r\n self.lblouterloop_stallmax, self.txtouterloop_stallmax,\r\n self.lblouterloop_tolfit, self.txtouterloop_tolfit,\r\n self.lblouterloop_ntrials, self.txtouterloop_ntrials,\r\n self.lblouterloop_elitecount, self.txtouterloop_elitecount,\r\n self.lblouterloop_warmstart, self.txtouterloop_warmstart])\r\n\r\n \r\n vboxleft = wx.BoxSizer(wx.VERTICAL)\r\n vboxright = wx.BoxSizer(wx.VERTICAL)\r\n lblLeftTitle = wx.StaticText(self, -1, \"Inner-Loop Solver Parameters\")\r\n lblRightTitle = wx.StaticText(self, -1, \"Outer-Loop Solver Parameters\")\r\n vboxleft.Add(lblLeftTitle)\r\n vboxleft.Add(innerloopgrid)\r\n vboxright.Add(lblRightTitle)\r\n vboxright.Add(outerloopgrid)\r\n \r\n font = self.GetFont()\r\n font.SetWeight(wx.FONTWEIGHT_BOLD)\r\n lblLeftTitle.SetFont(font)\r\n lblRightTitle.SetFont(font)\r\n\r\n \r\n hbox = wx.BoxSizer(wx.HORIZONTAL)\r\n \r\n hbox.Add(vboxleft)\r\n hbox.AddSpacer(20)\r\n hbox.Add(vboxright)\r\n \r\n \r\n self.lbltrialX = wx.StaticText(self, -1, \"Trial decision vector or initial guess\")\r\n self.txttrialX = wx.TextCtrl(self, -1, style=wx.TE_MULTILINE, size = (700,300))\r\n self.btntrialX = wx.Button(self, -1, \"...\")\r\n trialbox = wx.BoxSizer(wx.HORIZONTAL)\r\n trialbox.AddMany([self.lbltrialX, self.btntrialX])\r\n\r\n self.mainbox = wx.BoxSizer(wx.VERTICAL)\r\n self.mainbox.AddMany([hbox, trialbox, self.txttrialX])\r\n\r\n self.SetSizer(self.mainbox)\r\n self.SetupScrolling()\r\n\r\nclass PhysicsOptionsPanel(wx.lib.scrolledpanel.ScrolledPanel):\r\n def __init__(self, parent):\r\n \r\n wx.lib.scrolledpanel.ScrolledPanel.__init__(self, parent)\r\n\r\n ephemerisgrid = wx.GridSizer(4,2,5,5)\r\n perturbgrid = wx.GridSizer(4,2,5,5)\r\n \r\n self.lblephemeris_source = wx.StaticText(self, -1, \"Ephemeris Source\")\r\n ephemeris_source_typestypes = ['Static','SPICE']\r\n self.cmbephemeris_source = wx.ComboBox(self, -1, choices = ephemeris_source_typestypes, style=wx.CB_READONLY)\r\n\r\n self.lblSPICE_leap_seconds_kernel = wx.StaticText(self, -1, \"Leap seconds kernel\")\r\n self.txtSPICE_leap_seconds_kernel = wx.TextCtrl(self, -1, \"SPICE_leap_seconds_kernel\", size=(200,-1))\r\n\r\n self.lblSPICE_reference_frame_kernel = wx.StaticText(self, -1, \"Frame kernel\")\r\n self.txtSPICE_reference_frame_kernel = wx.TextCtrl(self, -1, \"SPICE_reference_frame_kernel\", size=(200,-1))\r\n\r\n self.lbluniverse_folder = wx.StaticText(self, -1, \"Universe folder\")\r\n self.txtuniverse_folder = wx.TextCtrl(self, -1, \"universe_folder\", size=(400,-1))\r\n self.btnGetNewUniverseFolder = wx.Button(self, -1, \"...\")\r\n self.btnSetDefaultUniverse = wx.Button(self, -1, \"Default\")\r\n UniverseButtonSizer = wx.BoxSizer(wx.HORIZONTAL)\r\n UniverseButtonSizer.AddMany([self.txtuniverse_folder, self.btnGetNewUniverseFolder, self.btnSetDefaultUniverse])\r\n\r\n self.lblperturb_SRP = wx.StaticText(self, -1, \"Enable SRP\")\r\n self.chkperturb_SRP = wx.CheckBox(self, -1)\r\n\r\n self.lblperturb_thirdbody = wx.StaticText(self, -1, \"Enable third body\")\r\n self.chkperturb_thirdbody = wx.CheckBox(self, -1)\r\n\r\n self.lblspacecraft_area = wx.StaticText(self, -1, \"Spacecraft area (in m^2)\")\r\n self.txtspacecraft_area = wx.TextCtrl(self, -1, \"spacecraft_area\")\r\n\r\n self.lblcoefficient_of_reflectivity = wx.StaticText(self, -1, \"Coefficient of reflectivity\")\r\n self.txtcoefficient_of_reflectivity = wx.TextCtrl(self, -1, \"coefficient_of_reflectivity\")\r\n\r\n ephemerisgrid.AddMany([self.lblephemeris_source, self.cmbephemeris_source,\r\n self.lblSPICE_leap_seconds_kernel, self.txtSPICE_leap_seconds_kernel,\r\n self.lblSPICE_reference_frame_kernel, self.txtSPICE_reference_frame_kernel,\r\n self.lbluniverse_folder, UniverseButtonSizer])\r\n perturbgrid.AddMany([ self.lblperturb_SRP, self.chkperturb_SRP,\r\n self.lblperturb_thirdbody, self.chkperturb_thirdbody,\r\n self.lblspacecraft_area, self.txtspacecraft_area,\r\n self.lblcoefficient_of_reflectivity, self.txtcoefficient_of_reflectivity])\r\n\r\n\r\n\r\n\r\n lblLeftTitle = wx.StaticText(self, -1, \"Ephemeris settings\")\r\n vboxleft = wx.BoxSizer(wx.VERTICAL)\r\n vboxleft.AddMany([lblLeftTitle, ephemerisgrid])\r\n\r\n lblRightTitle = wx.StaticText(self, -1, \"Perturbation settings\")\r\n vboxright = wx.BoxSizer(wx.VERTICAL)\r\n vboxright.AddMany([lblRightTitle, perturbgrid])\r\n\r\n font = self.GetFont()\r\n font.SetWeight(wx.FONTWEIGHT_BOLD)\r\n lblLeftTitle.SetFont(font)\r\n lblRightTitle.SetFont(font)\r\n\r\n self.mainbox = wx.BoxSizer(wx.HORIZONTAL)\r\n \r\n self.mainbox.Add(vboxleft)\r\n self.mainbox.AddSpacer(20)\r\n self.mainbox.Add(vboxright)\r\n\r\n\r\n spiralgrid = wx.GridSizer(2,2,5,5)\r\n self.lblspiral_model_type = wx.StaticText(self, -1, \"Spiral model type\")\r\n spiral_model_choices = ['Battin','Edelbaum']\r\n self.cmbspiral_model_type = wx.ComboBox(self, -1, choices = spiral_model_choices, style = wx.CB_READONLY)\r\n spiralgrid.AddMany([self.lblspiral_model_type, self.cmbspiral_model_type])\r\n lblBottomTitle = wx.StaticText(self, -1, \"Spiral settings\")\r\n lblBottomTitle.SetFont(font)\r\n vboxspiral = wx.BoxSizer(wx.VERTICAL)\r\n vboxspiral.AddMany([lblBottomTitle, spiralgrid])\r\n\r\n lambertgrid = wx.GridSizer(2,2,5,5)\r\n self.lbllambert_type = wx.StaticText(self, -1, \"Lambert solver type\")\r\n lambert_choices = ['Arora-Russell','Izzo (not included in open-source)']\r\n self.cmblambert_type = wx.ComboBox(self, -1, choices = lambert_choices, style = wx.CB_READONLY)\r\n lambertgrid.AddMany([self.lbllambert_type, self.cmblambert_type])\r\n lblLambertTitle = wx.StaticText(self, -1, \"Lambert settings\")\r\n lblLambertTitle.SetFont(font)\r\n vboxlambert = wx.BoxSizer(wx.VERTICAL)\r\n vboxlambert.AddMany([lblLambertTitle, lambertgrid])\r\n\r\n self.mainvbox = wx.BoxSizer(wx.VERTICAL)\r\n self.mainvbox.Add(self.mainbox)\r\n self.mainvbox.AddSpacer(20)\r\n self.mainvbox.AddMany([vboxspiral, vboxlambert])\r\n\r\n self.SetSizer(self.mainvbox)\r\n self.SetupScrolling()\r\n\r\nclass OutputOptionsPanel(wx.lib.scrolledpanel.ScrolledPanel):\r\n def __init__(self, parent):\r\n \r\n wx.lib.scrolledpanel.ScrolledPanel.__init__(self, parent)\r\n\r\n self.mainbox = wx.FlexGridSizer(20,2,5,5)\r\n\r\n self.lblcreate_GMAT_script = wx.StaticText(self, -1, \"Create GMAT scripts\")\r\n self.chkcreate_GMAT_script = wx.CheckBox(self, -1)\r\n\r\n self.lbloutput_units = wx.StaticText(self, -1, \"Output units\")\r\n outputchoices = ['km and km/s','LU and LU/day']\r\n self.cmboutput_units = wx.ComboBox(self, -1, choices=outputchoices, style=wx.CB_READONLY)\r\n \r\n self.lbloutput_dormant_journeys = wx.StaticText(self, -1, \"Output journey entries for wait times at intermediate and final target?\")\r\n self.chkoutput_dormant_journeys = wx.CheckBox(self, -1)\r\n\r\n self.lblpost_mission_wait_time = wx.StaticText(self, -1, \"Stay time at the final target\")\r\n self.txtpost_mission_wait_time = wx.TextCtrl(self, -1, \"post_mission_wait_time\")\r\n\r\n self.lblgenerate_initial_guess_file = wx.StaticText(self, -1, \"Generate initial guess file? (experimental!)\")\r\n self.chkgenerate_initial_guess_file = wx.CheckBox(self, -1)\r\n\r\n self.lblmission_type_for_initial_guess_file = wx.StaticText(self, -1, \"Mission type for initial guess file\")\r\n initial_guess_file_choices = [\"MGA\",\"MGADSM\",\"MGALT\",\"FBLT\",\"MGANDSM\",\"PSBI\"]\r\n self.cmbmission_type_for_initial_guess_file = wx.ComboBox(self, -1, choices=initial_guess_file_choices, style=wx.CB_READONLY)\r\n\r\n self.lbloverride_working_directory = wx.StaticText(self, -1, \"Override working directory?\")\r\n self.chkoverride_working_directory = wx.CheckBox(self, -1)\r\n\r\n self.lblforced_working_directory = wx.StaticText(self, -1, \"Working directory\")\r\n self.txtforced_working_directory = wx.TextCtrl(self, -1, \"forced_working_directory\", size=(600,-1))\r\n self.btnforced_working_directory = wx.Button(self, -1, \"...\")\r\n working_directory_sizer = wx.BoxSizer(wx.HORIZONTAL)\r\n working_directory_sizer.AddMany([self.txtforced_working_directory, self.btnforced_working_directory])\r\n\r\n self.lblgenerate_forward_integrated_ephemeris = wx.StaticText(self, -1, \"Generate forward-integrated STK-compatible ephemeris\")\r\n self.chkgenerate_forward_integrated_ephemeris = wx.CheckBox(self, -1)\r\n\r\n self.lblbackground_mode = wx.StaticText(self, -1, \"Enable background mode?\")\r\n self.chkbackground_mode = wx.CheckBox(self, -1)\r\n\r\n self.mainbox.AddMany([ self.lbloutput_dormant_journeys, self.chkoutput_dormant_journeys,\r\n self.lblpost_mission_wait_time, self.txtpost_mission_wait_time,\r\n self.lblcreate_GMAT_script, self.chkcreate_GMAT_script,\r\n self.lbloutput_units, self.cmboutput_units,\r\n self.lblgenerate_initial_guess_file, self.chkgenerate_initial_guess_file,\r\n self.lblmission_type_for_initial_guess_file, self.cmbmission_type_for_initial_guess_file,\r\n self.lbloverride_working_directory, self.chkoverride_working_directory,\r\n self.lblforced_working_directory, working_directory_sizer,\r\n self.lblgenerate_forward_integrated_ephemeris, self.chkgenerate_forward_integrated_ephemeris,\r\n self.lblbackground_mode, self.chkbackground_mode])\r\n\r\n self.SetSizer(self.mainbox)\r\n self.SetupScrolling()\r\n\r\n \r\nclass OptionsBook(wx.Notebook):\r\n #class for Options notebook\r\n def __init__(self, parent):\r\n wx.Notebook.__init__(self, parent=parent, id=wx.ID_ANY, style=\r\n wx.BK_DEFAULT\r\n #wx.BK_TOP \r\n #wx.BK_BOTTOM\r\n #wx.BK_LEFT\r\n #wx.BK_RIGHT\r\n )\r\n \r\n font = self.GetFont()\r\n font.SetPointSize(10)\r\n self.SetFont(font)\r\n\r\n\r\n #create tabs\r\n self.tabGlobal = GlobalOptionsPanel(self)\r\n self.AddPage(self.tabGlobal, \"Global Mission Options\")\r\n self.tabSpacecraft = SpacecraftOptionsPanel(self)\r\n self.AddPage(self.tabSpacecraft, \"Spacecraft Options\")\r\n self.tabJourney = JourneyOptionsPanel(self)\r\n self.AddPage(self.tabJourney, \"Journey Options\")\r\n self.tabSolver = SolverOptionsPanel(self)\r\n self.AddPage(self.tabSolver, \"Solver Options\")\r\n self.tabPhysics = PhysicsOptionsPanel(self)\r\n self.AddPage(self.tabPhysics, \"Physics Options\")\r\n self.tabOutput = OutputOptionsPanel(self)\r\n self.AddPage(self.tabOutput, \"Output Options\")","sub_path":"branch/EMTG_student/PyEMTG/OptionsNotebook.py","file_name":"OptionsNotebook.py","file_ext":"py","file_size_in_byte":74018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"431063408","text":"#!/usr/bin/env python3\n# encoding: utf-8\n\nimport argparse, sys, os\nfrom glob import glob\n\n\nclass TruncateCSV(object):\n def __init__(self, args):\n self.args = args\n self.config()\n\n def config(self):\n \"\"\"configure options\"\"\"\n if self.args.cd != None:\n self.chdir()\n\n if self.args.files != None:\n self.csvs = self.args.files\n else:\n self.csvs = glob(self.args.glob)\n\n if self.args.ext[0] != \".\":\n self.args.ext = (\".\" + self.args.ext)\n\n def chdir(self):\n \"\"\"allows user to fix bad directory input\"\"\"\n try:\n os.chdir(self.args.cd)\n\n except: # bad path\n err = \"Could not change to directory {}\".format(self.args.cd)\n self.check_input(err, \"directory\", \"os.path.isdir('{}')\",\n \"os.chdir('{}')\")\n\n def check_input(self, err_msg, checking, exit_condition, hook=None):\n \"\"\"asks user for input and returns answer if it meets a condition\"\"\"\n print(err_msg)\n while True:\n print()\n prompt = \"Reenter {}; ('e' to exit): \".format(checking)\n response = input(prompt)\n if response.lower() == \"e\":\n print(\"Exiting...\")\n sys.exit()\n else:\n try:\n command = exit_condition.format(response)\n path_status = eval(command)\n\n if path_status:\n if hook != None:\n hook = hook.format(response)\n exec(hook)\n break\n except:\n print(\"Try again.\")\n return response\n\n\n def handle_file(self, csv):\n \"\"\"truncates file creates backup based on arguments\"\"\"\n lines = self.csvread(csv)\n if not self.args.overwrite:\n backup = csv + self.args.ext\n self.csvwrite(backup, lines)\n\n else:\n self.csvwrite(csv, lines)\n\n def csvread(self, csv):\n \"\"\"opens a csv file and returns lines greater than a certain index\"\"\"\n with open(csv, 'r', encoding='utf-8', errors='replace') as to_trunc:\n lines = to_trunc.readlines()\n return lines[self.args.num:]\n\n def csvwrite(self, csv, lines):\n \"\"\"writes to file with list of lines provided\"\"\"\n with open(csv, 'w', encoding='utf-8') as to_write:\n to_write.writelines(lines)\n\n def fix_file(self, fnf):\n \"\"\"allows user to correct a bad file input\"\"\"\n err = \"File {} not found in {}\".format(fnf, os.getcwd())\n new_file = self.check_input(err, \"filename\", \"os.path.isfile('{}')\")\n return new_file\n\n\ndef parser():\n if len(sys.argv[1:]) == 0:\n sys.argv.append(\"-h\")\n\n parser = argparse.ArgumentParser(\n description=\"Remove unneeded headers from data files\",\n usage=\"num [-hvd DIR] [-o | -e EXT] [(-f FILE)... | -g GLOB]\",\n epilog=\"\"\"NOTE: glob patterns should be put in quotes; filenames\n listed with the -f flag should not be relative paths if the -d flag\n is also enabled.\"\"\")\n\n# if you want script to exit if number not provided (no default value)\n parser.add_argument(\"num\",\n type=int,\n help='the number of lines to be truncated')\n\n# if you want a default value for num as pos. arg\n # parser.add_argument(\"num\",\n # nargs='?',\n # default=1,\n # type=int,\n # help='the number of lines to be truncated')\n\n parser.add_argument(\"-d\",\"--dir\",\n metavar=\"DIR\",\n dest=\"cd\",\n help=\"the target directory to truncate all CSVs in\")\n\n files_grp = parser.add_mutually_exclusive_group()\n files_grp.add_argument(\"-f\",\"--file\",\n metavar=\"FILE\",\n dest=\"files\",\n action=\"append\",\n help=\"files to truncate\")\n files_grp.add_argument(\"-g\",\"--glob\",\n default=\"*.csv\",\n help=\"glob pattern to match files [default: %(default)s]\")\n\n backup_grp = parser.add_mutually_exclusive_group()\n backup_grp.add_argument(\"-o\",\"--overwrite\",\n action=\"store_true\",\n help=\"overwrite files without making backups\")\n backup_grp.add_argument(\"-e\",\"--ext\",\n default=\".trc\",\n help=\"backup extension [default: %(default)s]\")\n\n parser.add_argument(\"-v\",\"--version\",\n action=\"version\",\n version=\"%(prog)s 2.0.1 (test)\")\n\n args = parser.parse_args()\n return args\n\n\n\ndef main():\n args = parser()\n to_trunc = TruncateCSV(args)\n\n if len(to_trunc.csvs) > 0:\n for csv in to_trunc.csvs:\n\n try:\n to_trunc.handle_file(csv)\n\n except FileNotFoundError:\n new_file = to_trunc.fix_file(csv)\n to_trunc.handle_file(new_file)\n\n else:\n no_files = \"No files were found matching pattern {} in {}\"\n print(no_files.format(to_trunc.args.glob, os.getcwd()))\n\n\nif __name__ == \"__main__\":\n main()\n\n# TODO:\n","sub_path":"python/trunchead_csv.py","file_name":"trunchead_csv.py","file_ext":"py","file_size_in_byte":5109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"557242707","text":"\"\"\"\nReads every line from the CSV and import it into the DB\nThe CSV file has been cleaned as to keep this script as simple as possible.\n\"\"\"\n\nimport csv\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom sqlalchemy.engine.url import URL\nimport settings\n\nengine = create_engine(URL(**settings.DATABASE))\ndb = scoped_session(sessionmaker(bind=engine))\n\n\ndef main():\n file = open(\"books.csv\")\n reader = csv.reader(file)\n for isbn, title, author, year in reader:\n db.execute(\"INSERT INTO books\"\n \"(isbn, title, author, year)\"\n \"VALUES (:isbn, :title, :author, :year)\",\n {\"isbn\": isbn, \"title\": title, \"author\": author, \"year\": year})\n\n print(f\"added {title} by {author} to the database\")\n db.commit()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"import_books.py","file_name":"import_books.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"142294588","text":"from __future__ import unicode_literals\nimport re\nfrom past.builtins import cmp\nimport functools\nimport frappe, erpnext\nfrom erpnext.accounts.report.utils import get_currency, convert_to_presentation_currency\nfrom erpnext.accounts.utils import get_fiscal_year\nfrom frappe import _\nfrom six import itervalues\nfrom frappe.utils import (flt, getdate, get_first_day, add_months, add_days, formatdate, cstr, cint)\nfrom erpnext.accounts.doctype.accounting_dimension.accounting_dimension import get_accounting_dimensions, get_dimension_with_children\n\n\ndef get_budget_data(\n\t\tcompany, root_type, period_list, filters=None,\n\t\taccumulated_values=1, only_current_fiscal_year=True, ignore_closing_entries=False,\n\t\tignore_accumulated_values_for_fy=False , total = True):\n\n\taccounts = get_budget_accounts(company, root_type)\n\tif not accounts:\n\t\treturn None\n\n\taccounts, accounts_by_name, parent_children_map = filter_budget_accounts(accounts)\n\n\tcompany_currency = get_appropriate_currency(company, filters)\n\n\tbudget_distribution_by_account = {}\n\tfor root in frappe.db.sql(\"\"\"select lft, rgt from tabAccount\n\t\t\twhere root_type=%s and ifnull(parent_account, '') = ''\"\"\", root_type, as_dict=1):\n\n\t\tset_budget_distribution_by_account(\n\t\t\tcompany,\n\t\t\tperiod_list[0][\"year_start_date\"] if only_current_fiscal_year else None,\n\t\t\tperiod_list[-1][\"to_date\"],\n\t\t\troot.lft, root.rgt, filters,\n\t\t\tbudget_distribution_by_account, ignore_closing_entries=ignore_closing_entries\n\t\t)\n\tcalculate_values(\n\t\taccounts_by_name, budget_distribution_by_account, period_list, accumulated_values, ignore_accumulated_values_for_fy)\n\taccumulate_values_into_parents(accounts, accounts_by_name, period_list, accumulated_values)\n\tout = prepare_data(accounts, period_list, company_currency)\n\tout = filter_out_zero_value_rows(out, parent_children_map)\n\n\tif out and total:\n\t\tadd_total_row(out, root_type, period_list, company_currency)\n\n\treturn out\n\ndef get_appropriate_currency(company, filters=None):\n\tif filters and filters.get(\"presentation_currency\"):\n\t\treturn filters[\"presentation_currency\"]\n\telse:\n\t\treturn frappe.get_cached_value('Company', company, \"default_currency\")\n\ndef get_budget_accounts(company, root_type):\n\treturn frappe.db.sql(\"\"\"\n\t\tselect name, account_number, parent_account, lft, rgt, root_type, report_type, account_name, include_in_gross, account_type, is_group, lft, rgt\n\t\tfrom `tabAccount`\n\t\twhere company=%s and root_type=%s order by lft\"\"\", (company, root_type), as_dict=True)\n\ndef set_budget_distribution_by_account(\n\t\tcompany, from_date, to_date, root_lft, root_rgt, filters, budget_distribution_by_account, ignore_closing_entries=False):\n\t\"\"\"Returns a dict like { \"account\": [gl entries], ... }\"\"\"\n\tadditional_conditions = get_additional_conditions(from_date, ignore_closing_entries, filters)\n\n\taccounts = frappe.db.sql_list(\"\"\"select name from `tabAccount`\n\t\twhere lft >= %s and rgt <= %s and company = %s\"\"\", (root_lft, root_rgt, company))\n\n\tif accounts:\n\t\tadditional_conditions += \" and ba.account in ({})\"\\\n\t\t\t.format(\", \".join([frappe.db.escape(d) for d in accounts]))\n\n\t\tgl_filters = {\n\t\t\t\"company\": company,\n\t\t\t\"from_date\": from_date,\n\t\t\t\"to_date\": to_date,\n\t\t\t\"finance_book\": cstr(filters.get(\"finance_book\"))\n\t\t}\n\n\t\tfor key, value in filters.items():\n\t\t\tif value:\n\t\t\t\tgl_filters.update({\n\t\t\t\t\tkey: value\n\t\t\t\t})\n\n\t\tbudget_entries = frappe.db.sql(\"\"\"\n\t\t\tselect \n\t\t\t\tfa.year_start_date, \n\t\t\t\tb.budget_against, \n\t\t\t\tb.cost_center, \n\t\t\t\tb.project,\n\t\t\t\tb.payroll_entry, \n\t\t\t\tb.fiscal_year, \n\t\t\t\tba.account, \n\t\t\t\tba.budget_amount, \n\t\t\t\tb.monthly_distribution\n\t\t\tfrom \n\t\t\t\t`tabBudget` b, \n\t\t\t\t`tabBudget Account` ba, \n\t\t\t\t`tabFiscal Year` fa \n\t\t\twhere\n\t\t\t\tb.name = ba.parent \n\t\t\t\tand b.docstatus = 1\t\t\t\t\n\t\t\t\tand b.fiscal_year = fa.name \n\t\t\t\tand b.company=%(company)s {additional_conditions} \n\t\t\t\tand fa.year_start_date >= %(from_date)s \n\t\t\t\tand fa.year_end_date <= %(to_date)s \n\t\t\torder by ba.account\"\"\".format(additional_conditions=additional_conditions), gl_filters, as_dict=True)\n\n\n\t\tfor budget in budget_entries:\n\t\t\tif budget['monthly_distribution']:\n\t\t\t\t#print(\"dddd\")\n\t\t\t\tget_distribution_budget_by_percentage(budget['account'], budget['fiscal_year'], budget['monthly_distribution'], budget['budget_amount'],budget_distribution_by_account)\n\t\t\t#else:\n\t\t\t\t#print(\"asdf\")\n\t\t\t\t#get_distribution_budget(budget['account'], budget['fiscal_year'], budget['budget_amount'],budget_distribution_by_account)\n\n\t\treturn budget_distribution_by_account\n\ndef get_distribution_budget_by_percentage(account, fiscal_year, monthly_distribution, budget_amount, budget_distribution_by_account):\n\tmdps = frappe.db.sql(\"\"\"\n\t\tSELECT\n\t\t\tIF ( YEAR(fy.year_start_date ) = YEAR(fy.year_end_date),\n\t\t\t\t\tDATE(CONCAT_WS('-', md.fiscal_year, month(str_to_date(LEFT(mdp.month,3),'%%b')), 1))\n \t\t, IF( MONTH(fy.year_start_date ) > month(str_to_date(LEFT(mdp.month,3),'%%b')),\n \t\t\tDATE(CONCAT_WS('-', YEAR(fy.year_end_date ), month(str_to_date(LEFT(mdp.month,3),'%%b')), 1)),\n \t\t\tDATE(CONCAT_WS('-', YEAR(fy.year_start_date), month(str_to_date(LEFT(mdp.month,3),'%%b')), 1))\n \t\t)\n \t) AS posting_date,\n\t\t\tmd.fiscal_year, \t\t\n\t\t\tmdp.percentage_allocation,\n\t\t\t'' AS account,\n\t\t\t'' AS total_budget_amount\n\t\tFROM \n\t\t\t`tabMonthly Distribution` md,\n\t\t\t`tabMonthly Distribution Percentage` mdp,\n \t\t`tabFiscal Year` fy\n\t\tWHERE\n\t\t\tmd.name = mdp.parent\n \t\tand md.fiscal_year = fy.name\n \t\tand md.fiscal_year = %(fiscal_year)s\n \t\tand md.name = %(monthly_distribution)s \"\"\",{ \"fiscal_year\": fiscal_year, \"monthly_distribution\": monthly_distribution},as_dict=True)\n\t\n\tfor v in mdps:\n\t\tv['account'] = account\n\t\tv['total_budget_amount'] = (budget_amount*v['percentage_allocation'])/100\n\t\tbudget_distribution_by_account.setdefault(account, []).append(v)\n\t#print(budget_distribution_by_account)\n\treturn budget_distribution_by_account\n\t\ndef get_distribution_budget(account, fiscal_year, budget_amount, budget_distribution_by_account):\n\tfiscal_year_start_date = frappe.db.get_value(\"Fiscal Year\", fiscal_year, \"year_start_date\")\n\tv={\n\t\t\"posting_date\": '',\n\t\t\"account\": account,\n\t\t\"fiscal_year\": fiscal_year,\n\t\t\"total_budget_amount\":''\n\t}\n\n\tfor x in range(12):\t\t\n\t\tv[\"posting_date\"] = add_months(fiscal_year_start_date, x)\n\t\tv[\"account\"] = account\n\t\tv[\"total_budget_amount\"] = (8.333 * budget_amount) / 100 \n\t\tbudget_distribution_by_account.setdefault(account, []).append(v)\n\t#print(budget_distribution_by_account)\n\treturn budget_distribution_by_account\n\t\ndef calculate_values(\n\t\taccounts_by_name, gl_entries_by_account, period_list, accumulated_values, ignore_accumulated_values_for_fy):\n\tfor entries in itervalues(gl_entries_by_account):\n\t\tfor entry in entries:\n\t\t\td = accounts_by_name.get(entry.account)\n\t\t\tif not d:\n\t\t\t\tfrappe.msgprint(\n\t\t\t\t\t_(\"Could not retrieve information for {0}.\".format(entry.account)), title=\"Error\",\n\t\t\t\t\traise_exception=1\n\t\t\t\t)\n\t\t\tfor period in period_list:\n\t\t\t\t# check if posting date is within the period\n\n\t\t\t\tif entry.posting_date <= period.to_date:\n\t\t\t\t\tif (accumulated_values or entry.posting_date >= period.from_date) and \\\n\t\t\t\t\t\t(not ignore_accumulated_values_for_fy or\n\t\t\t\t\t\t\tentry.fiscal_year == period.to_date_fiscal_year):\n\t\t\t\t\t\td[period.key] = d.get(period.key, 0.0) + flt(entry.total_budget_amount)\n\n\t\t\t#if entry.posting_date < period_list[0].year_start_date:\n\t\t\t#\td[\"opening_balance\"] = d.get(\"opening_balance\", 0.0) + flt(entry.debit) - flt(entry.credit)\n\ndef filter_budget_accounts(accounts, depth=20):\n\tparent_children_map = {}\n\taccounts_by_name = {}\n\tfor d in accounts:\n\t\taccounts_by_name[d.name] = d\n\t\tparent_children_map.setdefault(d.parent_account or None, []).append(d)\n\n\tfiltered_accounts = []\n\n\tdef add_to_list(parent, level):\n\t\tif level < depth:\n\t\t\tchildren = parent_children_map.get(parent) or []\n\t\t\tsort_accounts(children, is_root=True if parent==None else False)\n\n\t\t\tfor child in children:\n\t\t\t\tchild.indent = level\n\t\t\t\tfiltered_accounts.append(child)\n\t\t\t\tadd_to_list(child.name, level + 1)\n\n\tadd_to_list(None, 0)\n\n\treturn filtered_accounts, accounts_by_name, parent_children_map\n\ndef sort_accounts(accounts, is_root=False, key=\"name\"):\n\t\"\"\"Sort root types as Asset, Liability, Equity, Income, Expense\"\"\"\n\n\tdef compare_accounts(a, b):\n\t\tif re.split('\\W+', a[key])[0].isdigit():\n\t\t\t# if chart of accounts is numbered, then sort by number\n\t\t\treturn cmp(a[key], b[key])\n\t\telif is_root:\n\t\t\tif a.report_type != b.report_type and a.report_type == \"Balance Sheet\":\n\t\t\t\treturn -1\n\t\t\tif a.root_type != b.root_type and a.root_type == \"Asset\":\n\t\t\t\treturn -1\n\t\t\tif a.root_type == \"Liability\" and b.root_type == \"Equity\":\n\t\t\t\treturn -1\n\t\t\tif a.root_type == \"Income\" and b.root_type == \"Expense\":\n\t\t\t\treturn -1\n\t\telse:\n\t\t\t# sort by key (number) or name\n\t\t\treturn cmp(a[key], b[key])\n\t\treturn 1\n\n\taccounts.sort(key = functools.cmp_to_key(compare_accounts))\n\ndef get_additional_conditions(from_date, ignore_closing_entries, filters):\n\tadditional_conditions = []\n\n\taccounting_dimensions = get_accounting_dimensions(as_list=False)\n\n\tif filters:\n\t\tif filters.get(\"project\"):\n\t\t\tif not isinstance(filters.get(\"project\"), list):\n\t\t\t\tfilters.project = frappe.parse_json(filters.get(\"project\"))\n\n\t\t\tadditional_conditions.append(\"b.project in %(project)s\")\n\n\t\tif filters.get(\"cost_center\"):\n\t\t\tfilters.cost_center = get_cost_centers_with_children(filters.cost_center)\n\t\t\tadditional_conditions.append(\"b.cost_center in %(cost_center)s\")\n\n\tif accounting_dimensions:\n\t\tfor dimension in accounting_dimensions:\n\t\t\tif filters.get(dimension.fieldname):\n\t\t\t\tif frappe.get_cached_value('DocType', dimension.document_type, 'is_tree'):\n\t\t\t\t\tfilters[dimension.fieldname] = get_dimension_with_children(dimension.document_type,\n\t\t\t\t\t\tfilters.get(dimension.fieldname))\n\t\t\t\t\tadditional_conditions.append(\"{0} in %({0})s\".format(dimension.fieldname))\n\t\t\t\telse:\n\t\t\t\t\tadditional_conditions.append(\"{0} in (%({0})s)\".format(dimension.fieldname))\n\n\treturn \" and {}\".format(\" and \".join(additional_conditions)) if additional_conditions else \"\"\n\ndef accumulate_values_into_parents(accounts, accounts_by_name, period_list, accumulated_values):\n\t\"\"\"accumulate children's values in parent accounts\"\"\"\n\tfor d in reversed(accounts):\n\t\tif d.parent_account:\n\t\t\tfor period in period_list:\n\t\t\t\taccounts_by_name[d.parent_account][period.key] = \\\n\t\t\t\t\taccounts_by_name[d.parent_account].get(period.key, 0.0) + d.get(period.key, 0.0)\n\ndef prepare_data(accounts, period_list, company_currency):\n\tdata = []\n\tyear_start_date = period_list[0][\"year_start_date\"].strftime(\"%Y-%m-%d\")\n\tyear_end_date = period_list[-1][\"year_end_date\"].strftime(\"%Y-%m-%d\")\n\n\tfor d in accounts:\n\t\t# add to output\n\t\thas_value = False\n\t\ttotal = 0\n\t\trow = frappe._dict({\n\t\t\t\"account\": _(d.name),\n\t\t\t\"parent_account\": _(d.parent_account) if d.parent_account else '',\n\t\t\t\"indent\": flt(d.indent),\n\t\t\t\"year_start_date\": year_start_date,\n\t\t\t\"year_end_date\": year_end_date,\n\t\t\t\"currency\": company_currency,\n\t\t\t\"include_in_gross\": d.include_in_gross,\n\t\t\t\"account_type\": d.account_type,\n\t\t\t\"is_group\": d.is_group,\t\t\t\n\t\t\t\"account_name\": ('%s - %s' %(_(d.account_number), _(d.account_name))\n\t\t\t\tif d.account_number else _(d.account_name))\n\t\t})\n\t\tfor period in period_list:\n\t\t\trow[period.key] = flt(d.get(period.key, 0.0), 3)\n\n\t\t\tif abs(row[period.key]) >= 0.005:\n\t\t\t\t# ignore zero values\n\t\t\t\thas_value = True\n\t\t\t\ttotal += flt(row[period.key])\n\n\t\trow[\"has_value\"] = has_value\n\t\trow[\"total\"] = total\n\t\tdata.append(row)\n\n\treturn data\n\ndef filter_out_zero_value_rows(data, parent_children_map, show_zero_values=False):\n\tdata_with_value = []\n\tfor d in data:\n\t\tif show_zero_values or d.get(\"has_value\"):\n\t\t\tdata_with_value.append(d)\n\t\telse:\n\t\t\t# show group with zero balance, if there are balances against child\n\t\t\tchildren = [child.name for child in parent_children_map.get(d.get(\"account\")) or []]\n\t\t\tif children:\n\t\t\t\tfor row in data:\n\t\t\t\t\tif row.get(\"account\") in children and row.get(\"has_value\"):\n\t\t\t\t\t\tdata_with_value.append(d)\n\t\t\t\t\t\tbreak\n\n\treturn data_with_value\n\ndef add_total_row(out, root_type, period_list, company_currency):\n\ttotal_row = {\n\t\t\"account_name\": _(\"Total {0})\").format(_(root_type)),\n\t\t\"account\": _(\"Total {0} )\").format(_(root_type)),\n\t\t\"currency\": company_currency\n\t}\n\n\tfor row in out:\n\t\tif not row.get(\"parent_account\"):\n\t\t\tfor period in period_list:\n\t\t\t\ttotal_row.setdefault(period.key, 0.0)\n\t\t\t\ttotal_row[period.key] += row.get(period.key, 0.0)\n\t\t\t\trow[period.key] = row.get(period.key, 0.0)\n\n\t\t\ttotal_row.setdefault(\"total\", 0.0)\n\t\t\ttotal_row[\"total\"] += flt(row[\"total\"])\n\t\t\trow[\"total\"] = \"\"\n\n\tif \"total\" in total_row:\n\t\tout.append(total_row)\n\n\t\t# blank row after Total\n\t\tout.append({})\n\ndef get_cost_centers_with_children(cost_centers):\n\tif not isinstance(cost_centers, list):\n\t\tcost_centers = [d.strip() for d in cost_centers.strip().split(',') if d]\n\n\tall_cost_centers = []\n\tfor d in cost_centers:\n\t\tif frappe.db.exists(\"Cost Center\", d):\n\t\t\tlft, rgt = frappe.db.get_value(\"Cost Center\", d, [\"lft\", \"rgt\"])\n\t\t\tchildren = frappe.get_all(\"Cost Center\", filters={\"lft\": [\">=\", lft], \"rgt\": [\"<=\", rgt]})\n\t\t\tall_cost_centers += [c.name for c in children]\n\t\telse:\n\t\t\tfrappe.throw(_(\"Cost Center: {0} does not exist\".format(d)))\n\n\treturn list(set(all_cost_centers))\n","sub_path":"tailpos_sync/tailpos_sync/report/budget_statement_helper.py","file_name":"budget_statement_helper.py","file_ext":"py","file_size_in_byte":13150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"475823310","text":"from math import cos, sin, radians\n\ndef crusoe(n, d, ang, dist_mult, ang_mult):\n x, y, a = 0, 0, radians(ang)\n for i in range(n):\n x += d * cos(a)\n y += d * sin(a)\n d *= dist_mult\n a *= ang_mult\n return x, y","sub_path":"crusoe.py","file_name":"crusoe.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"508187171","text":"\"\"\"\n@author:Liushihao\n@time:2020/5/16:15:23\n@email:Liushihao_1224@163.com\n@describe: 编写一个程序,使用正则表达式校验输入的车牌号是否正确。\n\"\"\"\nimport re\ncar_at = re.compile('^(([\\u4e00-\\u9fa5]{1}[A-Z]{1})[-]?|([wW][Jj][\\u4e00-\\u9fa5]{1}[-]?)|([a-zA-Z]{2}))[A-Za-z0-9]{5}$')\nwhile True:\n car_num = input(\"请输入车牌号: \")\n result = re.search(car_at, car_num)\n if result:\n print(\"车牌号正确\")\n else:\n print(\"车牌号不正确\")","sub_path":"chapter8/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"203127002","text":"# From https://github.com/google-research/planet/blob/0c6f7d3c56fe691da5b0a2fc62db3cb7075cfcf4/planet/control/wrappers.py#L427\n\nimport datetime\nimport io\nimport os\nimport uuid\n\nimport numpy as np\nimport tensorflow as tf\n\nclass CollectGymDataset(object):\n \"\"\"Collect transition tuples and store episodes as Numpy files.\"\"\"\n\n def __init__(self, env, outdir):\n self._env = env\n self._outdir = outdir and os.path.expanduser(outdir)\n self._episode = None\n self._transition = None\n\n def __getattr__(self, name):\n return getattr(self._env, name)\n\n def step(self, action, *args, **kwargs):\n if kwargs.get('blocking', True):\n transition = self._env.step(action, *args, **kwargs)\n return self._process_step(action, *transition)\n else:\n future = self._env.step(action, *args, **kwargs)\n return lambda: self._process_step(action, *future())\n\n def reset(self, *args, **kwargs):\n if kwargs.get('blocking', True):\n observ = self._env.reset(*args, **kwargs)\n return self._process_reset(observ)\n else:\n future = self._env.reset(*args, **kwargs)\n return lambda: self._process_reset(future())\n\n def _process_step(self, action, observ, reward, done, info):\n self._transition.update({'action': action, 'reward': reward})\n self._transition.update(info)\n self._episode.append(self._transition)\n self._transition = {}\n if not done:\n self._transition.update(self._process_observ(observ))\n else:\n episode = self._get_episode()\n info['episode'] = episode\n if self._outdir:\n filename = self._get_filename()\n self._write(episode, filename)\n return observ, reward, done, info\n\n def _process_reset(self, observ):\n self._episode = []\n self._transition = {}\n self._transition.update(self._process_observ(observ))\n return observ\n\n def _process_observ(self, observ):\n if not isinstance(observ, dict):\n observ = {'observ': observ}\n return observ\n\n def _get_filename(self):\n timestamp = datetime.datetime.now().strftime('%Y%m%dT%H%M%S')\n identifier = str(uuid.uuid4()).replace('-', '')\n filename = '{}-{}.npz'.format(timestamp, identifier)\n filename = os.path.join(self._outdir, filename)\n return filename\n\n def _get_episode(self):\n episode = {k: [t[k] for t in self._episode] for k in self._episode[0]}\n episode = {k: np.array(v) for k, v in episode.items()}\n for key, sequence in episode.items():\n if sequence.dtype == 'object':\n message = \"Sequence '{}' is not numeric:\\n{}\"\n raise RuntimeError(message.format(key, sequence))\n return episode\n\n def _write(self, episode, filename):\n if not tf.gfile.Exists(self._outdir):\n tf.gfile.MakeDirs(self._outdir)\n with io.BytesIO() as file_:\n np.savez_compressed(file_, **episode)\n file_.seek(0)\n with tf.gfile.Open(filename, 'w') as ff:\n ff.write(file_.read())\n name = os.path.splitext(os.path.basename(filename))[0]\n print('Recorded episode {}.'.format(name))\n","sub_path":"collect_gym_dataset.py","file_name":"collect_gym_dataset.py","file_ext":"py","file_size_in_byte":3009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"235260300","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jun 3 15:31:10 2018\r\n\r\n\"\"\"\r\nimport threading as tr,time\r\n\r\ndef slp():\r\n time.sleep(5)\r\n print('wake up')\r\n \r\ntobj=tr.Thread(target=slp)\r\ntobj.start()\r\ntobj.join() #to join main thread to child\r\n\r\nprint('done')","sub_path":"python/threading.py","file_name":"threading.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"149793480","text":"from otree.api import Currency as c, currency_range\nfrom ._builtin import Page, WaitPage\nfrom .models import Constants\nfrom . import models\nimport random\n\nclass PickCard(Page):\n form_model = models.Player\n form_fields = ['believe1', 'scale1', 'believe2', 'scale2']\n\n def vars_for_template(self):\n return {\n 'msg': self.player.content\n }\n\n\nclass PickSelect(Page):\n pass\n\n\nclass Intro(Page):\n def vars_for_template(self):\n self.player.set_k()\n msgs = self.player.get_msg()\n self.player.content = msgs[self.player.card_content()]\n\n\nclass FinalResult(Page):\n def vars_for_template(self):\n # random.shuffle(self.player.participant.vars['payoff'])\n chosen_round = self.player.participant.vars['chosen_round']\n urn = self.player.participant.vars['payoff'][chosen_round]\n comprehension = round(float(self.player.participant.vars['comprehension']), 1)\n urn = round(float(urn) * self.session.config['real_world_currency_per_point'],1)\n IQ = round(float(self.player.participant.vars['IQ']) * self.session.config['real_world_currency_per_point'], 1)\n self.player.final_payoff = round(urn + IQ + Constants.show_up + comprehension, 1)\n return {\n 'Urn': urn,\n 'IQ': IQ,\n 'show_up': Constants.show_up,\n 'comprehension': comprehension,\n 'total': urn + IQ + Constants.show_up + comprehension\n }\n\npage_sequence = [\n Intro,\n PickSelect,\n PickCard,\n FinalResult\n]\n","sub_path":"pickCard/pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"13022363","text":"\nfrom django.urls import path,include, re_path\nfrom . import views\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\napp_name = 'minor'\n\nurlpatterns = [\n\n path('',views.HomeView.as_view(),name='new-home'),\n path('project//',views.ProjectDetailView.as_view(), name= 'project'),\n path(\"group-registration/\", views.group_registration,name='group-registration'),\n path(\"faculty-registration/\", views.faculty_registration,name='faculty-registration'),\n path('login/', views.user_login,name='user-login'),\n path('logout/', views.user_logout,name = 'user-logout'),\n path('project-form/', views.project_form_view, name = 'project-form'),\n path('coordinator-projects/', views.coordinator_home, name = 'coordinator-home'),\n path('mentor-approval//', views.mentor_approval, name= 'mentor-approval'),\n path('hod-approval//', views.hod_approval, name= 'hod-approval'),\n path('project//edit/', views.ProjectUpdateView.as_view(), name='project_edit'),\n\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"project3/minor/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"17225693","text":"#!/usr/bin/env python\n\n\nfrom pyphylogenomics import BLAST\nimport sys\n\n\nblast_output = sys.argv[1].strip()\nmodel_genome = sys.argv[2].strip()\noutput_file = sys.argv[3].strip()\nspecies_name = sys.argv[4].strip()\n\nBLAST.blastParser(blast_output, model_genome, output_file, species_name)\n","sub_path":"code/parse_blast.py","file_name":"parse_blast.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"577499697","text":"import sys\nimport math\n\nclass ProcessBar:\n\tdef __init__(self, TargetValue, barWidth = 80, barBody = '='):\n\t\tself.currentValue = 0\n\t\t\n\t\tif len(barBody) == 1:\n\t\t\tself.barBody = barBody\n\t\telse:\n\t\t\traise Exception(\"The bar body should be build with a single halfwidth character.\")\n\t\t\n\t\ttry:\n\t\t\tself.barWidth = int(barWidth)\n\t\texcept ValueError:\n\t\t\traise Exception(\"The process bar width should be an integer.\")\n\t\t\t\n\t\ttry:\n\t\t\tself.TargetValue = float(TargetValue)\n\t\texcept ValueError:\n\t\t\traise Exception(\"The target value should be an integer.\")\n\t\t\n\n\tdef start(self):\n\t\tsys.stdout.write(\"[%s]\" % (\" \" * self.barWidth))\n\t\tsys.stdout.flush()\n\t\tsys.stdout.write(\"\\b\" * (self.barWidth+1)) # return to start of line, after '['\n\n\tdef process(self,nowProcess):\n\t\t# Draw the progress bar\n\t\tprecurrentValue = self.currentValue\n\t\tself.currentValue = int(math.floor((nowProcess/self.TargetValue) * self.barWidth))\n\t\tsys.stdout.write(self.barBody * (self.currentValue - precurrentValue))\n\t\tsys.stdout.flush()\n\n\tdef end(self):\n\t\t# End the progress bar\n\t\tif self.currentValue != self.TargetValue:\n\t\t\tsys.stdout.write(\"=\" * (self.barWidth - self.currentValue))\n\t\t\tsys.stdout.flush()\n\t\tsys.stdout.write(\"\\n\")\n","sub_path":"ProcessBar.py","file_name":"ProcessBar.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"624121425","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n\n# 单例模式\nclass Singleton(object):\n __instance = None\n\n def __new__(cls, age, name):\n if not cls.__instance:\n cls.__instance = object.__new__(cls)\n return cls.__instance\n\n\na = Singleton(18, 'dg')\nb = Singleton(8, 'ac')\na.age = 19\nprint(b.age)\n","sub_path":"singleton.py","file_name":"singleton.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"372661266","text":"import os\nimport sys\nimport time\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom pylab import *\nfrom sklearn.linear_model import LogisticRegression, Ridge\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.preprocessing import StandardScaler\n\nsys.path.append('/gpfs/projects/gavingrp/dongmeic/sdm/python/models_new')\nimport model_utils_new as util\nfrom construct_model_matrices_random import ModelMatrixConstructor\n\n# model1 - model with only bioclimatic variables\n# model2 - model with bioclimatic variables, transformation and interactions\n# model3 - model with bioclimatic variables, transformation, interactions and beetle variables\n# model4 - add age and density to model3\n\nmodel = 'model2'\nDATA_DIR = '/gpfs/projects/gavingrp/dongmeic/sdm/data/Xy_random_split_data'\nIMG_DIR = '/gpfs/projects/gavingrp/dongmeic/beetle/output/plots/images/' + model\nOUT_DIR = '/gpfs/projects/gavingrp/dongmeic/beetle/output/tables/' + model\nREGULARIZER = 'l1'\nprint('Regularizer:', REGULARIZER)\n\ndef main():\n make_dirs()\n plt.rcParams['figure.figsize'] = 10, 8\n TEST = False\n dropBtl = False\n dropVgt = False\n matrix_constructor = ModelMatrixConstructor(DATA_DIR, TEST)\n matrix_constructor.construct_model_matrices()\n if model == 'model1':\n \ttest_vars = matrix_constructor.get_variables()\n else:\n \ttest_vars = matrix_constructor.add_beetle_vars()\n \tif model == 'model2':\n \t\tdropBtl = True\n \telif model != 'model5':\n \t\tdropVgt = True\n #test_vars = matrix_constructor.add_interactions()\n #test_vars = matrix_constructor.add_variations()\n for var in ['x', 'y', 'year']:\n \t\ttest_vars.append(var)\n test_vars = sorted(test_vars)\n data_sets = matrix_constructor.select_variables(test_vars)\n [[X_train, y_train], [X_valid, y_valid], [X_test, y_test]] = data_sets\n for (data_set, name) in zip(data_sets, ['Train', 'Valid', 'Test']):\n \t\tprint_dims(data_set, name)\n util.print_percent_presence(y_train, 'y_train')\n util.print_percent_presence(y_valid, 'y_valid')\n util.print_percent_presence(y_test, 'y_test')\n y_train.columns=['btl_t']\n y_valid.columns=['btl_t']\n y_test.columns=['btl_t']\n full_train = X_train.copy()\n full_valid = X_valid.copy()\n full_test = X_test.copy()\n full_train['btl_t'] = y_train['btl_t']\n full_valid['btl_t'] = y_valid['btl_t']\n full_test['btl_t'] = y_test['btl_t']\n drop = ['x', 'y', 'year']\n if dropBtl:\n \tbtl_sum9 = [var for var in list(X_train) if 'btl' in var or 'sum9' in var]\n \tvgt = [var for var in list(X_train) if 'age' in var or 'density' in var]\n \tdrop += vgt\n \tdrop += btl_sum9\n \tdrop.append('vgt')\n if dropVgt:\n \tvgt = [var for var in list(X_train) if 'age' in var or 'density' in var]\n \tdrop += vgt\n X_train = X_train.drop(drop, axis=1)\n X_valid = X_valid.drop(drop, axis=1)\n X_test = X_test.drop(drop, axis=1)\n predictors = list(X_train)\n X_train, X_valid, X_test = scale_data(X_train, X_valid, X_test)\n y_train = y_train['btl_t'].values.reshape(-1)\n y_valid = y_valid['btl_t'].values.reshape(-1)\n y_test = y_test['btl_t'].values.reshape(-1)\n\n print('Fitting model...')\n BEST_C = get_best_C(X_train, y_train, X_valid, y_valid, predictors)\n logistic_clf = LogisticRegression(C=BEST_C, penalty=REGULARIZER, solver='saga', n_jobs=-1)\n logistic_clf.fit(X_train, y_train)\n preds = logistic_clf.predict(X_test)\n probs = logistic_clf.predict_proba(X_test)\n accuracy = sum(y_test == preds) / len(preds)\n print('Test accuracy:', accuracy) \n\n pred_ps = logistic_clf.predict_proba(X_test)\n pred_ps = np.array([p[1] for p in pred_ps])\n THRESHOLD = 0.5\n preds = get_predictions_at_threshold(pred_ps, THRESHOLD)\n best_threshold = threshold_plot(pred_ps, y_test);\n print('\\n\\nConfusion Matrices============================================')\n print('0.5 threshold:')\n cm = util.make_confusion_matrix(y_test, pred_ps, 0.5)\n metrics = util.get_metrics(cm)\n print('\\n\\nOptimal threshold:', best_threshold['threshold'])\n cm = util.make_confusion_matrix(\n y_test, pred_ps, best_threshold['threshold'])\n metrics = util.get_metrics(cm)\n auc_metrics = util.get_auc(y_test, pred_ps, OUT_DIR)\n util.plot_roc(\n auc_metrics['fpr'], auc_metrics['tpr'], path='%s/roc.png' % IMG_DIR)\n coefs = pd.DataFrame(\n [[pred, coef]\n for pred, coef in zip(predictors, logistic_clf.coef_[0])],\n columns=['predictor', 'coef'])\n coefs['abs'] = np.abs(coefs.coef)\n coefs = coefs.sort_values('abs', ascending=False)\n coefs = coefs.drop(['abs'], axis=1)\n print(coefs)\n coefs.to_csv('%s/coefficients.csv' % OUT_DIR, index=False)\n print('\\n\\nModel intercept:', logistic_clf.intercept_)\n\n pred_ps_train = logistic_clf.predict_proba(X_train)\n pred_ps_train = np.array([p[1] for p in pred_ps_train])\n pred_ps_valid = logistic_clf.predict_proba(X_valid)\n pred_ps_valid = np.array([p[1] for p in pred_ps_valid])\n full_train['probs'] = pred_ps_train\n full_train['preds'] = get_predictions_at_threshold(\n pred_ps_train, best_threshold['threshold'])\n full_valid['probs'] = pred_ps_valid\n full_valid['preds'] = get_predictions_at_threshold(\n pred_ps_valid, best_threshold['threshold'])\n full_test['probs'] = pred_ps\n full_test['preds'] = get_predictions_at_threshold(\n pred_ps, best_threshold['threshold'])\n all_data = full_train.append(full_valid).append(full_test)\n all_data.index = range(all_data.shape[0])\n years = sorted(full_train.year.unique())\n df = all_data[['x', 'y', 'year', 'btl_t', 'probs', 'preds']]\n df.to_csv('%s/predictions.csv' % OUT_DIR, index=False)\n\n print('\\n\\nGenerating prediction plots==================================')\n for year in years:\n print(' Train...')\n make_actual_pred_and_error_matrices(\n full_train,\n year,\n plot=True,\n path='%s/pred_plot_train_%d.png' % (IMG_DIR, year))\n print(' Valid...')\n make_actual_pred_and_error_matrices(\n full_valid,\n year,\n plot=True,\n path='%s/pred_plot_valid_%d.png' % (IMG_DIR, year))\n print(' Test...')\n make_actual_pred_and_error_matrices(\n full_test,\n year,\n plot=True,\n path='%s/pred_plot_test_%d.png' % (IMG_DIR, year))\n print(' Combined probabilities...')\n make_actual_pred_and_error_matrices(\n all_data,\n year,\n pred_type='probs',\n plot=True,\n path='%s/prob_plot_all_%d.png' % (IMG_DIR, year))\n print('all done!')\n \ndef make_dirs():\n for d in [IMG_DIR, OUT_DIR]:\n if not os.path.exists(d):\n os.makedirs(d)\n \n \ndef print_dims(data_set, name):\n print('%s:\\n X: %r\\n y: %r'\n % (name, data_set[0].shape, data_set[1].shape))\n\n\ndef scale_data(X_train, X_valid, X_test):\n scaler = StandardScaler()\n X_train = scaler.fit_transform(X_train)\n X_valid = scaler.transform(X_valid)\n X_test = scaler.transform(X_test)\n return X_train, X_valid, X_test\n\ndef get_best_C(X_train, y_train, X_valid, y_valid, predictors):\n\t\tl_mods = []\n\t\tCs = np.logspace(-4, 0, 5)\n\t\tbest_C = np.nan\n\t\tbest_accuracy = 0\n\t\tt0 = time.time()\n\t\tbest_penalty = None\n\t\tfor C in Cs:\n\t\t\t\tprint('Testing C =', C)\n\t\t\t\tfor penalty in [REGULARIZER]:\n\t\t\t\t\t\tprint(' %s:' % penalty, end=' ')\n\t\t\t\t\t\tlogistic_clf = LogisticRegression(C=C, penalty=penalty, solver='saga', n_jobs=-1)\n\t\t\t\t\t\tlogistic_clf.fit(X_train, y_train)\n\t\t\t\t\t\tpreds = logistic_clf.predict(X_valid)\n\t\t\t\t\t\taccuracy = sum(y_valid == preds) / len(preds)\n\t\t\t\t\t\ta = [[pred, coef] for pred, coef in zip(predictors, logistic_clf.coef_[0])]\n\t\t\t\t\t\tsig_preds = []\n\t\t\t\t\t\tsig_coefs = []\n\t\t\t\t\t\tfor pred, coef in a:\n\t\t\t\t\t\t\t\tif abs(coef) > 0:\n\t\t\t\t\t\t\t\t\t\tsig_preds.append(pred)\n\t\t\t\t\t\t\t\t\t\tsig_coefs.append(coef)\n\t\t\t\t\t\tprint([sig_preds[i] for i in argsort(np.abs(sig_coefs))[::-1]])\n\t\t\t\t\t\tprint([sig_coefs[i] for i in argsort(np.abs(sig_coefs))[::-1]])\t\t\t\t\t\t\n\t\t\t\t\t\tif (accuracy > best_accuracy):\n\t\t\t\t\t\t\t\tbest_C = C\n\t\t\t\t\t\t\t\tbest_accuaracy = accuracy\n\t\t\t\t\t\t\t\tbest_penalty = penalty\n\t\t\t\t\t\tprint('Validation accuracy:', round(accuracy, 4))\n\t\t\t\t\t\tl_mods.append(accuracy)\n\t\t\t\t\t\tprint('Elapsed time: %.2f minutes' % ((time.time() - t0) / 60))\n\t\tprint(l_mods)\n\t\treturn best_C\n\ndef get_predictions_at_threshold(pred_ps, threshold):\n return 1 * (pred_ps >= threshold)\n\n\ndef threshold_plot(pred_ps, targets, plot=False):\n thresholds = np.linspace(0, 1, 500)\n accuracies = []\n n = len(pred_ps)\n for threshold in thresholds:\n preds = get_predictions_at_threshold(pred_ps, threshold)\n accuracies.append((preds == targets).sum() / n)\n if plot:\n plt.plot(thresholds, accuracies);\n optimal_threshold = thresholds[np.argmax(accuracies)]\n optimal_accuracy = max(accuracies)\n if plot:\n plt.plot([optimal_threshold, optimal_threshold],\n [min(accuracies), max(accuracies)],\n 'r')\n plt.plot([0, 1], [optimal_accuracy, optimal_accuracy], 'r')\n plt.xlabel('Threshold for predicting \"Renewal\"')\n plt.ylabel('Accuracy')\n return {'threshold': optimal_threshold, 'accuracy': optimal_accuracy}\n\n\ndef pred_plot(actual_matrix, pred_matrix, error_matrix, year, path):\n fig = plt.figure()\n plt.subplot(131)\n imshow(np.rot90(actual_matrix));\n plt.title('%d Actual' % year);\n plt.subplot(132)\n imshow(np.rot90(pred_matrix));\n plt.title('%d Predicted' % year);\n plt.subplot(133)\n imshow(np.rot90(error_matrix));\n plt.title('%d Error' % year);\n fig.savefig(path)\n\n\ndef make_actual_pred_and_error_matrices(\n data, year, pred_type='preds', plot=False, path=''):\n data_year = data.loc[data.year == year, :]\n actual_matrix = util.column2matrix(data_year, 'btl_t')\n pred_matrix = util.column2matrix(data_year, pred_type)\n error_matrix = pred_matrix - actual_matrix\n if plot:\n pred_plot(actual_matrix, pred_matrix, error_matrix, year, path)\n return actual_matrix, pred_matrix, error_matrix\n \nif __name__ == '__main__':\n main()\n","sub_path":"python/models_new/logistic_model_random.py","file_name":"logistic_model_random.py","file_ext":"py","file_size_in_byte":10334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"195049400","text":"import random\r\nprint(\"Number guessing game\")\r\n\r\nrandomNum=random.randint(1,10)\r\nchances=0\r\nprint(\"Guess a number between 1 and 10\")\r\nwhile chances<5: \r\n guess=int(input(\"Enter your guess: \"))\r\n if guess==randomNum:\r\n print(\"Congratulations you won\")\r\n break\r\n elif guess 100:\n output = '亲,你走错片场了吧!输入的数字不在范围内'\n mb.showinfo('Hint:', output)\n elif guess == number:\n output = '恭喜,猜数正确'\n mb.showinfo('欢迎来到数字竞猜游戏:', output)\n break\n elif guess < number:\n low = guess\n output = '猜测数字比系统小,新范围'+str(low)+'--' + str(height)\n low = guess\n mb.showinfo('欢迎来到数字竞猜游戏', output)\n else:\n height = guess\n output = '猜测数字比系统大,新范围' + str(low)+'--' + str(height)\n mb.showinfo('欢迎来到数字竞猜游戏', output)\nprint('结束')\n\n","sub_path":"python/guess_number/guess_number3.py","file_name":"guess_number3.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"581831639","text":"from die import Die\r\nimport matplotlib.pyplot as plt\r\n#创建一个色子\r\ndie = Die()\r\nresults = [] #存储摇出来的结果\r\nfor roll_num in range(1000):\r\n result = die.roll()\r\n results.append(result)\r\n#分析结果\r\nfrequencies = []\r\nfor value in range(1,die.num_sides+1): #左闭右开\r\n frequency = results.count(value)\r\n frequencies.append(frequency)\r\nprint(results)\r\nprint(frequencies)\r\n#可视化结果\r\n\r\nplt.bar(range(1,7),frequencies,align='center')\r\nplt.xlabel(\"number\")\r\nplt.ylabel(\"Frequncy\")\r\n'''\r\n前边设置的x、y值其实就代表了不同柱子在图形中的位置(坐标),通过for循环找到每一个x、y值的相应坐标——a、b,\r\n再使用plt.text在对应位置添文字说明来生成相应的数字标签,而for循环也保证了每一个柱子都有标签。\r\n其中,a, b+0.05表示在每一柱子对应x值、y值上方0.05处标注文字说明, \r\n'%.0f' % b,代表标注的文字,即每个柱子对应的y值, ha='center', va= 'bottom'代表horizontalalignment(水平对齐)、\r\nverticalalignment(垂直对齐)的方式,fontsize则是文字大小。\r\n链接:https://www.jianshu.com/p/5ae17ace7984\r\n'''\r\nfor x,y in zip(range(1,7),frequencies): #设置数字标签\r\n plt.text(x,y+0.05,'%.0f'%y,ha = 'center',va='bottom')\r\nplt.grid()\r\nplt.show()","sub_path":"test/PYTHON/matplotlib/plt_bar.py","file_name":"plt_bar.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"224413922","text":"import logging\n\nfrom flask import Flask, escape, request, jsonify, abort\nfrom jjigae.naver import Term, parallel_lookup\nfrom jjigae.prestudy import extract\nfrom jjigae.common import COMMON_WORDS\n\napp = Flask(__name__)\napp.config[\"JSON_AS_ASCII\"] = False\n\n\n@app.route(\"/prestudy\", methods=[\"POST\"])\ndef prestudy():\n args = request.get_json()\n if \"text\" in args and isinstance(args[\"text\"], str):\n text = args[\"text\"]\n words = extract(text)\n limit = (\n args[\"limit_to_common_words\"] if \"limit_to_common_words\" in args else None\n )\n limit = limit if limit < len(COMMON_WORDS) else None\n return jsonify(\n {\n k: v.__dict__\n for (k, v) in parallel_lookup(\n words, restrict_to_common_words=limit\n ).items()\n }\n )\n else:\n return abort(jsonify({\"error\": \"Need text (str) in JSON body\"}))\n\n\n@app.route(\"/lookup\", methods=[\"POST\"])\ndef lookup():\n args = request.get_json()\n if \"word\" in args and isinstance(args[\"word\"], str):\n word = args[\"word\"]\n try:\n term = Term.lookup(word)\n if term:\n return jsonify(term.__dict__)\n else:\n return jsonify({\"not_found\": True})\n except Exception as e:\n app.logger.error(\"Error processing %s: %s\", word, str(e))\n return abort(jsonify({\"word\": word, \"error\": str(e)}))\n\n elif \"words\" in args and isinstance(args[\"words\"], list):\n words = args[\"words\"]\n try:\n return jsonify({k: v.__dict__ for (k, v) in parallel_lookup(words).items()})\n except Exception as e:\n app.logger.error(\"Error processing %s: %s\", str(words), str(e))\n return abort(jsonify({\"words\": words, \"error\": str(e)}))\n else:\n return abort(\n jsonify({\"error\": \"Need word (str) or words (list[str]) in JSON body\"})\n )\n\n\n@app.route(\"/\")\ndef status():\n return jsonify(status=\"ok\")\n\n\nif __name__ != \"__main__\":\n gunicorn_logger = logging.getLogger(\"gunicorn.error\")\n app.logger.handlers = gunicorn_logger.handlers\n app.logger.setLevel(gunicorn_logger.level)\n","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"37008453","text":"#\n# Copyright © 2021 Uncharted Software 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\nimport logging\nimport os\n\nimport pandas as pd\nfrom d3m import container, utils\nfrom d3m.metadata import base as metadata_base, hyperparams\nfrom d3m.primitive_interfaces import base, transformer\nfrom distil.primitives import utils as distil_utils\nfrom distil.primitives.utils import SINGLETON_INDICATOR, CATEGORICALS\nfrom distil.utils import CYTHON_DEP\nimport version\n\n__all__ = (\"ReplaceSingletonsPrimitive\",)\n\nlogger = logging.getLogger(__name__)\n\n\nclass Hyperparams(hyperparams.Hyperparams):\n use_columns = hyperparams.Set(\n elements=hyperparams.Hyperparameter[int](-1),\n default=(),\n semantic_types=[\n \"https://metadata.datadrivendiscovery.org/types/ControlParameter\"\n ],\n description=\"A set of column indices to force primitive to operate on. If any specified column cannot be parsed, it is skipped.\",\n )\n\n\nclass ReplaceSingletonsPrimitive(\n transformer.TransformerPrimitiveBase[\n container.DataFrame, container.DataFrame, Hyperparams\n ]\n):\n \"\"\"\n Replaces category members with a count of one with a shared singleton token value. Currently applies to columns\n with semantic type Categorical, Ordinal or DateTime.\n \"\"\"\n\n metadata = metadata_base.PrimitiveMetadata(\n {\n \"id\": \"7cacc8b6-85ad-4c8f-9f75-360e0faee2b8\",\n \"version\": version.__version__,\n \"name\": \"Replace singeltons\",\n \"python_path\": \"d3m.primitives.data_transformation.replace_singletons.DistilReplaceSingletons\",\n \"source\": {\n \"name\": \"Distil\",\n \"contact\": \"mailto:cbethune@uncharted.software\",\n \"uris\": [\n \"https://github.com/uncharted-distil/distil-primitives/blob/main/distil/primitives/replace_singletons.py\",\n \"https://github.com/uncharted-distil/distil-primitives\",\n ],\n },\n \"installation\": [\n CYTHON_DEP,\n {\n \"type\": metadata_base.PrimitiveInstallationType.PIP,\n \"package_uri\": \"git+https://github.com/uncharted-distil/distil-primitives.git@{git_commit}#egg=distil-primitives\".format(\n git_commit=utils.current_git_commit(os.path.dirname(__file__)),\n ),\n },\n ],\n \"algorithm_types\": [\n metadata_base.PrimitiveAlgorithmType.ENCODE_BINARY,\n ],\n \"primitive_family\": metadata_base.PrimitiveFamily.DATA_TRANSFORMATION,\n },\n )\n\n def produce(\n self,\n *,\n inputs: container.DataFrame,\n timeout: float = None,\n iterations: int = None,\n ) -> base.CallResult[container.DataFrame]:\n logger.debug(f\"Running {__name__}\")\n\n # set values that only occur once to a special token\n outputs = inputs.copy()\n\n # determine columns to operate on\n cols = distil_utils.get_operating_columns(\n inputs, self.hyperparams[\"use_columns\"], CATEGORICALS\n )\n\n for c in cols:\n vcs = pd.value_counts(list(inputs.iloc[:, c]))\n singletons = set(vcs[vcs == 1].index)\n if singletons:\n mask = outputs.iloc[:, c].isin(singletons)\n outputs.loc[mask, outputs.columns[c]] = SINGLETON_INDICATOR\n\n logger.debug(f\"\\n{outputs}\")\n\n return base.CallResult(outputs)\n","sub_path":"distil/primitives/replace_singletons.py","file_name":"replace_singletons.py","file_ext":"py","file_size_in_byte":4035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"90097293","text":"# Definition for binary tree with next pointer.\n# class TreeLinkNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n# self.next = None\n\nclass Solution:\n # @param root, a tree link node\n # @return nothing\n def connect(self, root):\n if not root:\n return\n nodeQueue = [root]\n while nodeQueue:\n prevNode = None\n for node in nodeQueue:\n if not prevNode:\n prevNode = node\n continue\n prevNode.next = node\n prevNode = node\n \n nodeQueue = [childNode for node in nodeQueue for childNode in [node.left, node.right] if childNode]","sub_path":"LeetCode/BFS/116_PopulatingNextRightPointersInEachNode.py","file_name":"116_PopulatingNextRightPointersInEachNode.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"214130854","text":"from os import environ\n\nfrom flask import current_app\n\n\ndef get_default_value(name):\n return {\n 'YOTI_APPLICATION_ID': environ.get('YOTI_APPLICATION_ID'),\n 'YOTI_CLIENT_SDK_ID': environ.get('YOTI_CLIENT_SDK_ID'),\n 'YOTI_KEY_FILE_PATH': environ.get('YOTI_KEY_FILE_PATH'),\n 'YOTI_REDIRECT_TO': 'flask_yoti.profile',\n 'YOTI_LOGIN_VIEW': 'flask_yoti.login',\n }.get(name)\n\n\ndef get_config_value(name):\n try:\n config = current_app.config\n parameter = config.get(name, get_default_value(name))\n except RuntimeError:\n parameter = get_default_value(name)\n\n if parameter is None:\n raise RuntimeError(\n 'Required parameter \"{0}\" is not configured'.format(name)\n )\n return parameter\n","sub_path":"plugins/flask_yoti/flask_yoti/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"157850494","text":"from feature_creator import FeatureCreator\nfrom train_one_prediction import TrainOnePrediction\nfrom weight import Weight\n\n\nclass OnlineLearning:\n\n def __init__(self, feature, data, flabel):\n self.feature = feature\n self.data = data\n self.phi = {} # Φファイ\n self.label = 0\n self.flabel = flabel\n self.weight = {}\n self.iteration = 1000\n\n def online_learning(self):\n count = 0\n\n \"\"\" initinalize \"\"\"\n for value in self.feature.values():\n split_word = value.split(' ')\n [self.weight.update({self.flabel + word: 0}) for word in split_word]\n cfeature = FeatureCreator()\n\n \"\"\" update weight \"\"\"\n while self.iteration >= count:\n count = count + 1\n for key, value in self.feature.items():\n self.phi = cfeature.create(value, self.data, self.flabel)\n self.label = TrainOnePrediction(self.weight, self.phi)\n if self.label is not key:\n update_weight = Weight(self.weight, self.phi, key)\n self.weight = update_weight.update()\n","sub_path":"NLP_programing/chapter3/online_learning.py","file_name":"online_learning.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"356247166","text":"# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nimport os\nimport os.path\nimport re\nimport shutil\nimport tempfile\n\nimport git\n\nfrom dockstack import docker\nfrom dockstack import exceptions\n\n\nenv_pattern = re.compile(\"\\$\\{\\w+\\}\")\n\n\nclass DockerContainer(object):\n \"\"\"Class to create a docker container.\"\"\"\n\n log = logging.getLogger(__name__)\n\n def __init__(self, service, common_conf, service_conf,\n config_dir, noop=False):\n \"\"\"Initialize with a given configuration.\n\n :param service: Name of the service.\n :param common_conf: Dictionary with config values from common YAML.\n :param service_conf: Dictionary with config values from service YAML.\n :param config_dir: Directory with configuration files.\n :param noop: Do not actually execute commands when requested.\n :param quiet: Do things more quietly.\n\n :raises: InvalidConfig on config errors.\n \"\"\"\n if 'common' not in common_conf:\n raise exceptions.InvalidConfig(\"Expecting a common config.\")\n if 'service' not in service_conf:\n raise exceptions.InvalidConfig(\"Expecting a service config.\")\n\n self.common_conf = common_conf['common']\n self.service_conf = service_conf['service']\n self.service_name = service\n self.noop = noop\n self.volumes = [] # Container volumes\n\n # Environment variables. We automatically supply the config dir.\n self.envs = {}\n self.envs['dockstack_config'] = config_dir\n\n # Set our working directory. All files will be added here and all\n # prep commands will be run from here, as well.\n self.workdir = self.service_conf.get('workdir', '/dockstack')\n\n # Script to hold our commands\n self.command_script = \"%s_commands.sh\" % self.service_name\n\n # Actual command to execute. This could change if there is only\n # a single command.\n self.command = os.path.join(self.workdir, self.command_script)\n\n self.docker = docker.Docker(noop)\n\n def _add_volumes(self, conf):\n \"\"\"Verify volumes have a source and destination.\"\"\"\n if 'volumes' not in conf:\n return\n for volume in conf['volumes']:\n if volume.find(':') == -1:\n raise exceptions.InvalidConfig(\n \"Invalid volume '%s'. Format is SRC:DST\" % volume)\n src, dst = volume.split(':')\n if not src or not dst:\n raise exceptions.InvalidConfig(\n \"Invalid volume '%s'. Format is SRC:DST\" % volume)\n\n # Volumes may contain environment variable references\n # that we need to handle here.\n src = self._replace_envs(src)\n dst = self._replace_envs(dst)\n self.volumes.append((src, dst))\n\n def _build_image(self):\n \"\"\"Build a customized image from the base image.\"\"\"\n base_image = self._get_image()\n new_image = self._get_image_name()\n\n dockerfile = []\n dockerfile.append(\"FROM %s\" % base_image)\n\n # Set build environment variables\n for env, val in self.envs.items():\n dockerfile.append(\"ENV %s %s\" % (env, val))\n\n if 'expose' in self.service_conf:\n for port in self.service_conf['expose']:\n dockerfile.append(\"EXPOSE %s\" % port)\n\n dockerfile.append(\"WORKDIR %s\" % self.workdir)\n\n try:\n tempd = tempfile.mkdtemp()\n\n if len(self.service_conf['commands']) == 1:\n self.command = self.service_conf['commands'][0]\n else:\n self._commands_as_script(\n self.service_conf['commands'],\n os.path.join(tempd, self.command_script))\n\n dockerfile.append(\"ADD %s %s/\" % (self.command_script,\n self.workdir))\n\n # Add all files to the workdir location.\n # NOTE: The files may contain env var references, but docker\n # itself should handle those during build since we define\n # them above with ENV. However, our file copy operation below\n # must substitute them.\n if 'add' in self.service_conf:\n for entry in self.service_conf['add']:\n if entry.find(':') > 0:\n local_file, container_file = entry.split(':')\n else:\n local_file = entry\n container_file = None\n\n basename = os.path.basename(local_file)\n\n # ADD requires the file to be relative to the source dir\n shutil.copy(self._replace_envs(local_file), tempd)\n\n if container_file:\n dockerfile.append(\"ADD %s %s/%s\" % (basename,\n self.workdir,\n container_file))\n else:\n # NOTE: The trailing slash on workdir is needed\n dockerfile.append(\"ADD %s %s/\" % (basename,\n self.workdir))\n\n # Run prep commands _after_ all files have been added.\n if 'prep' in self.service_conf:\n for command in self.service_conf['prep']:\n dockerfile.append(\"RUN %s\" % command)\n\n dockerfile.extend(self._handle_sources(tempd))\n dockerfile = '\\n'.join(dockerfile)\n\n with open(os.path.join(tempd, 'Dockerfile'), 'w') as f:\n f.write(dockerfile)\n\n self.docker.build(tempd, new_image)\n\n finally:\n shutil.rmtree(tempd)\n self.log.debug(\"Dockerfile:\\n-------\\n%s\\n--------\" % dockerfile)\n\n def _commands_as_script(self, commands, script_name):\n \"\"\"Combine commands into a master script file.\n\n :param commands: A list of commands to execute.\n :param script_name: Full path to the script to build.\n \"\"\"\n with open(script_name, \"w\") as f:\n f.write(\"#!/bin/sh\\n\")\n f.write(\"\\n\".join(commands))\n f.write(\"\\n\")\n os.chmod(script_name, 0o700)\n\n def _container_exists(self, name):\n containers = self.docker.ps(show_all=True)\n for container in containers:\n if name in container['names']:\n return True\n return False\n\n def _get_envs(self):\n \"\"\"Read environment variables from the configs.\n\n An environment variable defined in the service config takes precedence\n over one defined in the common config.\n \"\"\"\n if 'environment' in self.common_conf:\n for k, v in self.common_conf['environment'].iteritems():\n self.envs[k] = v\n if 'environment' in self.service_conf:\n for k, v in self.service_conf['environment'].iteritems():\n self.envs[k] = v\n\n def _get_image(self):\n \"\"\"Determine the docker image to use.\"\"\"\n if 'image' in self.service_conf:\n return self.service_conf['image']\n return self.common_conf['image']\n\n def _get_image_name(self):\n return \"dockstack/%s\" % self.service_name\n\n def _handle_sources(self, build_dir):\n \"\"\"Create the build commands for 'sources' entries.\n\n We have to put the sources into the docker build directory, as that is\n a requirement for the ADD instructions. We copy them there, if needed,\n but try not to copy stuff we don't need.\n\n :param build_dir: The docker build directory.\n\n :returns: A list of commands to use for the docker build.\n \"\"\"\n commands = []\n\n ignored = ('*.pyc', '.tox', '.testrepository')\n\n if 'sources' not in self.service_conf:\n return commands\n\n for source in self.service_conf['sources']:\n source = self._replace_envs(source)\n\n # Git repos\n if source[0:6] == \"git://\":\n base = os.path.basename(source)\n repo_name = os.path.splitext(base)[0]\n git_dir = os.path.join(build_dir, repo_name)\n self.log.debug(\"GIT CLONE: %s TO %s\" % (source, git_dir))\n if not self.noop:\n git.Repo.clone_from(source, git_dir)\n commands.append(\"ADD %s %s/%s\" %\n (repo_name, self.workdir, repo_name))\n commands.append(\"WORKDIR %s/%s\" % (self.workdir, repo_name))\n commands.append(\"RUN pip install -U -r requirements.txt\")\n commands.append(\"RUN pip install -U -r test-requirements.txt\")\n commands.append(\"RUN python setup.py install\")\n\n # Local directories\n elif os.path.isdir(source):\n base = os.path.basename(source)\n if not self.noop:\n shutil.copytree(source,\n os.path.join(build_dir, base),\n ignore=shutil.ignore_patterns(*ignored))\n commands.append(\"ADD %s %s/%s\" % (base, self.workdir, base))\n commands.append(\"WORKDIR %s/%s\" % (self.workdir, base))\n commands.append(\"RUN pip install -U -r requirements.txt\")\n commands.append(\"RUN pip install -U -r test-requirements.txt\")\n commands.append(\"RUN python setup.py install\")\n else:\n raise exceptions.InvalidConfig(\n \"Source '%s' is not valid.\" % source)\n\n return commands\n\n def _image_exists(self, image):\n \"\"\"Check if a docker image exists.\n\n If the 'history' command fails, we assume it doesn't exist.\n\n :param image: Image name to check.\n :returns: True if the image exists, False otherwise.\n \"\"\"\n try:\n self.docker.history(image)\n except Exception:\n return False\n return True\n\n def _replace_envs(self, string):\n \"\"\"Substitute any env variables within a string with their value.\n\n Look for any \"${env}\" substrings and replaces it with the value of\n the 'env' variable.\n\n :param string: The string in which to do substitutions.\n\n :returns: The result string.\n :raises: InvalidConfig if the environment variable is not defined.\n \"\"\"\n new_string = string\n iterator = env_pattern.finditer(string)\n for match in iterator:\n begin, end = match.span()\n env = string[begin+2:end-1]\n if env not in self.envs:\n raise exceptions.InvalidConfig(\n \"Variable '%s' not defined\" % env)\n new_string = new_string.replace(string[begin:end], self.envs[env])\n return new_string\n\n def _validate_configs(self):\n \"\"\"Validate the common and service configurations.\n\n This will validate the configuration values needed to use docker.\n\n :raises: InvalidConfig on config errors.\n \"\"\"\n required_common = ['image']\n\n # Check for missing values.\n for value in required_common:\n if value not in self.common_conf:\n raise exceptions.InvalidConfig(\"Missing '%s' value\" % value)\n\n self._get_envs()\n self._add_volumes(self.common_conf)\n self._add_volumes(self.service_conf)\n\n def start(self, rebuild=False):\n \"\"\"Start the docker container.\n\n The configurations from both the common YAML and service YAML will\n be used to configure and start the docker container. The container\n will be named after the service name for convenience.\n\n Each service container will have a directory from the host machine\n mounted as a volume within each container (the /data directory of\n the container). This can be used for data persistence, such as logs.\n\n :param rebuild: Rebuild the container if it exists.\n\n :raises: InvalidConfig on config errors.\n \"\"\"\n self._validate_configs()\n image = self._get_image_name()\n description = self.service_conf.get('description', self.service_name)\n\n # If container already exists, just start it.\n container_exists = self._container_exists(self.service_name)\n if container_exists and not rebuild:\n self.log.info(\"START - %s\" % description)\n self.docker.start(self.service_name)\n return\n\n ports = []\n if 'ports' in self.service_conf:\n for port_mapping in self.service_conf['ports']:\n host_port, container_port = port_mapping.split(':')\n ports.append((host_port, container_port))\n\n links = []\n if 'links' in self.service_conf:\n for link in self.service_conf['links']:\n links.append((link, link))\n\n daemon = True\n if 'daemon' in self.service_conf:\n daemon = self.service_conf['daemon']\n\n image_exists = self._image_exists(image)\n\n if rebuild and image_exists:\n if container_exists:\n self.docker.rm(self.service_name)\n self.docker.rmi(image)\n self._build_image()\n elif not image_exists:\n self._build_image()\n\n self.log.info(\"RUN - %s\" % description)\n self.docker.run(image,\n self.command,\n name=self.service_name,\n links=links,\n ports=ports,\n volumes=self.volumes,\n daemon=daemon)\n","sub_path":"dockstack/container.py","file_name":"container.py","file_ext":"py","file_size_in_byte":14292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"100655996","text":"##############################################################\n# Libraries\n##############################################################\nimport numpy as np\nimport csv\nimport random\n\n\n##############################################################\n# Variable Definition\n##############################################################\n\n\n##############################################################\n# Class Definition\n##############################################################\n# Node Class\n# Create a Node and its data\n# API Operation | Description\n# Node(track_id) | Create Node\n# str | Print track_id\nclass Node:\n # Initialize a node\n # Node(track_id)\n # Input: track_id\n # Output: None\n def __init__(self, track_id, track_name=None, artist=None, album=None, file_location=None, next=None):\n self.track_id = track_id\n self.track_name = track_name\n self.artist = artist\n self.album = album\n self.file_location = file_location\n self.next = next\n\n # Print track_id\n # str()\n # input: None\n # Output: string of track_id\n def __str__(self):\n return str(self.track_id)\n\n\n# LinkedList class\n# Create a linked list\n# API Operation | Description\n# LinkedList(head) | Create a LinkedList by initialize the head\n# len | Print the length of the LinkedList\n# insert_to_front(data) | Create a data Node and set to the head\n# find(data) | Find Node with desired data\n# append(data) | Append new data to the end\n# delete(data) | Delete Node with desired data\n# insert_after(pre_data, data) | Insert a data Node right after the current one\n# print_list() | Print the whole LinkedList\nclass LinkedList(object):\n # Initialize a LinkedList\n # LinkedList(data)\n # Input: data\n # Output: None\n def __init__(self, head):\n self.head = head\n\n # print LinkedList length\n # len()\n # Input: None\n # Output: length of the LinkedList\n def __len__(self):\n current = self.head\n counter = 0\n while current is not None:\n counter += 1\n current = current.next\n return counter\n\n # Find the nth linked Node\n # find_nth(n)\n # Input: n as integer\n # Output nth's track_id\n def find_nth(self, n):\n current = self.head\n counter = 0\n track_id = 0\n if n <= 0:\n print(\"Invalid Input in Finding Location\")\n exit(1)\n while counter < n:\n counter += 1\n current = current.next\n track_id = current.track_id\n if current.next is None:\n print(\"Not Found in the List\")\n return track_id\n return track_id\n\n # insert to the front\n # insert_to_front(data)\n # Input: data\n # Output: newly created node\n def insert_to_front(self, track_id, track_name=None, artist=None, album=None, file_location=None):\n if track_id is None:\n return None\n node = Node(track_id=track_id, track_name=track_name, artist=artist, album=album, file_location=file_location,\n next=self.head)\n self.head = node\n return node\n\n # Find Node with desired track_id\n # find(track_id)\n # Input: track_id\n # Output: None\n def find(self, track_id, feedback=False):\n if track_id is None:\n return None\n curr_node = self.head\n while curr_node is not None:\n if curr_node.track_id == track_id:\n return curr_node\n curr_node = curr_node.next\n # Determine Feedback\n if feedback:\n return curr_node\n else:\n return None\n\n # Append new data to the end\n # append(data)\n # Input: data\n # Output: None\n def append(self, track_id, track_name=None, artist=None, album=None, file_location=None):\n if track_id is None:\n return None\n node = Node(track_id=track_id, track_name=track_name, artist=artist, album=album, file_location=file_location)\n if self.head is None:\n self.head = node\n return node\n curr_node = self.head\n while curr_node.next is not None:\n curr_node = curr_node.next\n curr_node.next = node\n return node\n\n # Delete Node if data matches\n # delete(data)\n # Input: data\n # Output: None\n def delete(self, track_id):\n if track_id is None:\n return None\n if self.head is None:\n return None\n if self.head.track_id == track_id:\n self.head = self.head.next\n return\n prev_node = self.head\n curr_node = self.head.next\n while curr_node is not None:\n if curr_node.track_id == track_id:\n prev_node.next = curr_node.next\n return\n else:\n prev_node = curr_node\n curr_node = curr_node.next\n\n # Insert after certain node\n # insert_after(pre_data, data)\n # Input: pre_data, data\n # Output: None\n def insert_after(self, pre_track_id, track_id, track_name=None, artist=None, album=None, file_location=None):\n new_node = Node(track_id=track_id, track_name=track_name, artist=artist, album=album,\n file_location=file_location)\n pre_node = self.find(pre_track_id, feedback=True)\n new_node.next = pre_node.next\n pre_node.next = new_node\n\n # Print the LinkedList\n # print_list()\n # Input: None\n # Output: None\n def print_list(self):\n temp = self.head\n counter = 1\n while temp:\n print(counter, \"||\", temp.track_id, \"|\", temp.track_name, \"| by:\", temp.artist, \"| in:\", temp.album)\n temp = temp.next\n counter += 1\n\n # str()\n # creates a string with all the data from the list\n # inputs: none\n # returns: list in the form of a string\n def __str__(self):\n s = ''\n cur = self.head\n if cur is None:\n s += \"EMPTY\"\n while cur is not None:\n s += str(cur.track_id) + ' '\n cur = cur.next\n return s\n\n # Return shape\n # shape()\n # Input: None\n # Output: [length, height]\n def shape(self):\n return np.asarray([self.__len__(), 5])\n\n\n# HashTable Class\n# Create a Node and its data\n# API Operation | Description\n# Node(track_id) | Create Node\n# insert(item) | Insert an item\n# hash_function(key) | Hashing Function\n# str | Print track_id\nclass HashTable:\n # __init___(length)\n # constructor that makes an empty HashTable with length\n # inputs: numElements which is number of elements in Hash_Table\n # returns: none\n def __init__(self, length):\n self.length = length\n self.table = [None] * self.length\n index = 0\n for item in self.table:\n self.table[index] = LinkedList(None)\n index += 1\n self.n_data = 0\n\n # _hashFunc\n # hashing function\n # inputs: key\n # returns: location in hash table\n def hash_function(self, key):\n return key.track_id\n\n # insert(item)\n # inserts an item in the hash table\n # inputs: item - to insert\n # returns: none\n def insert(self, item):\n loc = int(self.hash_function(item))\n self.table[loc].append(item)\n\n # find(loc)\n # Find item at location\n # input: loc\n # output: item at loc\n def find(self, location):\n return self.table[location].head\n\n # str()\n # creates a string with all the data from the table\n # inputs: none\n # returns: table in the form of a string\n def __str__(self):\n s = ''\n i = 0\n for x in self.table:\n s += \"Data at index \" + str(i) + \" is \\n\"\n s += str(self.table[i])\n s += \"\\n\"\n i = i + 1\n return s\n\n # __getitem__(item)\n # Obtain Linked Note at location\n # input: location\n # output: node at location\n def __getitem__(self, item):\n if 0 < item < self.length:\n return self.table[item].head.track_id\n else:\n print(\"Error(900): Index Out of Range or not in range\")\n exit(900)\n\n\n# Class Library\n# Create library\n# API Operation | Description\n# Library(playlist_length) | Create Library from csv\n# add_track(playlist, add_track_id, add_track_location) | Add track to a location in playlist\n# print(playlist) | Print playlist\nclass Library:\n def __init__(self, playlist_length, file_name=\"raw_track.csv\", repeat=False):\n # Load Library\n self.file_name = file_name\n self.data_range = 175 # 155321\n self.library = HashTable(self.data_range)\n with open(self.file_name) as csv_file:\n tracks = csv.reader(csv_file, dialect='excel')\n index = 0\n for row in tracks:\n if index > 0:\n new_node = Node(track_id=row[0],\n track_name=row[37],\n artist=row[5],\n album=row[2],\n file_location=row[26])\n self.library.insert(item=new_node)\n index += 1\n # Check Playlist Length\n self.playlist_length = playlist_length\n if self.playlist_length > self.data_range:\n print(\"## Length Out of Range ##\")\n self.playlist_length = self.data_range\n else:\n self.playlist_length = self.playlist_length\n # Generate Playlist\n random_list = np.zeros(self.playlist_length)\n index = 0\n while index <= self.playlist_length - 1:\n temp_num = random.randint(0, self.data_range - 1)\n # Check if exists\n if not repeat:\n exist = 0\n for index2 in range(0, self.playlist_length):\n if temp_num == int(random_list[index2]):\n exist = 1\n if exist == 0 and self.library.find(temp_num) is not None:\n random_list[index] = temp_num\n index += 1\n else:\n index = index\n else:\n random_list[index] = temp_num\n index += 1\n # Push playlist info\n self.playlist = LinkedList(None)\n for item in random_list:\n track_id = int(item)\n self.playlist.append(track_id=self.library[track_id].track_id,\n track_name=self.library[track_id].track_name,\n artist=self.library[track_id].artist,\n album=self.library[track_id].album,\n file_location=self.library[track_id].file_location)\n\n # Add a track to the playlist\n # add_track(playlist, add_track_id, add_track_location)\n # Input: playlist, add_track_id, add_track_location\n # Output: modified playlist\n def add_track(self, playlist, add_track_id, add_track_location):\n outer_range = len(playlist)\n # Find the corresponding track info\n if self.library[add_track_id] is not None:\n if add_track_location > outer_range or add_track_location < 1:\n print(\"Warning(901): Add Out of Index\")\n add_loc = outer_range\n else:\n add_loc = add_track_location - 1\n # Add to playlist\n pre_track = playlist.find_nth(n=add_loc)\n playlist.insert_after(pre_track_id=pre_track,\n track_id=add_track_id,\n track_name=self.library[add_track_id].track_name,\n artist=self.library[add_track_id].artist,\n album=self.library[add_track_id].album,\n file_location=self.library[add_track_id].file_location)\n return LinkedList(head=playlist.head)\n else:\n print(\"Warning(902): Item not found in library\")\n return LinkedList(head=playlist.head)\n\n # Print the current playlist\n # print(playlist)\n # Input: playlist\n # Output: None\n def print(self, playlist):\n print(\"Printing Current Playlist\")\n playlist.print_list()\n print(\"\")\n\n\n##############################################################\n# Function Prototype\n##############################################################\ndef test_api():\n # Create Library\n lib = Library(file_name=\"raw_track_short.csv\", playlist_length=10)\n # Obtain Playlist\n playlist = lib.playlist\n # Print Playlist\n lib.print(playlist=playlist)\n # Add new song to playlist\n playlist = lib.add_track(playlist=playlist, add_track_id=-1, add_track_location=5) #Cory tried 154, -1 pass, -1, 5 fail\n # Print playlist\n lib.print(playlist)\n\n\n##############################################################\n# Main Function\n##############################################################\ndef main():\n print(\"Hello World!\")\n test_api()\n\n\n##############################################################\n# Main Function Runner\n##############################################################\nif __name__ == \"__main__\":\n main()\n","sub_path":"lab6/lab6_2.py","file_name":"lab6_2.py","file_ext":"py","file_size_in_byte":13684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"188639296","text":"import xml.etree.ElementTree as ET\nimport csv\nfrom graph import drawGraph\n\n# Requiered Define with Tablaeu Workbook should be analyzed\ntablaeuWorkBook = ET.parse('src/2019_12-02 - Cost to Serve (Live) - DH.twb')\n# Requiered Choose the Tab or Datasource from Tablaeu Workbook\ntablaeuSource=\"customer_order_profile (ML Estimated)\"\n\n# Optional Do you wand to see only connceted Fields, when keep True?\nonlyConnectedFileds=True\n\ndef parse():\n root = tablaeuWorkBook.getroot()\n for datasource in root.findall('datasources/datasource'):\n value = datasource.get('caption')\n print (value)\n columnID=0\n columnCollections={}\n all_calculation=[]\n if (value == tablaeuSource):\n for column in datasource.findall(\"column\"):\n columnID=columnID+1\n columnName=column.get(\"name\")\n columnCaption=column.get(\"caption\")\n columnRole=column.get(\"role\")\n columnCollections.update({columnID: columnName})\n dataset=[]\n typeOfColumn=\"field\"\n idCalcColumnAll=[]\n\n \n if column.find(\"calculation\") is not None:\n columnFormula=column.find(\"calculation\").get(\"formula\")\n typeOfColumn=\"calculation\"\n idx_s =[i for i in range(len(columnFormula)) if columnFormula.startswith(\"[\", i)]\n idx_e =[i for i in range(len(columnFormula)) if columnFormula.startswith(\"]\", i)] \n j=0\n\n for pos_start_all in idx_s:\n pos_end_all=idx_e[j]\n j=j+1\n valueAll=columnFormula[pos_start_all:pos_end_all+1]\n idCalcColumnAll.append(valueAll)\n else:\n columnFormula=column.find(\"calculation\")\n \n dataset.append(columnID)\n dataset.append(columnCaption)\n dataset.append(columnName)\n dataset.append(typeOfColumn)\n dataset.append(columnFormula)\n dataset.append(idCalcColumnAll)\n dataset.append(columnRole)\n all_calculation.append(dataset) \n final=[]\n\n #HEAD ROW FOR CSV\n head=[]\n head.append(\"id\")\n head.append(\"caption\")\n head.append(\"name\")\n head.append(\"typeOfColumn_parent_calculations\")\n head.append(\"formula\")\n head.append(\"names_of_parent\")\n head.append(\"ids_of_parent\")\n head.append(\"role_of_column\")\n final.append(head)\n \n for calc in all_calculation:\n temp=[]\n temp.append(calc[0])\n temp.append(calc[1])\n temp.append(calc[2])\n temp.append(calc[3])\n temp.append(calc[4])\n temp.append(calc[5])\n \n ids=[]\n\n for element in calc[5]:\n dependencies=[]\n for x, y in columnCollections.items(): \n if y==element:\n dependencies.append(x)\n break\n ids.append(dependencies)\n\n temp.append(ids)\n temp.append(calc[6])\n final.append(temp)\n \n with open(\"output/\"+tablaeuSource+\".csv\", 'w', newline='') as myfile:\n wr = csv.writer(myfile, delimiter=';')\n wr.writerows(final) \n\n\nif __name__== \"__main__\":\n parse()\n drawGraph(tablaeuSource, onlyConnectedFileds)","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":3742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"415301496","text":"import sys\nsys.setrecursionlimit(1 << 20)\nINF = float('inf')\n\n\ndef read_int_list():\n return list(map(int, input().split()))\n\n\ndef read_ints():\n return map(int, input().split())\n\n\nfrom itertools import combinations\n\n\ndef main():\n N = int(input())\n P = read_int_list()\n dp = [[0] * 10010 for _ in range(N + 1)]\n unique = {0}\n for i in range(1, N + 1):\n p = P[i - 1]\n for sum_p in range(10010):\n tmp_p = dp[i - 1][sum_p]\n if sum_p >= p:\n tmp_p = max(tmp_p, dp[i - 1][sum_p - p] + p)\n dp[i][sum_p] = tmp_p\n unique.add(tmp_p)\n print(len(unique))\n\n\nmain()\n","sub_path":"others/tpdc_a.py","file_name":"tpdc_a.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"277034229","text":"from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom AnalizadorSistemas.models import *\nfrom django.core import serializers\nfrom django.http import HttpResponse\nfrom AnalizadorSistemas.Mundo import Calculador\nfrom django.template import RequestContext\nimport json\nimport csv\n# Create your views here.\n\ndef login(request):\n\n template = \"login.html\"\n return render(request,template,context_instance=RequestContext(request))\n\n@login_required(redirect_field_name='home')\ndef exportar(request):\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=\"datos.csv\"'\n writer = csv.writer(response)\n totalSalidas = Salida.objects.all()\n lista = list(totalSalidas)\n matriz = Calculador.generarMatriz(lista)\n print(matriz[0])\n writer.writerow(['Producto', 'Fecha', 'Defectuoso', 'Costo'])\n for i in matriz:\n writer.writerow(i)\n\n\n\n return response\n\n\n\ndef home(request):\n\n #Contenedores de datos\n totalSalidas = Salida.objects.all()\n totalEntradas = Entrada.objects.all()\n\n N = Calculador.obtenerN(totalSalidas)\n #Calculo de Calidad\n totalDatos = Calculador.contatTotal(totalSalidas)\n totalDefectuosos = Calculador.ContarMalos(totalSalidas)\n totalAceptados = Calculador.contarBuenos(totalSalidas)\n #Calculo Tiempo de Ciclo\n tiempoCiclo = Calculador.datosTiempoCiclo(totalEntradas,totalSalidas)\n ##Calculo indicadores\n info = Proceso.objects.all()\n porcentajes= Calculador.obtenerPorcentaje(info)\n disponibilidad = porcentajes[len(porcentajes)-1]\n dispo = str(disponibilidad)\n rendimiento = Calculador.RendimientoPromedio(totalEntradas,totalSalidas,info)\n rendi = float(\"{0:.2f}\".format(rendimiento))\n calidad = Calculador.CalidadPromedio(totalEntradas,totalSalidas)\n calidad = float(\"{0:.2f}\".format(calidad))\n #Calculo Rendimiento\n rendimiento = Calculador.datosRendimiento(totalEntradas,totalSalidas,0.03)\n #Costos\n costos = Calculador.datosCostos(totalSalidas)\n\n diccionario = {'malos':totalDefectuosos,'buenos':totalAceptados,\n 'totalDatos':totalDatos,'N':N,'ciclo':tiempoCiclo,\n 'calidad':str(calidad), 'dispo':dispo, 'rendimientoG':str(rendi), 'rendimientoU':rendimiento,\n 'costos':costos}\n\n\n template = \"index.html\"\n return render(request, template, diccionario, context_instance=RequestContext(request))\n\ndef actualizar(request):\n\n\n #Contenedores de datos\n totalSalidas = Salida.objects.all()\n totalEntradas = Entrada.objects.all()\n N = Calculador.obtenerN(totalSalidas)\n #Calculo de Calidad\n totalDatos = Calculador.contatTotal(totalSalidas)\n totalDefectuosos = Calculador.ContarMalos(totalSalidas)\n totalAceptados = Calculador.contarBuenos(totalSalidas)\n #Calculo Tiempo de Ciclo\n tiempoCiclo = Calculador.datosTiempoCiclo(totalEntradas,totalSalidas)\n ##Calculo indicadores\n info = Proceso.objects.all()\n porcentajes= Calculador.obtenerPorcentaje(info)\n disponibilidad = porcentajes[len(porcentajes)-1]\n dispo = str(disponibilidad)\n rendimiento = Calculador.RendimientoPromedio(totalEntradas,totalSalidas,info)\n rendi = float(\"{0:.2f}\".format(rendimiento))\n calidad = Calculador.CalidadPromedio(totalEntradas,totalSalidas)\n calidad = float(\"{0:.2f}\".format(calidad))\n #Calculo Rendimiento\n rendimiento = Calculador.datosRendimiento(totalEntradas,totalSalidas,0.03)\n #Costos\n costos = Calculador.datosCostos(totalSalidas)\n\n\n\n\n datos = {'malos':totalDefectuosos,'buenos':totalAceptados,\n 'totalDatos':totalDatos,'N':N,'ciclo':tiempoCiclo,\n 'calidad':str(calidad), 'dispo':dispo, 'rendimientoG':str(rendi), 'rendimientoU':rendimiento,\n 'costos':costos}\n\n\n\n\n salida = json.dumps(datos)\n return HttpResponse(salida, content_type='application/json')\n\ndef variables(request):\n template = \"variables.html\"\n return render(request,template,context_instance=RequestContext(request))\n\ndef subir(request):\n # if this is a POST request we need to process the form data\n vInstalaciones = request.POST.get(\"instalaciones\")\n numOperario = request.POST.get(\"operarios\")\n turnosTrabajo = request.POST.get(\"turnosTrabajo\")\n anosMaquina = request.POST.get(\"anosAdquisicionMaquina\")\n porcentajeSeguro = request.POST.get(\"porcentajeSeguro\")\n valorKilowatts = request.POST.get(\"valorKiloWatts\")\n costoHerramienta = request.POST.get(\"costoHerramienta\")\n vidaMaquina = request.POST.get(\"vidaMaquina\")\n presMensual = request.POST.get(\"presupuestoMensual\")\n costoServicios = request.POST.get(\"CostoServicios\")\n porcentajeDisponibilidad = request.POST.get(\"porcDisponibilidad\")\n mantenimieno = request.POST.get(\"mantenimiento\")\n tiempoPlaneado = request.POST.get(\"tiempoPlaneado\")\n estandarCiclo = request.POST.get(\"estandarCiclo\")\n\n proceso = Proceso(tiempoPlaneado=tiempoPlaneado, porcDisponibilidad= porcentajeDisponibilidad, valorInstalacion = vInstalaciones,\n numOperarios=numOperario, turnoTrabajo= turnosTrabajo, porcentajeSeguro = porcentajeSeguro,\n valorKilowatts = valorKilowatts, presupuestoMensual = presMensual, costoServicios= costoServicios,\n costoHerramienta = costoHerramienta, vidaMaquina = vidaMaquina, estandarCiclo=estandarCiclo,\n anosMaquina = anosMaquina, mantenimieno=mantenimieno)\n\n\n proceso.save()\n\n\n return HttpResponseRedirect(\"/\")\n\n\n\n\n\n","sub_path":"PDG GitHub/AnalizadorSistemas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"485846845","text":"'''\nCreated on May 7, 2014\n\n@author: jeffy\n'''\nimport os\ndef rename(dir):\n files = os.listdir(dir)\n os.chdir(dir)\n count = 0\n for f in files:\n if f.endswith('.pdf'):\n count += 1\n os.rename(f, 'KDD'+str(count)+'.pdf')\n \nif __name__ == '__main__':\n rename('../../data/KDD11')","sub_path":"src/lib/rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"650890228","text":"from turtle import *\nfrom time import sleep\n\n\nlives = 3\ncanvas = getcanvas()\nregister_shape('panda_2.gif')\n\nclass Panda(Turtle):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.pu()\n\t\tself.size = 20\n\t\tself.dx = 4.5\n\t\tself.dy = 4.5\n\t\tcanvas = getcanvas()\n\t\tself.shape('panda_2.gif')\n\n\tdef move(self):\n\t\tself.goto(self.xcor() + self.dx, self.ycor() + self.dy)\n\n\tdef check_tile_collision(self, list):\n\t\tfor entity in list:\n\t\t\tif (self.xcor() + self.size > entity.xcor() - entity.width and self.xcor() - self.size < entity.xcor() + entity.width) and\\\n\t\t\t(self.ycor() + self.size > entity.ycor() - entity.height and self.ycor() - self.size < entity.ycor() + entity.height):\n\t\t\t\tif entity.ycor() - entity.height < self.ycor() < entity.ycor() + entity.height:\n\t\t\t\t\tself.dx *= -1\n\t\t\t\tif entity.xcor() - entity.width < self.xcor() < entity.xcor() + entity.width:\n\t\t\t\t\tself.dy *= -1\n\t\t\t\tentity.hp -= 1\n\t\t\t\tif entity.hp == 0:\n\t\t\t\t\tentity.goto(500,0)\n\n\t\t\t\telse:\n\t\t\t\t\tentity.draw_self()\n\n\t\t\t\tif self.dx > 0:\n\t\t\t\t\tself.dx += 0.05\n\t\t\t\telse:\n\t\t\t\t\tself.dx -= 0.05\n\n\t\t\t\tif self.dy > 0:\n\t\t\t\t\tself.dy += 0.05\n\t\t\t\telse:\n\t\t\t\t\tself.dy -= 0.05\n\t\t\t\t#replace with math stuff\n\n\tdef check_player_collision(self, player):\n\t\tif self.xcor() + self.size > player.xcor() and self.xcor() - self.size < player.xcor() + player.width and\\\n\t\tself.ycor() + self.size > player.ycor() - player.height and self.ycor() - self.size < player.ycor() + player.height:\n\t\t\tself.dy *= -1\n\t\t\tself.dx = abs(self.dx)\n\n\t\telif self.xcor() - self.size < player.xcor() and self.xcor() + self.size > player.xcor() - player.width and\\\n\t\tself.ycor() + self.size > player.ycor() - player.height and self.ycor() - self.size < player.ycor() + player.height:\n\t\t\tself.dy *= -1\n\t\t\tself.dx = -abs(self.dx)\n\n\n\tdef check_edge_collision(self):\n\t\tglobal lives, heart_stamps, hearts\n\t\tif self.xcor() >= canvas.winfo_width()/2 - self.size or self.xcor() <= -canvas.winfo_width()/2 + self.size:\n\t\t\tself.dx *= -1\n\n\t\tif self.ycor() >= canvas.winfo_height()/2 - self.size:\n\t\t\tself.dy *= -1\n\n\t\telif self.ycor() - self.size <= -canvas.winfo_height()/2 + 10:\n\t\t\tlives -= 1\n\t\t\tif lives == 0:\n\t\t\t\treturn True\n\t\t\tself.goto(0,0)\n\t\t\tgetscreen().update()\n\t\t\tsleep(1.5)\n\t\t\treturn 'reduce'\n\t\telse:\n\t\t\treturn False","sub_path":"Breakout/Panda.py","file_name":"Panda.py","file_ext":"py","file_size_in_byte":2226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"503765720","text":"# -*- coding: utf-8 -*-\n\nfrom django import forms\n#from .validators import validate_file_extension\n\ndef validate_file_extension(value):\n import os\n from django.core.exceptions import ValidationError\n ext = os.path.splitext(value.name)[1] # [0] returns path+filename\n valid_extensions = ['.fasta', '.fas', '.fa', '.fastq', '.fq']\n if not ext.lower() in valid_extensions:\n raise ValidationError(u'Unsupported file extension.')\n\nclass DocumentForm(forms.Form):\n docfile = forms.FileField(\n label='Select a file',\n validators=[validate_file_extension]\n )\n","sub_path":"myproject/myapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"313534825","text":"from django.test import SimpleTestCase\nfrom testfixtures import TempDirectory, LogCapture\n\nfrom logging import INFO, ERROR, DEBUG\nfrom unittest import mock\nimport os\n\nfrom hardware.Utils.logger import Logger\n\n\nclass LoggerTests(SimpleTestCase):\n def setUp(self):\n self.temp_dir = TempDirectory()\n\n def tearDown(self):\n self.temp_dir.cleanup()\n\n def test_create_logger_with_dir(self):\n \"\"\"\n Simple test for creating a logger\n \"\"\"\n with mock.patch.dict(os.environ, {\"LOG_DIRECTORY\": self.temp_dir.path}):\n logger = Logger(name=\"test_logger\", filename=\"logger.txt\")\n\n self.assertTrue(logger.name == \"test_logger\")\n self.assertTrue(\n logger.format == \"%(asctime)s | %(levelname)s | %(message)s\"\n )\n self.assertTrue(logger.level is INFO)\n\n def test_create_logger_with_level(self):\n with mock.patch.dict(os.environ, {\"LOG_DIRECTORY\": self.temp_dir.path}):\n logger = Logger(name=\"test_logger\", filename=\"logger.txt\", level=ERROR)\n\n self.assertTrue(logger.name == \"test_logger\")\n self.assertTrue(\n logger.format == \"%(asctime)s | %(levelname)s | %(message)s\"\n )\n self.assertTrue(logger.level is ERROR)\n\n @mock.patch.object(os, \"makedirs\")\n @mock.patch(\"os.path.exists\")\n def test_makedir_if_not_exist(self, path_mock, dir_mock):\n \"\"\"\n insures that the function os.makedir is called if the supplied directory\n doesn't exist\n \"\"\"\n path_mock.return_value = False\n dir_mock.return_value = self.temp_dir.path\n with mock.patch.dict(os.environ, {\"LOG_DIRECTORY\": self.temp_dir.path}):\n Logger(name=\"test_logger\", filename=\"logger.txt\")\n\n dir_mock.assert_called()\n dir_mock.assert_called_with(self.temp_dir.path)\n\n def test_info_message(self):\n \"\"\"\n Tests the .info method\n \"\"\"\n with mock.patch.dict(os.environ, {\"LOG_DIRECTORY\": self.temp_dir.path}):\n with LogCapture() as capture:\n logger = Logger(name=\"test_logger\", filename=\"logger.txt\")\n logger.info(\"test message\")\n\n capture.check((\"test_logger\", \"INFO\", \"test message\"))\n\n @mock.patch(\"builtins.print\")\n def test_info_message_with_print(self, mock_print=mock.MagicMock()):\n \"\"\"\n Tests the .info method\n \"\"\"\n with mock.patch.dict(\n os.environ, {\"LOG_DIRECTORY\": self.temp_dir.path, \"SHOW_LOGS\": \"True\"}\n ):\n with LogCapture() as capture:\n logger = Logger(name=\"test_logger\", filename=\"logger.txt\")\n logger.info(\"test message\")\n\n self.assertTrue(mock_print.mock_calls == [mock.call(\"test message\")])\n\n capture.check((\"test_logger\", \"INFO\", \"test message\"))\n\n def test_message_failure(self):\n \"\"\"\n makes sure that nothing is logged during initialization\n \"\"\"\n with mock.patch.dict(os.environ, {\"LOG_DIRECTORY\": self.temp_dir.path}):\n with LogCapture() as capture:\n logger = Logger(name=\"test_logger\", filename=\"logger.txt\") # noqa: F841\n capture.check() # expect no output\n\n def test_error_message(self):\n \"\"\"\n Tests the .error method\n \"\"\"\n with mock.patch.dict(os.environ, {\"LOG_DIRECTORY\": self.temp_dir.path}):\n with LogCapture() as capture:\n logger = Logger(name=\"test_logger\", filename=\"logger.txt\")\n logger.error(\"test message\")\n\n capture.check((\"test_logger\", \"ERROR\", \"test message\"))\n\n def test_debug_message(self):\n \"\"\"\n Tests the .debug method\n \"\"\"\n with mock.patch.dict(os.environ, {\"LOG_DIRECTORY\": self.temp_dir.path}):\n with LogCapture() as capture:\n mylogger = Logger(\n name=\"test_logger\", filename=\"logger.txt\", level=DEBUG\n )\n mylogger.debug(\"test message\")\n\n capture.check((\"test_logger\", \"DEBUG\", \"test message\"))\n\n def test_warn_message(self):\n \"\"\"\n Tests the .warn method\n \"\"\"\n with mock.patch.dict(os.environ, {\"LOG_DIRECTORY\": self.temp_dir.path}):\n with LogCapture() as capture:\n mylogger = Logger(name=\"test_logger\", filename=\"logger.txt\")\n mylogger.warn(\"test message\")\n\n capture.check((\"test_logger\", \"WARNING\", \"test message\"))\n","sub_path":"hardware/tests/test_logger.py","file_name":"test_logger.py","file_ext":"py","file_size_in_byte":4559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"208175352","text":"from os.path import join, abspath\nimport subprocess\n\nfrom my_utils.python_utils.general import get_arg_string\nfrom my_utils.tensorflow_utils.training import set_GPUs\nfrom global_settings import PYTHON_EXE, RESULTS_DIR, PROCESSED_DATA_DIR\n\n\ndataset = \"svhn\"\ndata_dir = join(PROCESSED_DATA_DIR, \"ComputerVision\", dataset.upper(), \"bytes\")\ntrain_file = join(data_dir, \"train.npz\")\ntest_file = join(data_dir, \"test.npz\")\n\noutput_dir = abspath(join(RESULTS_DIR, \"semi_supervised\", \"{}\".format(dataset), \"ICT_VD\"))\n\n\n# Default settings\n# =============================== #\nDEFAULT_CONFIG_500 = {\n \"num_labeled\": 500,\n \"input_norm\": \"standard\",\n \"flip_horizontally\": False,\n \"translating_pixels\": 2,\n\n \"batch_size\": 100,\n \"batch_size_labeled\": 25,\n\n \"epochs\": 1000,\n \"steps\": 280000,\n \"rampup_len_step\": 10000,\n \"rampdown_len_step\": 80000,\n\n \"lr_max\": 0.1,\n \"lr_momentum\": 0.9,\n \"weight_decay\": 0.0001,\n \"weight_norm\": False,\n \"gauss_noise\": True,\n\n \"ema_momentum_init\": 0.99,\n \"ema_momentum_final\": 0.99,\n\n \"alpha\": 1.0,\n \"cross_ent_l\": 1.0,\n \"cent_u_coeff_max\": 0.0,\n \"cons_coeff_max\": 10.0,\n \"weight_kld_coeff_max\": 0.05,\n\n \"cons_mode\": \"mse\",\n\n # It is important that this one is False when #labeled is small\n # Which means we also apply consistency loss on labeled data\n \"cons_4_unlabeled_only\": False,\n\n # We should not mask weights\n \"mask_weights\": False,\n\n # Setting this one to either True or False does not change the results\n # However, when \"cons_against_mean\" = False, we should set it to True\n \"ema_4_log_sigma2\": True,\n \"cons_against_mean\": True,\n}\n\n\nDEFAULT_CONFIG_250 = DEFAULT_CONFIG_500\nDEFAULT_CONFIG_250['num_labeled'] = 250\n\n\nDEFAULT_CONFIG_1000 = DEFAULT_CONFIG_500\nDEFAULT_CONFIG_1000['num_labeled'] = 1000\n# =============================== #\n\n\n# Run settings\n# =============================== #\nrun_config = {\n \"output_dir\": output_dir,\n \"dataset\": dataset,\n \"train_file\": train_file,\n \"test_file\": test_file,\n\n\n # 9310gaurav\n # ------------------------ #\n \"model_name\": \"9310gaurav\",\n\n # 250\n # ------------------------ #\n # \"run\": \"0_ICTVD_L250_Nesterov_alpha1.0\",\n # \"run\": \"0a_ICTVD_L250_Nesterov_alpha1.0\",\n # \"run\": \"0b_ICTVD_L250_Nesterov_alpha1.0\",\n # \"num_labeled\": 250,\n # \"alpha\": 1.0,\n # \"cent_u_coeff_max\": 0.0,\n # ------------------------ #\n\n # 500\n # ------------------------ #\n # \"run\": \"100_ICTVD_L500_Nesterov_alpha1.0\",\n # \"run\": \"100a_ICTVD_L500_Nesterov_alpha1.0\",\n # \"run\": \"100b_ICTVD_L500_Nesterov_alpha1.0\",\n # \"num_labeled\": 500,\n # \"alpha\": 1.0,\n # \"cent_u_coeff_max\": 0.0,\n # ------------------------ #\n\n # 1000\n # ------------------------ #\n # \"run\": \"200_ICTVD_L1000_Nesterov_alpha1.0\",\n # \"run\": \"200a_ICTVD_L1000_Nesterov_alpha1.0\",\n # \"run\": \"200b_ICTVD_L1000_Nesterov_alpha1.0\",\n # \"num_labeled\": 1000,\n # \"alpha\": 1.0,\n # \"cent_u_coeff_max\": 0.0,\n # ------------------------ #\n\n \"force_rm_dir\": True,\n}\n# =============================== #\n\nif run_config['num_labeled'] == 250:\n config = DEFAULT_CONFIG_250\nelif run_config['num_labeled'] == 500:\n config = DEFAULT_CONFIG_500\nelif run_config['num_labeled'] == 1000:\n config = DEFAULT_CONFIG_1000\nelse:\n raise ValueError(\"num_labeled={}\".format(run_config['num_labeled']))\n\nconfig.update(run_config)\narg_str = get_arg_string(config)\nset_GPUs([0])\n\nprint(\"Running arguments: [{}]\".format(arg_str))\nrun_command = \"{} ./train.py {}\".format(PYTHON_EXE, arg_str).strip()\nsubprocess.call(run_command, shell=True)","sub_path":"working/semi_supervised/ICT_VD/run_svhn.py","file_name":"run_svhn.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"574149157","text":"#!/usr/bin/python2\n# coding: utf-8\n\nfrom __future__ import unicode_literals\nimport simplejson as json\nimport random\nimport thread\nimport numpy as np\nimport argparse\n\nargs_parser = argparse.ArgumentParser(description='Simple application suggesting tweets with the help of Machine Learning algorithms')\nargs_parser.add_argument('pseudo', metavar='', type=str,\n help='Twitter user\\'s name (without the @)')\nargs = args_parser.parse_args()\n\nfrom flask import Flask, render_template, request, redirect, url_for, jsonify\napp = Flask(__name__)\n\nimport stream_categorie as sg\nfrom stream_categorie import MyFilteredStream as FStream\n\nuser = args.pseudo\nmax_tweets = 30 # Arbitrary maximum number of tweets\n\ncategories = []\ntweets=[]\n\nNocat=\"Halloween\" # Joker category\nnp.set_printoptions(formatter={'float': '{: 0.2f}'.format})\nstream = FStream()\nstream.stream()\n\n\"\"\"\nSimply show the index page\n:param username: The user's name (simply esthetic for the moment)\n\"\"\"\n@app.route('/')\n@app.route('/')\ndef index(username=user):\n return render_template('index.html', username=username)\n\n\"\"\"\nChange the user (useless for the moment)\n:param request.form['username']: New user's name\n\"\"\"\n@app.route('/switch', methods=['POST', 'GET'])\ndef switchUser():\n user = request.form['username']\n return redirect(url_for('index', username=user))\n\n\"\"\"\nUpdate the list of the categories\n:param json: True if a return is required\n:return: Returns the list of the categories (JSON format)\n\"\"\"\n@app.route('/update_categories', methods=['POST', 'GET'])\ndef update_categories(json=True):\n global categories, stream\n new_categories = stream.get_new_categories()\n\n for c in new_categories:\n categories += [{ \"color\": \"#%06x\" % random.randint(0, 0xFFFFFF),\n \"id\": len(categories),\n \"name\": c}]\n\n if json:\n return jsonify(result=categories)\n\n\"\"\"\nUpdate the list of the tweets\n:param json: True if a return is required\n:return: Returns the list of the tweets (JSON format)\n\"\"\"\n@app.route('/update_tweets', methods=['POST', 'GET'])\ndef update_tweets(json=True):\n global tweets, max_tweets, stream, categories\n\n for nt in stream.get_corpus():\n # Just in case the tweet's category has been removed for a mysterious reason\n has_cat = False\n\n for c in categories:\n if c[\"name\"] == nt[\"cat\"]:\n nt[\"cat\"] = c\n has_cat = True\n\n if has_cat:\n tweets += [nt]\n\n if len(tweets) > max_tweets:\n tweets.pop(0)\n\n stream.clear_corpus()\n\n print(tweets)\n\n if json:\n return jsonify(result=tweets)\n\n\"\"\"\nSimply launche the app in a new thread\nSet debug to True to activate the powerful Flask's debugger\n\"\"\"\nif __name__ == '__main__':\n # thread.start_new_thread(app.run(), debug=True)\n thread.start_new_thread(app.run(), debug=False)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"4358175","text":"def modify_fs(module, blade):\n 'Modify Filesystem'\n changed = True\n if (not module.check_mode):\n mod_fs = False\n nfsv3 = (module.params['nfs'] if (module.params['nfsv3'] is None) else module.params['nfsv3'])\n attr = {\n \n }\n if module.params['user_quota']:\n user_quota = human_to_bytes(module.params['user_quota'])\n if module.params['group_quota']:\n group_quota = human_to_bytes(module.params['group_quota'])\n fsys = get_fs(module, blade)\n if fsys.destroyed:\n attr['destroyed'] = False\n mod_fs = True\n if module.params['size']:\n if (human_to_bytes(module.params['size']) != fsys.provisioned):\n attr['provisioned'] = human_to_bytes(module.params['size'])\n mod_fs = True\n api_version = blade.api_version.list_versions().versions\n if (NFSV4_API_VERSION in api_version):\n if (nfsv3 and (not fsys.nfs.v3_enabled)):\n attr['nfs'] = NfsRule(v3_enabled=nfsv3)\n mod_fs = True\n if ((not nfsv3) and fsys.nfs.v3_enabled):\n attr['nfs'] = NfsRule(v3_enabled=nfsv3)\n mod_fs = True\n if (module.params['nfsv4'] and (not fsys.nfs.v4_1_enabled)):\n attr['nfs'] = NfsRule(v4_1_enabled=module.params['nfsv4'])\n mod_fs = True\n if ((not module.params['nfsv4']) and fsys.nfs.v4_1_enabled):\n attr['nfs'] = NfsRule(v4_1_enabled=module.params['nfsv4'])\n mod_fs = True\n if (nfsv3 or (module.params['nfsv4'] and fsys.nfs.v3_enabled) or fsys.nfs.v4_1_enabled):\n if (fsys.nfs.rules != module.params['nfs_rules']):\n attr['nfs'] = NfsRule(rules=module.params['nfs_rules'])\n mod_fs = True\n if (module.params['user_quota'] and (user_quota != fsys.default_user_quota)):\n attr['default_user_quota'] = user_quota\n mod_fs = True\n if (module.params['group_quota'] and (group_quota != fsys.default_group_quota)):\n attr['default_group_quota'] = group_quota\n mod_fs = True\n else:\n if (nfsv3 and (not fsys.nfs.enabled)):\n attr['nfs'] = NfsRule(enabled=nfsv3)\n mod_fs = True\n if ((not nfsv3) and fsys.nfs.enabled):\n attr['nfs'] = NfsRule(enabled=nfsv3)\n mod_fs = True\n if (nfsv3 and fsys.nfs.enabled):\n if (fsys.nfs.rules != module.params['nfs_rules']):\n attr['nfs'] = NfsRule(rules=module.params['nfs_rules'])\n mod_fs = True\n if (module.params['smb'] and (not fsys.smb.enabled)):\n attr['smb'] = ProtocolRule(enabled=module.params['smb'])\n mod_fs = True\n if ((not module.params['smb']) and fsys.smb.enabled):\n attr['smb'] = ProtocolRule(enabled=module.params['smb'])\n mod_fs = True\n if (module.params['http'] and (not fsys.http.enabled)):\n attr['http'] = ProtocolRule(enabled=module.params['http'])\n mod_fs = True\n if ((not module.params['http']) and fsys.http.enabled):\n attr['http'] = ProtocolRule(enabled=module.params['http'])\n mod_fs = True\n if (module.params['snapshot'] and (not fsys.snapshot_directory_enabled)):\n attr['snapshot_directory_enabled'] = module.params['snapshot']\n mod_fs = True\n if ((not module.params['snapshot']) and fsys.snapshot_directory_enabled):\n attr['snapshot_directory_enabled'] = module.params['snapshot']\n mod_fs = True\n if (module.params['fastremove'] and (not fsys.fast_remove_directory_enabled)):\n attr['fast_remove_directory_enabled'] = module.params['fastremove']\n mod_fs = True\n if ((not module.params['fastremove']) and fsys.fast_remove_directory_enabled):\n attr['fast_remove_directory_enabled'] = module.params['fastremove']\n mod_fs = True\n api_version = blade.api_version.list_versions().versions\n if (HARD_LIMIT_API_VERSION in api_version):\n if ((not module.params['hard_limit']) and fsys.hard_limit_enabled):\n attr['hard_limit_enabled'] = module.params['hard_limit']\n mod_fs = True\n if (module.params['hard_limit'] and (not fsys.hard_limit_enabled)):\n attr['hard_limit_enabled'] = module.params['hard_limit']\n mod_fs = True\n if mod_fs:\n n_attr = FileSystem(**attr)\n try:\n blade.file_systems.update_file_systems(name=module.params['name'], attributes=n_attr)\n except Exception:\n module.fail_json(msg='Failed to update filesystem {0}.'.format(module.params['name']))\n else:\n changed = False\n module.exit_json(changed=changed)","sub_path":"Data Set/bug-fixing-3/1b45abc4f3fd736414d819601126accc4672a80c--fix.py","file_name":"1b45abc4f3fd736414d819601126accc4672a80c--fix.py","file_ext":"py","file_size_in_byte":4984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"270058354","text":"import json\nimport corenlp\nif __name__ == '__main__':\n with open('./nlp.txt', 'r') as f:\n text = f.read()\n corenlp_dir = \"/usr/local/lib/stanford-corenlp-full-2013-06-20/\"\n parser = corenlp.StanfordCoreNLP(corenlp_path=corenlp_dir)\n # 一度に処理すると、途中で処理が切れる\n for line in text.split('\\n'):\n result = json.loads(parser.parse(line))\n for sentence_data in result['sentences']:\n for word_data in sentence_data['words']:\n print(word_data[0])\n","sub_path":"53.py","file_name":"53.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"328351509","text":"#!/usr/bin/env python\n\nimport sys, os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport scipy\nimport scipy.interpolate\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 6:\n sys.stderr.write(\"Usage: %s <# of Files> <# Nodes in one direction> <levels> <Post process extension> \\n\")%(sys.argv[0])\n sys.exit()\n\nnFiles = int(sys.argv[1])\nN = int(sys.argv[2])\ntitle = sys.argv[3]\nnLevels = sys.argv[4]\nextension = sys.argv[5]\n\nnNodes = N * N\n\nxMin = -100\nxMax = 100\nyMin = -100\nyMax = 100\n\nnDensity = [];\nx = [];\ny = [];\ntime = [];\n\nk = 0\nwhile k <= nFiles:\n f = open(str(k)+'-'+str(extension)+'.dat','r')\n lines = f.readlines()\n f.close()\n \n i=0\n for line in lines:\n x.append(float(line.split()[1]))\n y.append(float(line.split()[2]))\n time.append(k)\n i += 1\n k += 499\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n\nplt.scatter(x,y, c=time, cmap='seismic')\nxlim = plt.xlim([xMin,xMax])\nylim = plt.ylim([yMin,yMax])\n\nplt.xlabel('Angstroms', fontsize=15)\nplt.ylabel('Angstroms', fontsize=15)\nplt.title(title, fontsize=15)\n\nplt.savefig(title+'.png')\nplt.savefig(title+'.eps', format='eps', dpi=1200)\n\n","sub_path":"002-plot/pointByPoint-plot_membrane-saturation.py","file_name":"pointByPoint-plot_membrane-saturation.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"114458962","text":"#!/usr/bin/env python\n#coding: utf-8\n\"\"\"\nConverter module. \nThis is for the moment empty (populated only with almost pass through anonymous functions)\nbut aims to be populated with more sofisticated translators ... \n\n\"\"\"\n# get ready for python3\nfrom __future__ import with_statement, print_function\n\n__author__ = \"Jérôme Kieffer\"\n__contact__ = \"jerome.kieffer@esrf.eu\"\n__license__ = \"GPLv3+\"\n__copyright__ = \"European Synchrotron Radiation Facility, Grenoble, France\"\n\nimport types, logging\nlogger = logging.getLogger(\"converter\")\n\ndef convert_data_integer(data):\n \"\"\"\n convert data to integer\n \"\"\"\n if data is not None:\n return data.astype(int)\n else:\n return data\n\n\nCONVERSION_HEADER = {\n (\"edfimage\", \"edfimage\"): lambda header:header,\n }\nCONVERSION_DATA = {\n (\"edfimage\", \"edfimage\"): lambda data:data,\n (\"edfimage\", \"cbfimage\"): convert_data_integer,\n (\"edfimage\", \"mar345image\"): convert_data_integer,\n (\"edfimage\", \"fit2dmaskimage\"): convert_data_integer,\n (\"edfimage\", \"kcdimage\"): convert_data_integer,\n (\"edfimage\", \"OXDimage\"): convert_data_integer,\n (\"edfimage\", \"pnmimage\"): convert_data_integer,\n }\n\ndef convert_data(inp, outp, data):\n \"\"\"\n Return data converted to the output format ... over-simplistic implementation for the moment ...\n @param inp,outp: input/output format like \"cbfimage\"\n @param data(ndarray): the actual dataset to be transformed\n \"\"\"\n return CONVERSION_DATA.get((inp, outp), lambda data:data)(data)\n\ndef convert_header(inp, outp, header):\n \"\"\"\n return header converted to the output format\n @param inp,outp: input/output format like \"cbfimage\"\n @param header(dict):the actual set of headers to be transformed \n \"\"\"\n return CONVERSION_HEADER.get((inp, outp), lambda header:header)(header)\n","sub_path":"fabio-src/converters.py","file_name":"converters.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"96448927","text":"\"\"\" 9. Write a binary search function. It should take a sorted sequence and\nthe item it is looking for. It should return the index of the item if found.\nIt should return -1 if the item is not found.\"\"\"\n\nprint(\"Question 9\")\n\nposition = 0\nlist = [2,4,5,8,10,15,18,25,28,35,48,50]\n\n\ndef binary_search(list, n):\n\n lower_bound = 0\n upper_bound = len(list) - 1\n\n while lower_bound <= upper_bound:\n mid = (lower_bound + upper_bound) // 2\n\n if list[mid] == n:\n globals()['position'] = mid\n return True\n else:\n if list[mid] < n:\n lower_bound = mid + 1\n else:\n upper_bound = mid - 1\n\n return False\n\n\nif binary_search(list,50):\n print(\"Found at: \", position)\nelse:\n print(\"Not Found\")\n","sub_path":"9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"320885685","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.admin_dashboard, name=\"admin_dashboard\"),\n path('register-user', views.register_user_admin, name=\"register_user\"),\n path('show-user', views.get_user, name=\"show_user\"),\n path('update-user-to-admin/<int:user_id', views.update_user_to_admin, name=\"user_to_admin\"),\n path('create-service', views.AdminServiceCreateView.as_view(), name=\"create_service\"),\n path('view-service', views.AdminServiceListView.as_view(), name=\"view_service\"),\n \n path('updateservice/<int:service_id>/', views.update_service, name=\"updateservice\"),\n path('deleteservice/<int:service_id>/', views.delete_service, name=\"deleteservice\"),\n\n path('servicemen-order/', views.ServicemenOrderListView, name=\"admin_servicemen_order\"),\n path('servicemen-order-detail/<int:pk>/', views.ServicemenOrderDetailView.as_view(), name=\"admin_servicemen_order_detail\"),\n path('servicemen-order-status/<int:pk>/', views.ServicemenOrderStatuChangeView.as_view(), name=\"admin_servicemen_orderstatus_change\"),\n path('servicemen-neworder/', views.ServicemenNewOrderListView, name=\"admin_servicemen_neworder\"),\n path('servicemens/', views.ServicemenView.as_view(), name=\"admin_view_servicemen\"),\n\n]","sub_path":"admins/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"483929162","text":"import numpy as np\n\nfrom qgis.PyQt.QtCore import (Qt)\nfrom qgis.PyQt.QtGui import (QKeyEvent)\nfrom qgis.PyQt.QtWidgets import (QWidget)\nfrom qgis.core import (QgsWkbTypes, QgsGeometry, QgsPointLocator, Qgis)\nfrom qgis.gui import (QgisInterface, QgsMapToolAdvancedDigitizing, QgsMapMouseEvent,\n QgsSnapIndicator)\n\nfrom los_tools.processing.tools.util_functions import get_max_decimal_numbers, round_all_values\nfrom .los_without_target_widget import LoSNoTargetInputWidget\n\n\nclass LosNoTargetMapTool(QgsMapToolAdvancedDigitizing):\n\n def __init__(self, iface: QgisInterface) -> None:\n super().__init__(iface.mapCanvas(), iface.cadDockWidget())\n self._iface = iface\n self._canvas = self._iface.mapCanvas()\n\n self._point = None\n\n self._snapper = self._canvas.snappingUtils()\n self.snap_marker = QgsSnapIndicator(self._canvas)\n\n self._los_rubber_band = self.createRubberBand(QgsWkbTypes.LineGeometry)\n\n self._widget: QWidget = None\n\n def create_widget(self):\n self.delete_widget()\n\n self._widget = LoSNoTargetInputWidget()\n self._iface.addUserInputWidget(self._widget)\n self._widget.setFocus(Qt.TabFocusReason)\n\n self._widget.valuesChanged.connect(self.draw_los)\n\n def delete_widget(self):\n if self._widget:\n self._widget.releaseKeyboard()\n self._widget.deleteLater()\n self._widget = None\n\n def activate(self) -> None:\n super(LosNoTargetMapTool, self).activate()\n self.create_widget()\n self.messageDiscarded.emit()\n self._canvas = self._iface.mapCanvas()\n self._snapper = self._canvas.snappingUtils()\n if self._canvas.mapSettings().destinationCrs().isGeographic():\n self.messageEmitted.emit(\n \"Tool only works if canvas is in projected CRS. Currently canvas is in geographic CRS.\",\n Qgis.Critical)\n self.deactivate()\n return\n self._widget.setUnit(self._canvas.mapSettings().destinationCrs().mapUnits())\n\n def clean(self) -> None:\n self.snap_marker.setVisible(False)\n self._los_rubber_band.hide()\n\n def deactivate(self) -> None:\n self.clean()\n self.delete_widget()\n self._iface.mapCanvas().unsetMapTool(self)\n super(LosNoTargetMapTool, self).deactivate()\n\n def canvasReleaseEvent(self, e: QgsMapMouseEvent) -> None:\n if e.button() == Qt.RightButton:\n self.deactivate()\n elif e.button() == Qt.LeftButton:\n if self._snap_point:\n self._point = self._snap_point\n else:\n self._point = e.mapPoint()\n self.draw_los()\n\n def canvasMoveEvent(self, event: QgsMapMouseEvent) -> None:\n result = self._snapper.snapToMap(event.pos())\n self.snap_marker.setMatch(result)\n if result.type() == QgsPointLocator.Vertex:\n self._snap_point = result.point()\n else:\n self._snap_point = None\n\n def keyPressEvent(self, e: QKeyEvent) -> None:\n if e.key() == Qt.Key_Escape:\n self.deactivate()\n self._iface.mapCanvas().unsetMapTool(self)\n return super().keyPressEvent(e)\n\n def draw_los(self):\n\n canvas_crs = self._canvas.mapSettings().destinationCrs()\n\n if canvas_crs.isGeographic():\n self._iface.messageBar().pushMessage(\n \"LoS can be drawn only for projected CRS. Canvas is currently in geographic CRS.\",\n Qgis.Critical,\n duration=5)\n return\n\n if self._point:\n self._los_rubber_band.hide()\n self._los_rubber_band.setToGeometry(QgsGeometry(),\n self._canvas.mapSettings().destinationCrs())\n angles = np.arange(self._widget.min_angle,\n self._widget.max_angle + 0.000000001 * self._widget.angle_step,\n step=self._widget.angle_step).tolist()\n round_digits = get_max_decimal_numbers(\n [self._widget.min_angle, self._widget.max_angle, self._widget.angle_step])\n angles = round_all_values(angles, round_digits)\n size_constant = 1\n for angle in angles:\n new_point = self._point.project(size_constant, angle)\n geom = QgsGeometry.fromPolylineXY([self._point, new_point])\n geom = geom.extendLine(0, self._widget.length - size_constant)\n self._los_rubber_band.addGeometry(geom,\n self._canvas.mapSettings().destinationCrs())\n self._los_rubber_band.show()\n","sub_path":"los_tools/gui/los_without_target_visualization/los_without_target.py","file_name":"los_without_target.py","file_ext":"py","file_size_in_byte":4723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"537633421","text":"import numpy as np\nfrom scipy.stats import truncnorm\nfrom scipy.stats import poisson\nfrom scipy.stats import norm\nimport random\nimport math\n\n\nclass sSInstance:\n n = 8\n capacity = 125\n ch = 1.0\n cp = 10.0\n co = 10.0\n cr = 0\n init_inv = 0\n max_demand = 60\n prob = []\n max_inv_level = n * max_demand\n min_inv_level = -n * max_demand\n rev_time = []\n means = []\n cv = 1/3.0\n\n def max_inv_bouding(self, threshold):\n demand = [0 for _ in range(self.n * self.max_demand + 1)]\n for i in range(self.max_demand + 1):\n demand[i] = self.prob[0][i]\n for i in range(1, self.n):\n temp = [0 for _ in range(self.n * self.max_demand + 1)]\n for a in range((self.n - 1) * self.max_demand + 1):\n for b in range(self.max_demand + 1):\n # print(\"a = \" + str(a) + \" b = \" + str(b) + \" r = \" + str(r))\n temp[a + b] += self.prob[i][b] * demand[a]\n demand = temp\n j = self.n * self.max_demand\n pdf_dem = demand[j]\n while pdf_dem < threshold:\n j -= 1\n pdf_dem += demand[j - 1]\n\n self.max_inv_level = j\n self.min_inv_level = -j + self.init_inv\n\n\n\n # these functions generate different demands probabilities\n def gen_poisson_probability(self, mu):\n self.prob = [[0.0 for _ in range(0, self.max_demand +1)] for _ in range(self.n)]\n for i in range(self.n):\n for j in range(0, self.max_demand +1):\n self.prob[i][j] = poisson.pmf(j, mu)\n\n def gen_fix_probability(self, avg):\n self.prob = [[0.0 for _ in range(0, self.max_demand +1)] for _ in range(self.n)]\n if not (2 <= avg <= self.max_demand - 2):\n print(\"average outside interval allowed\")\n return\n for i in range(self.n):\n self.prob[i][avg-2] = 0.1\n self.prob[i][avg-1] = 0.2\n self.prob[i][avg] = 0.4\n self.prob[i][avg+1] = 0.2\n self.prob[i][avg+2] = 0.1\n\n def gen_bin_probability(self):\n if self.max_demand != 1:\n print(\"Error - In binary demand max demand has to be equal to 1\")\n self.prob = [[0.5, 0.5]for _ in range(self.n)]\n\n def gen_non_stationary_normal_demand(self, threshold):\n if len(self.means) != self.n:\n print(\"wrong size self.means vector\")\n return\n self.max_demand = int(norm(loc = max(self.means), scale = self.cv*max(self.means)).ppf(1-threshold))\n self.prob = [[0.0 for _ in range(0, self.max_demand +1)] for _ in range(self.n)]\n for i in range(self.n):\n norm_dist = norm(loc=self.means[i], scale = self.cv*self.means[i])\n for j in range(self.max_demand +1):\n self.prob[i][j] = norm_dist.pdf(j)\n self.prob[i] = self.prob[i]/sum(self.prob[i])\n\n def gen_non_stationary_poisson_demand(self, threshold): ## fix this VISE\n if len(self.means) != self.n:\n print(\"wrong size self.means vector\")\n return\n self.max_demand = int(poisson.ppf(loc = 0 , mu = max(self.means), q = (1-threshold)))\n self.prob = [[0.0 for _ in range(0, self.max_demand +1)] for _ in range(self.n)]\n for i in range(self.n):\n norm_dist = norm(loc=self.means[i], scale = self.cv*self.means[i])\n for j in range(self.max_demand +1):\n if self.means[i] != 0 :\n self.prob[i][j] = poisson.pmf(k = j, mu = self.means[i])\n else:\n self.prob[i][j] = poisson.pmf(k = j, mu = 0.1)\n\n self.prob[i] = self.prob[i]/sum(self.prob[i])\n\n def gen_means(self, type):\n self.means = [0 for _ in range(self.n)]\n if type == \"LCYA\":\n for i in range(self.n):\n self.means[i] = round(19 * math.exp(-(i-12)**2) / 5)\n elif type == \"SIN1\":\n for i in range(self.n):\n self.means[i] = round(70 * math.sin(0.8*(i+1)) +80)\n # Form Rossi et al. 2011\n elif type == \"P1\": # Form Rossi et al. 2011\n for i in range(self.n):\n self.means[i] = round(50 * (1 + math.sin(math.pi * i /6)))\n elif type == \"P2\": # Form Rossi et al. 2011\n for i in range(self.n):\n self.means[i] = round(50 * (1 + math.sin(math.pi * i /6))) + i\n elif type == \"P3\": # Form Rossi et al. 2011\n for i in range(self.n):\n self.means[i] = round(50*(1 + math.sin(math.pi * i /6))) + self.n - i\n elif type == \"P4\": # Form Rossi et al. 2011\n for i in range(self.n):\n self.means[i] = round(50 * (1 + math.sin(math.pi * i /6))) + min(i, self.n-i)\n elif type == \"P5\": # Form Rossi et al. 2011\n for i in range(self.n):\n self.means[i] = random.randint(0,100)\n # NEW PATTERNS FOR THE PAPER\n elif type == \"STA\": # new patterns for the paper\n for i in range(self.n):\n self.means[i] = 50\n elif type == \"INC\":\n for i in range(self.n):\n self.means[i] = round(i * 100 / (self.n-1))\n elif type == \"DEC\":\n for i in range(self.n):\n self.means[i] = round(100 - i * 100 / (self.n-1))\n elif type == \"LCY1\":\n c = 0\n for i in range(int(self.n / 3)):\n self.means[i] = round((i + 0.5) * 225 / self.n)\n for i in range(int(self.n /3), 2 * int(self.n /3) + self.n % 3):\n self.means[i] = 75\n for i in range(2 * int(self.n /3) + self.n % 3, self.n):\n self.means[i] = round((int(self.n / 3) - 0.5 - c) * 225 / self.n)\n c+=1\n elif type == \"LCY2\":\n c = 0\n for i in range(int(self.n / 2)):\n self.means[i] = round(i * 100 / (int(self.n/2)-1))\n for i in range(int(self.n /2), self.n):\n self.means[i] = round(100 - c * 100 / (int(self.n/2+0.5)-1))\n c+=1\n elif type == \"ERR\":\n for i in range(self.n):\n self.means[i] = random.randint(0,100)\n elif type == \"SIN\":\n for i in range(self.n):\n self.means[i] = round(50 * (1 + math.sin(math.pi * i /6)))\n\n return self.means\n\n\n\n def gen_demand(self, t):\n val = random.random() # generate a number in [0.0, 1.0) range\n pdf = 0.0\n for i in range(0, self.max_demand+1):\n pdf = pdf + self.prob[t][i]\n if pdf >= val:\n return i\n return self.max_demand\n\n\n","sub_path":"instance.py","file_name":"instance.py","file_ext":"py","file_size_in_byte":6616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"76460646","text":"import sys\nsys.stdin = open(\"swimming_centre_input.txt\",\"r\")\n\ndef f(n,s,d,m,m3):\n global minV\n if n>12:\n if minV >s:\n minV=s\n \n else:\n f(n+1,s+table[n]*d,d,m,m3)\n f(n+1,s+m,d,m,m3)\n f(n+3,s+m3,d,m,m3)\n return minV\n\n\nT = int(input())\nfor tc in range(1,T+1):\n d,m,m3,y = map(int,input().split())\n table = [0] + list(map(int,input().split()))\n minV = y\n print(f(1,0,d,m,m3))\n","sub_path":"Solving Club/휴강기간/swimming_centre_live.py","file_name":"swimming_centre_live.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"333305934","text":"__module_name__ = 'environment'\n__module_version__ = '1.0'\n__module_description__ = 'Weather, time of day, local features, etc.'\n__module_author__ = 'Allen Stetson'\n\nfrom random import randint\nimport sys\nsys.path.insert(0, '/work/td/xchat/mod/')\nfrom dnd.utils import ProbabilityArray\nfrom dnd.locations import LocationGenerator\n\nclass EnvirGenerator(object):\n def __init__(self):\n # Keep these sorted... sorta.\n self.times = [\"dawn\", \"morning\", \"afternoon\", \"day\", \"dusk\", \"twilight\", \"evening\", \"midnight\", \"night\"]\n # Initialize settings.\n self.randNum = randint(1,100)\n self.timeOfDay = self.getTimeOfDay()\n self.temperature = self.getTemperature()\n self.conditionType = None\n self.condition = self.getCondition()\n self.nearbyFeature = None\n self.location = self.getLocation()\n self.moonPhase = self.getMoon() \n \n def getTimeOfDay(self):\n # night, dawn, morning, day, afternoon, dusk, twilight, evening, midnight\n self.timeOfDay = self.times[randint(0,len(self.times)-1)]\n return self.timeOfDay\n \n def getTemperature(self):\n # Warm, cold, hot, frigid, cool,\n temps = [('frigid',1),('cold',2),('cool',3),('warm',3),('hot',2),('blisteringly hot',1)]\n probabilityArray = ProbabilityArray()\n temps = probabilityArray.create(temps)\n if self.randNum == 1:\n temps = ['frigid','blisteringly hot']\n self.temperature = temps[randint(0,len(temps)-1)]\n return self.temperature\n \n def getCondition(self):\n # Sunny, windy, rainy, snowy, still, blustery, clear, torrentially rainy, blizzardy, foggy, smoky\n temp = self.temperature\n conditions = [('windy','wind'),('rainy','wet'),('still','norm'),('blustery','wind'),('clear','norm'),\n ('smoky','smoke'),('hazy','norm')]\n if temp == \"frigid\" or temp == \"cold\":\n conditions.extend([('hailing','cold'), ('snowy','cold'), ('blizzarding','cold'),\n ('torrentially rainy','cold'),('foggy','cold'),('drizzly','cold')])\n elif temp == \"hot\" or temp == \"blisteringly hot\":\n conditions.extend([('stagnant','hot'), ('dusty','hot')])\n else:\n conditions.extend([('torrentially rainy','wet'), ('foggy','norm'), ('drizzly','wet')])\n (self.condition,self.conditionType) = conditions[randint(0,len(conditions)-1)]\n return self.condition\n \n def getLocation(self, conditionType=None):\n if not conditionType:\n conditionType = self.conditionType\n locationGenerator = LocationGenerator(conditionType=conditionType)\n self.location = locationGenerator.location\n self.getNearbyFeature()\n return self.location\n \n def getNearbyFeature(self, location=None):\n if not location:\n location = self.location\n locationGenerator = LocationGenerator(location=location)\n self.nearbyFeature = locationGenerator.nearbyFeature\n return self.nearbyFeature\n \n def getMoon(self):\n phases = ['waxing','quarter','half','gibbous','full','waning','crescent','new']\n phase = phases[randint(0,len(phases)-1)]\n return phase\n \n def getWeather(self):\n \"\"\"\n Based on our initial \"roll of the dice\" (random int 0-100), if it is exceptionally low,\n death is imminent. Exceptionally high, and special things result. In the middle, and you\n get a more normal weather event.\n\n Within the normal weather event, things like the time of day and location are used to generate\n an appropriate event.\n :return: printable string for xchat\n :rtype: str\n \"\"\"\n # DEATH\n if self.randNum == 1:\n printStr = \"It is an unbearably %s %s. It takes all of your effort to stave off death from this %s weather, \" % (self.temperature,self.timeOfDay,self.condition)\n printStr += \"and soon your strength will run out. Your bones will litter the %s where you lay.\" % (self.location)\n return(printStr)\n # PARADISE\n elif self.randNum == 95:\n printStr = \"It is a perfect %s in the %s. The weather could not be more to your liking. \" % (self.timeOfDay, self.location)\n printStr += \"You can not help but wonder if you hold the favor of your gods, at the moment.\"\n return(printStr)\n # DENIAL\n elif self.randNum > 95:\n printStr = \"It is a quiet, air-conditioned %s in the workplace. \" % (self.timeOfDay)\n printStr += \"The ambient hum of machines fills the air with soothing white noise, its haze broken only by occasional echoes of coworker dialogue in the distant cubicles. \"\n printStr += \"You recline comfortably in your office chair, toggling idly between desktops as your mind drifts to far-off fantasy lands, \"\n printStr += \"pondering what the future will bring and \"\n if self.timeOfDay in self.times[:2]:\n printStr += \"what the fates have decreed for lunch today.\"\n elif self.timeOfDay in self.times[-2:]:\n printStr += \"when you can stop burning the midnight oil.\"\n else:\n printStr += \"digesting the plate of lunch you consumed earlier.\"\n return(printStr)\n # NORMAL (not DEATH, PARADISE, or DENIAL)\n else:\n # UNDERDARK\n if self.location == \"underdark\":\n printStr = \"It is a %s %s %s in the world above, though down here in the %s it is always the same.\" % (self.temperature, self.condition, self.timeOfDay, self.location)\n if self.conditionType == \"cold\":\n printStr += \" The cold from the %s seems to radiate downward, although the torches provide a comforting warmth in this otherwise \" % self.nearbyFeature\n printStr += \"unwelcoming world.\"\n elif self.conditionType == \"hot\":\n printStr += \" The heat from the %s seems to radiate downward, although the dark shadows provide a comforting respite in this otherwise \" % self.nearbyFeature\n printStr += \"unwelcoming world.\"\n else:\n printStr += \" The looming shadows, oppressive silence, and stench of this world make you long for the %s.\" % self.nearbyFeature\n return(printStr)\n # NOT UNDERDARK\n else:\n printStr = \"It is a %s %s %s in the %s.\" % (self.temperature, self.condition, self.timeOfDay, self.location)\n if self.location == \"coast\":\n printStr = printStr.replace(\" in \", \" on \")\n ## MOON\n if self.timeOfDay in ['night','twilight','evening','midnight']:\n if not self.conditionType == \"wet\":\n if not self.moonPhase == \"new\":\n typesOfGlows = ['a calming','an eerie','an otherworldly','a dreamy']\n glow = typesOfGlows[randint(0,len(typesOfGlows)-1)]\n printStr += \" The %s moon casts %s glow on the landscape.\" % (self.moonPhase, glow)\n if self.moonPhase == \"full\":\n printStr += \" The ominous howl of a nearby creature fills you with unease.\"\n ## WET\n if self.conditionType == \"wet\":\n printStr += \" Rain pelts the %s all around.\" % self.nearbyFeature\n if self.randNum < 4:\n printStr += \" Floodwaters rise ever higher. You search for nearby debris on which to cling for safety.\"\n elif self.randNum < 12:\n printStr += \" The deafening peal of thunder reverberates off of the %s nearby as blinding flash of lightning strikes not far away.\" % self.nearbyFeature\n elif self.temperature == \"hot\":\n printStr += \" The cool rain brings you welcome relief from the heat of the %s.\" % self.timeOfDay\n elif self.condition == \"rainy\":\n printStr += \" You turn your face to the sky and soak in the cleansing rain.\"\n else:\n printStr += \" You seek shelter anywhere you can in an attempt to stay dry.\"\n ## COLD\n elif self.conditionType == \"cold\":\n if self.randNum <= 30:\n printStr += \" A chill radiates off of the %s around you. You pull your coat close to your body in an attempt to keep warm.\" % self.nearbyFeature\n elif self.randNum < 50:\n printStr += \" You scowl at your empty tinderbox and useless flint as you plod through the %s trying to keep your body warm.\" % self.nearbyFeature\n elif self.randNum > 94:\n printStr += \" The cold seeping in through your armor could not feel better as it cools your sweaty, battle-worn muscles.\"\n else:\n printStr += \" Frost coats the nearby %s; your breath rises in visible puffs. You shiver involuntarily.\" % self.nearbyFeature\n ## WINDY\n elif self.conditionType == \"wind\":\n printStr += \" Winds beat the %s around you.\" % self.nearbyFeature\n if self.condition == \"blustery\":\n garmentType = ['garments','loincloth','cape','dark cloak','robes']\n garmentWorn = garmentType[randint(0,len(garmentType)-1)]\n printStr += \" You lean into the oncoming wind and push through, your %s flapping behind you.\" % garmentWorn\n else:\n hatType = ['hat','helmet','feather cap','hood','tricorn hat','head scarf']\n hatWorn = hatType[randint(0,len(hatType)-1)]\n actionType = ['soldier on', 'charge', 'dash', 'crawl', 'plod wearily', 'march']\n actionTaken = actionType[randint(0,len(actionType)-1)]\n printStr += \" You hold your %s with one hand as you %s into the wind.\" % (hatWorn, actionTaken)\n ## HOT\n elif self.conditionType == \"hot\" or self.temperature == \"blisteringly hot\":\n if self.randNum < 10:\n printStr += \" You impotently lick your sun-battered lips with your dry tongue as you feverishly look for any sign of fresh water.\"\n elif self.randNum < 20:\n printStr += \" A blinding light reflects off of the %s adjacent from you; a taunting reminder of the utter lack of respite from the heat.\" % self.nearbyFeature\n elif self.randNum > 95:\n printStr += \" The heat radiating off of the nearby %s makes the cool touch of the sparkling lake in which you swim all the more refreshing.\" % self.nearbyFeature\n else:\n printStr += \" An uncomfortable heat radiates off of the %s around you. Your sweaty clothes stick to you as you move.\" % self.nearbyFeature\n ## SMOKY\n elif self.condition == \"smoky\":\n thingsThatBurn = ['the nearby village',\"the enemy's encampment\", \"the vermin's nest\", 'what used to be your home','the weapons of war']\n if self.location == 'coast':\n thingsThatBurn.extend(['your defeated armada','the treasure galleon','the docks',\"the enemy's fleet\",'the shipwreck','the mermaid\\'s alcove'])\n elif self.location == 'mountains':\n thingsThatBurn.extend(['cliff dwellings',\"eagles' nests\",'the mining encampment','the log cabin'])\n elif self.location == 'grasslands':\n thingsThatBurn.extend(['the dry grass','the landscape','the catfolk village','the vineyard'])\n elif self.location == 'jungle':\n thingsThatBurn.extend([\"the hunter's perch\",'the hideout','the temple','the only bridge across the gaping chasm','the secret weapon'])\n elif self.location == 'city':\n thingsThatBurn.extend(['the tavern','the prison','the gallows','the district',\"the nobleman's abode\",'the slave quarters','the magic academy', \\\n 'the thieves guild','your home',\"that greedy bastard's home\",'the safehouse','the warehouse'])\n elif self.location == 'settlement':\n thingsThatBurn.extend(['the food storage','the church','the adjacent woods',\"the monster's body\",'the general store',\"the woodcutter's shop\"])\n elif self.location == 'fort':\n thingsThatBurn.extend([\"the captain's abode\",'the protective wall','the map room','the stables','the war machines','the weapons store',\"the raven's roost\"])\n elif self.location == 'marsh':\n thingsThatBurn.extend(['the hatchery', 'the dam', 'the coven house', 'the manticore den', 'the lizardfolk village',\"the green hag's cabin\"])\n elif self.location == 'meadow':\n thingsThatBurn.extend(['the windmill', 'the cottage'])\n elif self.location == 'forest':\n thingsThatBurn.extend(['the ettercap den'])\n elif self.location == 'hills':\n thingsThatBurn.extend([\"the hill giant's home\"])\n \n whatBurned = thingsThatBurn[randint(0,len(thingsThatBurn)-1)]\n \n if self.randNum < 4:\n printStr += \" The charred remains of %s mark your irrevocable decent into evil.\" % whatBurned\n elif self.randNum < 7:\n printStr += \" The charred remains of %s serve as a reminder of your unquestioning devotion to your deity.\" % whatBurned\n elif self.conditionType == 'cold' and self.randNum < 50:\n printStr += \" The smouldering remains of %s provide at least a little warmth to your otherwise numb body.\" % whatBurned\n elif self.conditionType == 'wet' and self.randNum < 50:\n printStr += \" The smouldering remains of %s sizzle with each drop of precipitation unlucky enough to target it.\" % whatBurned\n elif self.randNum < 30:\n printStr += \" The charred remains of %s scar the land.\" % whatBurned\n elif self.randNum < 60:\n printStr += \" The charred remains of %s fill you with pride.\" % whatBurned\n elif self.randNum < 80:\n printStr += \" The charred remains of %s fill you with rage.\" % whatBurned\n elif self.randNum < 99:\n printStr += \" The charred remains of %s fill you with sadness.\" % whatBurned\n elif self.randNum < 100:\n printStr += \" The thick hookah smoke still pleasantly burns your nostrils and massages your mind.\" % whatBurned\n \n return(printStr)\n","sub_path":"mod/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":14547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"59235497","text":"\n# coding: utf-8\n\n# In[1]:\n\n\n# imports\nimport numpy as np\nimport pandas as pd\n\n\n# In[2]:\n\n\n# read in data\ndf = pd.read_csv('./players_scores.csv').set_index('student_name')\nprint(df)\n\n\n# ## 1 Data Description\n\n# In[3]:\n\n\nscores = df['data_science_score']\n# scores = df['math_score']\n\n\n# #### 1. Calculate mean, median, and mode of Data Science scores\n\n# In[4]:\n\n\nprint('Mean: {}, Median: {}, Mode: {}'.format(\nscores.mean(), scores.median(), scores.mode().values))\n\n\n# #### 2. Calculate variance and standard deviation of Data Science scores\n\n# In[5]:\n\n\nprint('Variance: {}, Standard Deviation: {}'.format(\nscores.std()**2, scores.std()))\n\n\n# #### 3. Incremental Mean/Variance Functions\n\n# In[6]:\n\n\ndef incremental_mean(mu, n, x_new):\n return ((n*mu)+x_new)/(n+1)\n\n\n# In[7]:\n\n\ndef incremental_var(v, mu, n, x_new):\n mu_new = incremental_mean(mu, n, x_new)\n return ((n-1)*(v) + (x_new - mu)*(x_new - mu_new))/n\n\n\n# In[8]:\n\n\nu_prime = incremental_mean(mu=scores.mean(), n=len(scores), x_new=100)\nprint('u\\' = {}'.format(u_prime))\n\n\n# In[9]:\n\n\nv_prime = incremental_var(scores.std()**2, scores.mean(), len(scores), 100)\nprint('v\\' = {}'.format(v_prime))\n\n\n# #### Verify Function Correctness\n\n# In[10]:\n\n\nscores_plus = scores.append(pd.Series(100))\nprint('u\\' = {}'.format(scores_plus.mean()))\nprint('v\\' = {}'.format(scores_plus.std()**2))\n","sub_path":"ptinsley-HW1-Q1.py","file_name":"ptinsley-HW1-Q1.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"446582132","text":"# -*- coding: utf-8 -*-\n\"\"\"\n【概要】\n\n【注意】\n\n【動作環境】\nWindows / MacOS, python 2.7系列\n\n【作成者】\n芝(2016/04/04)\nshiba.shintaro@gmail.com\n\n【備考】\n\n\"\"\"\n\nimport pandas as pd\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy\nimport scipy.fftpack\n\n\ndf = pd.read_csv(\"20160312_170222.csv\", header=9, names=[\"ch1\", \"ch2\", \"ch3\", \"ch4\", \"ch5\"])\n\nch1 = np.array(df[\"ch1\"].as_matrix())\nch2 = np.array(df[\"ch2\"].as_matrix())\ntrig = np.array(df[\"ch5\"].as_matrix())\n\n\n\nstart = 0 # サンプリングする開始位置\nN = 256 # FFTのサンプル数\n\nX = np.fft.fft(x[start:start+N]) # FFT\n# X = scipy.fftpack.fft(x[start:start+N]) # scipy\n\nfreqList = np.fft.fftfreq(N, d=1.0/fs) # 周波数軸の値を計算\n# freqList = scipy.fftpack.fftfreq(N, d=1.0/ fs) # scipy版\n\namplitudeSpectrum = [np.sqrt(c.real ** 2 + c.imag ** 2) for c in X] # 振幅スペクトル\nphaseSpectrum = [np.arctan2(int(c.imag), int(c.real)) for c in X] # 位相スペクトル\n\n# 波形を描画\nsubplot(311) # 3行1列のグラフの1番目の位置にプロット\nplot(range(start, start+N), x[start:start+N])\naxis([start, start+N, -1.0, 1.0])\nxlabel(\"time [sample]\")\nylabel(\"amplitude\")\n\n# 振幅スペクトルを描画\nsubplot(312)\nplot(freqList, amplitudeSpectrum, marker= 'o', linestyle='-')\naxis([0, fs/2, 0, 50])\nxlabel(\"frequency [Hz]\")\nylabel(\"amplitude spectrum\")\n\n# 位相スペクトルを描画\nsubplot(313)\nplot(freqList, phaseSpectrum, marker= 'o', linestyle='-')\naxis([0, fs/2, -np.pi, np.pi])\nxlabel(\"frequency [Hz]\")\nylabel(\"phase spectrum\")\n\nshow()\n","sub_path":"src/readLFP.py","file_name":"readLFP.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"575467999","text":"from scipy.spatial.distance import euclidean\nfrom sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport numpy as np\n\nclass KNN():\n def __init__(self):\n self.X_train = None\n self.y_train = None\n #Given: X_train -> list of values\n # y_train -> list of different types of labels for values\n def fit(self, X_train, y_train):\n self.X_train = X_train\n self.y_train = y_train\n\n #Given: x -> a value\n #function: returns distances from that value\n def _get_distances(self, x):\n dists = []\n i = 0\n for y in self.X_train:\n dists.append((i, euclidean(x, y)))\n i += 1\n return dists\n #Given : dists -> list of distaces from point\n # k -> quantity of top distances wanted returned\n #get nearest neighbors\n #return k amount of them\n def _get_k_nearest(self, dists, k):\n k_nearest = sorted(dists, key = lambda x : x[1])\n return k_nearest[:k]\n\n #Given: none\n #Return the label that is most common from nearest neighbors\n def _get_label_prediction(self, k_nearest):\n labels = [self.y_train[i] for i, _ in k_nearest]\n return np.argmax(np.bincount(labels))\n\n #Given: X_test -> test values\n # k -> number of nearest neighbors\n #return list of labels for nearest neighbors at each test point\n def predict(self, X_test, k = 3):\n preds = []\n for x in X_test:\n dists = self._get_distances(x)\n nearest = self._get_k_nearest(dists, k)\n preds.append(self._get_label_prediction(nearest))\n return preds\n\n\niris = load_iris()\ndata = iris.data\ntarget = iris.target\n\nX_train, X_test, y_train, y_test = train_test_split(data, target, random_state = 0, train_size = 0.25)\n\nknn = KNN()\nknn.fit(X_train, y_train)\npreds = knn.predict(X_test, 3)\n\nprint(\"Testing Accuracy: {}\".format(accuracy_score(preds, y_test)))\n","sub_path":"week-8/knn/K-NearestNeighbors-Lab.py","file_name":"K-NearestNeighbors-Lab.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"438723959","text":"\r\noperator_attributes_dictionary = {\r\n '+': (1, False),\r\n '-': (1, True),\r\n '*': (2, False),\r\n '/': (2, False),\r\n '^': (3, False),\r\n '~': (6, True),\r\n '%': (4, False),\r\n '!': (6, True),\r\n '@': (5, False),\r\n '$': (5, False),\r\n '&': (5, False)\r\n}\r\n\r\n\r\ndef check_power(char_of_operator):\r\n (power, do_not_need) = operator_attributes_dictionary.get(char_of_operator)\r\n return power\r\n\r\n\r\ndef check_if_can_be_duplicated(char_of_operator):\r\n (do_not_need, can_be_duplicated) = \\\r\n operator_attributes_dictionary.get(char_of_operator)\r\n return can_be_duplicated\r\n","sub_path":"Omega/operator_attributes.py","file_name":"operator_attributes.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"588470101","text":"import numpy as np\nimport cv2\n\n# reading image from a particular location\n#It's always better to give the whole path of the image location\n#the format is img=imread('<image-path>,offset) .. offset to be set to zero to get an grayscale version of image\n#if you just want to load the picture as it is there is no need to give offset value or set it to 255\nimg = cv2.imread('/<username>/Desktop/OpenCV/opencv/myprograms/iphone.jpeg',0) \n\n#displays the image\n#size of window is automatically set to fit the size of image\ncv2.imshow('image',img)\n\n#waitKey(0) function is necessary to keep the image window open\n#add & 0xFF only on 64 bit OS, not necessary for 32 bit one\nk = cv2.waitKey(0) & 0xFF\n\n#waiting for a keystroke\n#if ESC is pressed, image window just exits, 27 is ASCII code for ESC character\n#if key 's' is pressed image is saved to the the directory of existing rgb image and image window exits\nif k == 27: # wait for ESC key to exit\n cv2.destroyAllWindows()\nelif k == ord('s'): # wait for 's' key to save and exit\n cv2.imwrite('iphonegray.png',img)\n cv2.destroyAllWindows()\n","sub_path":"RGBtoGREY.py","file_name":"RGBtoGREY.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"177975235","text":"import logging\n\nfrom chatterbot.conversation import Statement\nfrom flask_restful import Resource\n\nfrom .nameparser import extract_names_regex\nfrom .parsers import query_parser, teach_parser, auth_parser\nfrom .logic.requests import Request, text, InputRequest, InvalidTokenError\nfrom common.utils import obscure\n\nlog = logging.getLogger(__name__)\n\n\nclass WaldurResource(Resource):\n \"\"\"\n Parent class of all Waldur resources\n \"\"\"\n def __init__(self, chatbot):\n \"\"\"\n :param chatbot: Chatterbot bot\n \"\"\"\n self.chatbot = chatbot\n self.response = None\n self.code = 200\n\n\nclass Query(WaldurResource):\n \"\"\"\n Resource to get answers from the underlying Chatterbot\n \"\"\"\n\n def __init__(self, chatbot, tokens_for_input):\n \"\"\"\n :param tokens_for_input: dict of {token: InputRequest, ...}\n \"\"\"\n super(Query, self).__init__(chatbot)\n self.tokens_for_input = tokens_for_input\n\n args = query_parser.parse_args()\n self.query = args.query\n self.token = None\n\n if args.Authorization is not None:\n if args.Authorization.startswith(\"token \"):\n self.token = args.Authorization[6:]\n else:\n self.token = args.Authorization\n\n log.info(f\"Query initialized with {{query: '{self.query}', token: '{obscure(self.token)}'}}\")\n\n if log.isEnabledFor(logging.DEBUG):\n obscured_tokens = {obscure(x): self.tokens_for_input[x] for x in self.tokens_for_input}\n log.debug(f\"Tokens waiting for input: {obscured_tokens}\")\n\n def post(self):\n \"\"\"\n Entry point for POST /\n Gets a response statement from the bot\n :param: query - question/input for bot\n :param: token - Waldur API token\n :return: response, code\n \"\"\"\n try:\n if self.token is not None and self.token in self.tokens_for_input:\n self._handle_input()\n else:\n self._handle_query()\n except InvalidTokenError:\n self.response = dict(message='Invalid Waldur API token')\n self.code = 401\n\n log.info(f\"Query response: {self.response} code: {self.code}\")\n return self.response, self.code\n\n def _handle_query(self):\n\n # Todo: Make it look better\n names_excluded = self.query\n for x in extract_names_regex(self.query):\n for splitted in x.split():\n names_excluded = names_excluded.replace(splitted, \"\").strip()\n names_excluded = \" \".join(names_excluded.split())\n \n bot_response = str(self.chatbot.get_response(names_excluded))\n log.debug(f\"Bot response: '{bot_response}'\")\n\n if bot_response.startswith(\"REQUEST\"):\n req = Request\\\n .from_string(bot_response)\\\n .set_token(self.token)\\\n .set_original(self.query)\n\n self.response = req.process()\n\n if isinstance(req, InputRequest):\n self.tokens_for_input[self.token] = req\n\n else:\n self.response = text(bot_response)\n\n def _handle_input(self):\n req = self.tokens_for_input[self.token]\\\n .set_input(self.query)\n\n self.response = req.process()\n\n if not req.waiting_for_input:\n del self.tokens_for_input[self.token]\n\n\nclass Teach(WaldurResource):\n \"\"\"\n Resource to give answers to the underlying Chatterbot\n \"\"\"\n\n def __init__(self, chatbot):\n super(Teach, self).__init__(chatbot)\n\n args = teach_parser.parse_args()\n self.statement = args.statement\n self.previous_statement = args.previous_statement\n\n log.info(f\"Teach initialized with {{statement: '{self.statement}', \"\n f\"previous_statement: '{self.previous_statement}'}}\")\n\n def post(self):\n \"\"\"\n Entry point for POST /teach/\n Teaches the bot that 'statement' is a valid response to 'previous_statement'\n :param: statement\n :param: previous_statement\n :return: response, code\n \"\"\"\n\n self.chatbot.learn_response(Statement(self.statement), Statement(self.previous_statement))\n return text(f\"Added '{self.statement}' as a response to '{self.previous_statement}'\"), 200\n\n\nclass Authenticate(Resource):\n \"\"\"\n Resource to intermediate token to frontend\n Not very secure\n \"\"\"\n\n def __init__(self, auth_tokens):\n \"\"\"\n :param auth_tokens: dict of {user_id: token, ...}\n \"\"\"\n self.auth_tokens = auth_tokens\n\n def post(self, user_id):\n \"\"\"\n Entry point for POST /auth/<user_id>\n :param user_id: user_id to tie the token to\n :param: token from POST body\n :return: response, code\n \"\"\"\n args = auth_parser.parse_args()\n\n log.info(f\"token {obscure(args.token)} received for {user_id}\")\n\n self.auth_tokens[user_id] = args.token\n\n return {'message': 'ok'}, 200\n\n def get(self, user_id):\n \"\"\"\n Entry point for GET /auth/<user_id>\n :param user_id: user_id to get the token for\n :return: response, code\n \"\"\"\n log.info(f\"token asked for {user_id}\")\n\n if user_id in self.auth_tokens:\n token = self.auth_tokens[user_id]\n del self.auth_tokens[user_id]\n return {'token': token}, 200\n else:\n return {'message': f\"No token for {user_id}\"}, 404\n","sub_path":"backend/waldur/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":5488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"121293852","text":"\n# coding: utf-8\n\n# In[3]:\n\n\n\nfrom sklearn import metrics\nfrom sklearn.metrics import precision_recall_fscore_support as score\n\n\n\n\n# In[6]:\n\nclass accu_scores:\n def __init__(self,y_test, y_pred_class):\n self.y_test = y_test\n self.y_pred_class = y_pred_class\n self.simpleAccu()\n self.confMat()\n \n precision, recall, fscore, support = score(y_test, y_pred_class)\n\n print('precision: {}'.format(precision))\n print('recall: {}'.format(recall))\n print('fscore: {}'.format(fscore))\n print('support: {}'.format(support))\n def simpleAccu(self):\n print(\"simple accuracy : \",metrics.accuracy_score(self.y_test, self.y_pred_class,))\n def confMat(self):\n print(\"confusion matrix : \", metrics.confusion_matrix(self.y_test, self.y_pred_class))\n\n \n\n\n# In[ ]:\n\n\n\n","sub_path":"Multi Class/AccuracyMultiCLF.py","file_name":"AccuracyMultiCLF.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"494636187","text":"\"\"\"Sliding window maximum\nleetcode\n\nGiven an array nums, there is a sliding window of size k which is moving from\nthe very left of the array to the very right. You can only see the k numbers in\nthe window. Each time the sliding window moves right by one position.\n\nFor example,\nGiven nums = [1,3,-1,-3,5,3,6,7], and k = 3.\n\nWindow position Max\n--------------- -----\n[1 3 -1] -3 5 3 6 7 3\n 1 [3 -1 -3] 5 3 6 7 3\n 1 3 [-1 -3 5] 3 6 7 5\n 1 3 -1 [-3 5 3] 6 7 5\n 1 3 -1 -3 [5 3 6] 7 6\n 1 3 -1 -3 5 [3 6 7] 7\nTherefore, return the max sliding window as [3,3,5,5,6,7].\n\"\"\"\n\nfrom collections import deque\n\nclass Solution(object):\n def maxSlidingWindow(self, nums, k):\n \"\"\"Return sequence of max value of all slicding windows from left to right.\n\n 1. Use deque for window so popleft is really O(1). For list it's O(n)\n 2. Keep tracking max window value. If the element is about to enqueue is\n larger or equal than max value, update max value. If the element is about\n to be dequed is equal to max value, do the max for new window\n\n The worst case is O(kn), e.g., [5, 4, 3, 2, 1] because every time you move the\n window, the popped one is max value of current window then max will be called\n If Queue.PriofityQueue is used to keep track of window, you can have max with\n O(n), but it's hard to remove element by it's index.\n\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n if not nums:\n return []\n\n if len(nums) < k:\n raise ValueError('Invalid window size: {}'.format(k))\n\n window = deque(nums[:k])\n current_max = max(window)\n max_windows = [current_max]\n\n for i, val in enumerate(nums, start=k):\n popped = window.popleft()\n window.append(val)\n if val >= current_max:\n current_max = val\n elif popped == current_max:\n current_max = max(window)\n else:\n pass\n\n max_windows.append(current_max)\n\n return max_windows[k:]\n\n\ndef main():\n sol = Solution()\n nums = [1, 3, -1, -3, 5, 3, 6, 7]\n k = 3\n assert sol.maxSlidingWindow(nums, k) == [3, 3, 5, 5, 6, 7]\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"arr/leetcode_Sliding_Window_Maximum.py","file_name":"leetcode_Sliding_Window_Maximum.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"281502196","text":"import threading\n\nfrom villas.node.node import Node\nfrom villas.controller.components.manager import Manager\nfrom villas.controller.components.gateways.villas_node import VILLASnodeGateway\n\n\nclass VILLASnodeManager(Manager):\n\n def __init__(self, **args):\n\n self.autostart = args.get('autostart', False)\n self.api_url = args.get('api_url', 'http://localhost:8080')\n self.api_url_external = args.get('api_url_external', self.api_url)\n\n args['api_url'] = self.api_url\n\n self.thread_stop = threading.Event()\n self.thread = threading.Thread(target=self.reconcile_periodically)\n\n self.node = Node(**args)\n\n self._status = self.node.status\n\n args['uuid'] = self._status.get('uuid')\n\n super().__init__(**args)\n\n def reconcile_periodically(self):\n while not self.thread_stop.wait(2):\n self.reconcile()\n\n def reconcile(self):\n try:\n self._status = self.node.status\n self._nodes = self.node.nodes\n\n for node in self._nodes:\n self.logger.debug('Found node %s on gateway: %s',\n node['name'], node)\n\n if node['uuid'] in self.components:\n ic = self.components[node['uuid']]\n\n # Update state\n ic.change_state(node['state'])\n else:\n ic = VILLASnodeGateway(self, node)\n\n self.add_component(ic)\n\n self.change_state('running')\n\n except Exception as e:\n self.change_to_error('failed to reconcile',\n exception=str(e),\n args=str(e.args))\n\n @property\n def status(self):\n status = super().status\n\n status['status']['villas_node_version'] = self._status.get('version')\n\n return status\n\n def on_ready(self):\n if self.autostart and not self.node.is_running():\n self.start()\n\n self.thread.start()\n\n super().on_ready()\n\n def on_shutdown(self):\n self.thread_stop.set()\n self.thread.join()\n\n return super().on_shutdown()\n\n def start(self, payload):\n self.node.start()\n\n self.change_state('starting')\n\n def stop(self, payload):\n if self.node.is_running():\n self.node.stop()\n\n self.change_state('idle')\n\n # Once the gateway shutsdown, all the gateway nodes are also shutdown\n for node in self.nodes:\n node.change_state('shutdown')\n\n def pause(self, payload):\n self.node.pause()\n\n self.change_state('paused')\n\n # Once the gateway shutsdown, all the gateway nodes are also shutdown\n for node in self.nodes:\n node.change_state('paused')\n\n def resume(self, payload):\n self.node.resume()\n\n def reset(self, payload):\n self.node.restart()\n","sub_path":"villas/controller/components/managers/villas_node.py","file_name":"villas_node.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"132058052","text":"assignments = []\nrows = 'ABCDEFGHI'\ncols = '123456789'\n\ndef cross(A, B):\n \"\"\"Cross product of elements in A and elements in B\n \"\"\"\n return [s+t for s in A for t in B]\n\n# set up all boxe labels, units, and peers dictionary\nboxes = cross(rows, cols)\nrow_units = [cross(r, cols) for r in rows]\ncolumn_units = [cross(rows, c) for c in cols]\nsquare_units = [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')]\ndiagonal_units = [list(map(lambda x:\"\".join(x),list(zip(rows,cols)))),list(map(lambda x:\"\".join(x),list(zip(rows,reversed(cols)))))]\nunitlist = row_units + column_units + square_units + diagonal_units # list of all units\nunits = dict((s, [u for u in unitlist if s in u]) for s in boxes) # mapping of box -> the units the box belongs to\npeers = dict((s, set(sum(units[s],[]))-set([s])) for s in boxes) # mapping of box -> the peers of the box\n\ndef assign_value(values, box, value):\n \"\"\"\n Please use this function to update your values dictionary!\n Assigns a value to a given box. If it updates the board record it.\n \"\"\"\n values[box] = value\n if len(value) == 1:\n assignments.append(values.copy())\n return values\n\ndef naked_twins(values):\n \"\"\"Eliminate values using the naked twins strategy.\n Args:\n values(dict): a dictionary of the form {'box_name': '123456789', ...}\n\n Returns:\n the values dictionary with the naked twins eliminated from peers.\n \"\"\"\n\n # Find all instances of naked twins\n for unit in unitlist:\n for i in range(9):\n box1 = unit[i]\n if len(values[box1]) != 2:\n continue\n for j in range(i + 1, 9):\n box2 = unit[j]\n if values[box1] == values[box2]: # found twins\n for peer in (set(unit) - set([box1, box2])): # eliminate the naked twins as possibilities for their peers\n for digit in values[box1]:\n values = assign_value(values, peer, values[peer].replace(digit,''))\n break\n\n return values\n\ndef grid_values(grid):\n \"\"\"\n Convert grid into a dict of {square: char} with '123456789' for empties.\n Args:\n grid(string) - A grid in string form.\n Returns:\n A grid in dictionary form\n Keys: The boxes, e.g., 'A1'\n Values: The value in each box, e.g., '8'. If the box has no value, then the value will be '123456789'.\n \"\"\"\n assert len(grid)==81\n available = '123456789'\n values = []\n for c in grid:\n if c == '.':\n values.append(available)\n else:\n values.append(c)\n return dict(zip(boxes,values))\n\ndef display(values):\n \"\"\"\n Display the values as a 2-D grid.\n Args:\n values(dict): The sudoku in dictionary form\n \"\"\"\n width = 1+max(len(values[s]) for s in boxes)\n line = '+'.join(['-'*(width*3)]*3)\n for r in rows:\n print(''.join(values[r+c].center(width)+('|' if c in '36' else '')\n for c in cols))\n if r in 'CF': print(line)\n return\n\ndef eliminate(values):\n \"\"\"Eliminate values from peers of each box with a single value.\n\n Go through all the boxes, and whenever there is a box with a single value,\n eliminate this value from the set of values of all its peers.\n\n Args:\n values: Sudoku in dictionary form.\n Returns:\n Resulting Sudoku in dictionary form after eliminating values.\n \"\"\"\n \n for box in values:\n if len(values[box]) == 1:\n digit = values[box]\n for peer in peers[box]:\n values = assign_value(values, peer, values[peer].replace(digit,'')) # eliminate this digit from values of peers\n \n return values\n\ndef only_choice(values):\n \"\"\"Finalize all values that are the only choice for a unit.\n\n Go through all the units, and whenever there is a unit with a value\n that only fits in one box, assign the value to this box.\n\n Args: \n values: Sudoku in dictionary form.\n Returns: \n Resulting Sudoku in dictionary form after filling in only choices.\n \"\"\"\n \n for unit in unitlist:\n digits = '123456789'\n for digit in digits:\n dplaces = [box for box in unit if digit in values[box]] # list of boxes where this digit is allowed in current unit\n if len(dplaces) == 1: # if there is only one box this digit could go in this unit\n values = assign_value(values, dplaces[0], digit) # assign this digit to this box\n\n return values\n\ndef reduce_puzzle(values):\n \"\"\"Reduce the search space for puzzle by repetitively applying eliminate, only choice, and naked twins strategy\n Stop iteration when there is no further progress\n Args: \n values: Sudoku in dictionary form.\n Returns:\n Resulting Sudoku after options are reduced\n \"\"\"\n stalled = False\n while not stalled:\n # Check how many boxes have a determined value\n solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])\n\n # Use the Eliminate Strategy to confine search space\n values = eliminate(values)\n\n # Use the Only Choice Strategy to confine search space\n values = only_choice(values)\n \n # Use the Naked Twins Strategy to confine search space\n values = naked_twins(values)\n\n # Check how many boxes have a determined value, to compare\n solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])\n # If no new values were added, stop the loop.\n stalled = solved_values_before == solved_values_after\n # Sanity check, return False if there is a box with zero available values:\n if len([box for box in values.keys() if len(values[box]) == 0]):\n return False\n return values\n\ndef get_best_box(values):\n \"\"\"identify the best box for starting depth first search, which is an unsolved box containing least options\n Args: \n values: Sudoku in dictionary form.\n Returns:\n string representing the best box to start depth first search\n \"\"\"\n min_len, best_box = min([(len(value),box)for box,value in values.items() if len(value) > 1])\n return best_box\n\n\ndef is_solved(values):\n \"\"\"determine whether a puzzle has been solved or not\n Args: \n values: Sudoku in dictionary form.\n Returns:\n bool: True for solved, False for unsolved\n \"\"\"\n unsolved_values = len([box for box in values.keys() if len(values[box]) != 1])\n return(unsolved_values == 0)\n\n\ndef search(values):\n \"\"\"Using depth-first search and propagation, create a search tree and solve the sudoku.\n Args: \n values: Sudoku in dictionary form.\n Returns:\n dictionary representing solved sodoku, or False if no solution is found\n \"\"\"\n # First, reduce the puzzle\n values = reduce_puzzle(values)\n \n # If previous step hits a dead-end, returns False\n if values is False:\n return False\n \n # If puzzle is solved, return the answer\n if is_solved(values):\n return values\n \n # Choose one of the unfilled squares with the fewest possibilities\n best_box = get_best_box(values)\n \n # Now use recursion to solve each one of the resulting sudokus, and if one returns a value (not False), return that answer!\n for digit in values[best_box]: # choose a possible value\n new_values = values.copy() # make a copy of the current puzzle for backtracking\n values[best_box] = digit # assign that value to the box\n ans = search(new_values) # start searching\n if ans: \n return ans # returns answer if puzzle is solved\n\n return False # sanity check, returns False if no solution is found\n \n\ndef solve(grid):\n \"\"\"\n Find the solution to a Sudoku grid.\n Args:\n grid(string): a string representing a sudoku grid.\n Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n Returns:\n The dictionary representation of the final sudoku grid. False if no solution exists.\n \"\"\"\n \n values = grid_values(grid)\n sudoku = search(values)\n if sudoku:\n return sudoku\n \n\nif __name__ == '__main__':\n \n grid = \"..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..\"\n \n diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n display(solve(diag_sudoku_grid))\n\n try:\n from visualize import visualize_assignments\n visualize_assignments(assignments)\n\n except SystemExit:\n pass\n except:\n print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')\n","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":8793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"97946405","text":"from django.urls import path\r\nfrom django.contrib import admin\r\n\r\nfrom .views import testview,login_view,register_view,logout_view\r\n\r\napp_name=\"translators\"\r\n\r\nurlpatterns = [\r\n \r\n path('', testview),\r\n path('login/',login_view, name='login'),\r\n path('register/', register_view, name='register'),\r\n path('logout/', logout_view, name='logout'),\r\n]","sub_path":"src/translators/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"259658251","text":"import re\nimport openpyxl as op\ndef exceliando():\n\texcel=op.load_workbook(\"nuevoenviolibrosya.xlsx\")\n\thoja=excel['Hoja1']\n\tlargo=len(hoja['A'])+1\n\tfor x in range(2,largo):\n\t\ttitul=hoja.cell(row=x,column=2).value\n\t\tprint(titul)\n\t\tprint(type(titul))\n\t\thoja.cell(row=x,column=2).value=corrector_titulo(titul)\n\t\tautor=hoja.cell(row=x,column=3).value\n\t\thoja.cell(row=x,column=3).value=corrector_titulo(autor)\n\n\texcel.save(\"nuevoenviolibrosya.xlsx\")\t\ndef corrector_titulo(pretitulo):\n\tretitulo=re.search(r\"(.*), ([LE][A-Z]\\w?)(.*)\", pretitulo)\n\tif retitulo == None:\n\t\tprepre=pretitulo\n\telse:\n\t\ttitulo=(retitulo[2]+\" \"+retitulo[1]+\" \"+retitulo[3]).strip()\n\t\tprepre=titulo\n\tretitulo2=re.search(r\"([\\w 0-9]*)(/L)([\\w 0-9]*)\",prepre)\n\tif retitulo2 == None:\n\t\treturn prepre.strip()\n\telse:\n\t\ttitulo=(retitulo2[1]+retitulo2[3]).strip()\n\t\treturn titulo\ndef corrector_autor(preautor):\t\n\treautor = re.search(r\"([\\w ]*), ([\\w ]*)\",preautor)\n\tif reautor == None:\n\t\treturn (preautor.strip(),preautor.strip())\n\telse:\t\n\t\tautor=reautor[2]+\" \"+reautor[1]\n\t\tapellido=reautor[1]\n\t\treturn (autor, apellido)\n#exceliando()\t\t","sub_path":"Principal/correctortitulo.py","file_name":"correctortitulo.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"231631036","text":"import time\nimport logging\nimport os\nimport uuid\nimport traceback\nimport pprint\nimport numpy as np\n\nfrom .advisor import make_advisor\n\nlogger = logging.getLogger(__name__)\n\nclass InvalidAdvisorException(Exception):\n pass\n\nclass InvalidProposalException(Exception):\n pass\n\nclass AdvisorService(object):\n def __init__(self):\n self._advisors = {}\n\n def create_advisor(self, knob_config, advisor_id=None):\n is_created = False\n advisor = None\n\n if advisor_id is not None:\n advisor = self._get_advisor(advisor_id)\n \n if advisor is None:\n advisor_inst = make_advisor(knob_config)\n advisor = self._create_advisor(advisor_inst, knob_config, advisor_id)\n is_created = True\n\n return {\n 'id': advisor.id,\n 'is_created': is_created # Whether a new advisor has been created\n }\n\n def delete_advisor(self, advisor_id):\n is_deleted = False\n\n advisor = self._get_advisor(advisor_id)\n\n if advisor is not None:\n self._delete_advisor(advisor)\n is_deleted = True\n\n return {\n 'id': advisor_id,\n # Whether the advisor has been deleted (maybe it already has been deleted)\n 'is_deleted': is_deleted \n }\n\n def generate_proposal(self, advisor_id):\n advisor = self._get_advisor(advisor_id)\n knobs = self._generate_proposal(advisor)\n\n return {\n 'knobs': knobs\n }\n\n # Feedbacks to the advisor on the score of a set of knobs\n # Additionally, returns another proposal of knobs after ingesting feedback\n def feedback(self, advisor_id, knobs, score):\n advisor = self._get_advisor(advisor_id)\n\n if advisor is None:\n raise InvalidAdvisorException()\n\n advisor_inst = advisor.advisor_inst\n advisor_inst.feedback(knobs, score)\n knobs = self._generate_proposal(advisor)\n\n return {\n 'knobs': knobs\n }\n\n def _create_advisor(self, advisor_inst, knob_config, advisor_id=None):\n advisor = Advisor(advisor_inst, knob_config, advisor_id)\n self._advisors[advisor.id] = advisor\n return advisor\n\n def _get_advisor(self, advisor_id):\n if advisor_id not in self._advisors:\n return None\n\n advisor = self._advisors[advisor_id]\n return advisor\n\n def _update_advisor(self, advisor, advisor_inst):\n advisor.advisor_inst = advisor_inst\n return advisor\n\n def _delete_advisor(self, advisor):\n del self._advisors[advisor.id]\n\n def _generate_proposal(self, advisor):\n knobs = advisor.advisor_inst.propose()\n\n # Simplify knobs to use JSON serializable values\n knobs = {\n name: self._simplify_value(value)\n for name, value\n in knobs.items()\n }\n\n return knobs\n\n def _simplify_value(self, value):\n # TODO: Support int64 & other non-serializable data formats\n if isinstance(value, np.int64):\n return int(value)\n\n return value\n\nclass Advisor(object):\n def __init__(self, advisor_inst, knob_config, advisor_id=None):\n if advisor_id is not None:\n self.id = advisor_id\n else:\n self.id = str(uuid.uuid4())\n \n self.advisor_inst = advisor_inst\n self.knob_config = knob_config\n","sub_path":"rafiki/advisor/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"484591488","text":"import numpy as np\n\ndef rgb2gray(image):\n size = image.shape\n if size[2] == 3:\n imout = np.zeros([size[0], size[1]])\n imout[:, :] = image[:, :, 1]\n return imout\n else:\n print(\"wrong image format\")\n return image","sub_path":"8 Year 3 University Python Head Pose Estimation Project/rgb2gray.py","file_name":"rgb2gray.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"650462616","text":"\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nimport scipy.stats as sta\r\nimport statsmodels.formula.api as smf\r\nfrom matplotlib.patches import Ellipse\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.metrics import (accuracy_score, mean_absolute_error,\r\n mean_squared_error, r2_score)\r\nfrom sklearn.model_selection import KFold, train_test_split\r\nfrom statsmodels.sandbox.regression.predstd import wls_prediction_std\r\nfrom statsmodels.stats.outliers_influence import summary_table\r\n\r\n# reading and loading into dataframe\r\ndf = pd.read_csv('P1training.csv')\r\ndf['date'] = pd.to_datetime(df['date'])\r\ndf['hour'] = pd.to_datetime(df['date']).dt.hour\r\n#df['day']= pd.to_datetime(df['date']).dt.dayofweek\r\ndf.head()\r\n\r\npvalue_threshold = 0.05\r\n\r\n\r\ndef forward_selected(data, response):\r\n \"\"\"Linear model designed by forward selection.\r\n\r\n Parameters:\r\n -----------\r\n data : pandas DataFrame with all possible predictors and response\r\n\r\n response: string, name of response column in data\r\n\r\n Returns:\r\n --------\r\n model: an \"optimal\" fitted statsmodels linear model\r\n with an intercept\r\n selected by forward selection\r\n evaluated by RMSE\r\n \"\"\"\r\n cols = [col for col in df.columns if response not in col]\r\n cols = [col for col in feature_cols if 'date' not in col]\r\n counter = cols.copy()\r\n # list to store selected predictors\r\n selected = []\r\n # variables to tore score:\r\n best = 0.0\r\n current = 0.0\r\n\r\n # split into test train\r\n kf = KFold(n_splits=10, shuffle=True, random_state=2)\r\n result = next(kf.split(df), None)\r\n train = df.iloc[result[0]]\r\n test = df.iloc[result[1]]\r\n # constructure formua\r\n for feat in cols:\r\n selected.append(feat)\r\n formula = \"{0} ~ 1 + {1}\".format(response, ' + '.join(selected))\r\n model = smf.ols(formula, data=train).fit()\r\n y_pred = model.predict(test[selected])\r\n print('RMSE:', np.sqrt(\r\n mean_squared_error(y_pred, test['Appliances'])))\r\n current = np.sqrt(mean_squared_error(y_pred, test['Appliances']))\r\n if best == 0.0:\r\n best = current\r\n print('best', best)\r\n if current > best:\r\n print('current more than best')\r\n print('currnet', current)\r\n print('best', best)\r\n selected.remove(feat)\r\n else:\r\n best = current\r\n pvalues = model.pvalues\r\n print('pvalues {}\\n'.format(pvalues))\r\n p_dict = pvalues.to_dict()\r\n for key, value in p_dict.items():\r\n if value >= pvalue_threshold:\r\n print('keys to remove',key)\r\n if key == 'Intercept':\r\n continue\r\n else:\r\n print('removing...')\r\n selected.remove(key)\r\n\r\n formula = \"{} ~ 1+ {}\".format(response,\r\n ' + '.join(selected))\r\n print(formula)\r\n model = smf.ols(formula, data=train).fit()\r\n print(model.summary())\r\n print('\\nParams:\\n', model.params)\r\n print('\\nPvalues:\\n', model.pvalues)\r\n predictions = model.predict(test[selected])\r\n print('RMSE:', np.sqrt(\r\n mean_squared_error(predictions, test[response])))\r\n return model\r\n\r\n\r\n# determine predictors\r\nfeature_cols = [col for col in df.columns if 'Appliances' not in col]\r\n\r\nmodel = forward_selected(df, 'Appliances')\r\n","sub_path":"applied_forecasting/forward_selection.py","file_name":"forward_selection.py","file_ext":"py","file_size_in_byte":3530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"554915455","text":"from abc import ABCMeta, abstractmethod, abstractproperty\n\nimport numpy as np\nimport statsmodels.stats.multitest as mc\n\nfrom ..base import MetaResult\nfrom ..stats import p_to_z\n\n\nclass Corrector(metaclass=ABCMeta):\n '''\n Base class for multiple comparison correction methods.\n '''\n\n # The name of the method that must be implemented in an Estimator class\n # in order to override the default correction method.\n _correction_method = None\n\n # Maps that must be available in the MetaResult instance\n _required_maps = ('p',)\n\n def __init__(self):\n pass\n\n @abstractproperty\n def _name_suffix(self):\n pass\n\n def _validate_input(self, result):\n if not isinstance(result, MetaResult):\n raise ValueError(\"First argument to transform() must be an \"\n \"instance of class MetaResult, not {}.\"\n .format(type(result)))\n for rm in self._required_maps:\n if result.maps.get(rm) is None:\n raise ValueError(\"{0} requires {1} maps to be present in the \"\n \"MetaResult, but none were found.\"\n .format(type(self), rm))\n\n def _generate_secondary_maps(self, result, corr_maps):\n # Generates corrected version of z and log-p maps if they exist\n p = corr_maps['p']\n if 'z' in result.maps:\n corr_maps['z'] = p_to_z(p) * np.sign(result.maps['z'])\n if 'log_p' in result.maps:\n corr_maps['log_p'] = -np.log10(p)\n return corr_maps\n\n def transform(self, result):\n est = result.estimator\n correction_method = self._correction_method + '_' + self.method\n\n # Make sure we return a copy of the MetaResult\n result = result.copy()\n\n # If a correction method with the same name exists in the current\n # MetaEstimator, use it. Otherwise fall back on _transform.\n if (correction_method is not None and hasattr(est, correction_method)):\n corr_maps = getattr(est, correction_method)(result, **self.parameters)\n else:\n self._validate_input(result)\n corr_maps = self._transform(result)\n\n # Update corrected map names and add them to maps dict\n corr_maps = {(k + self._name_suffix): v for k, v in corr_maps.items()}\n result.maps.update(corr_maps)\n\n return result\n\n @abstractmethod\n def _transform(self, result, **kwargs):\n # Must return a dictionary of new maps to add to .maps, where keys are\n # map names and values are the maps. Names must _not_ include\n # the _name_suffix:, as that will be added in transform() (i.e.,\n # return \"p\" not \"p_corr-FDR_q-0.05_method-indep\").\n pass\n\n\nclass FWECorrector(Corrector):\n \"\"\"\n Perform family-wise error rate correction on a meta-analysis.\n\n Parameters\n ----------\n method : `obj`:str\n The FWE correction to use. Either 'bonferroni' or 'permutation'.\n **kwargs\n Keyword arguments to be used by the FWE correction implementation.\n \"\"\"\n\n _correction_method = '_fwe_correct'\n\n def __init__(self, method='bonferroni', **kwargs):\n self.method = method\n self.parameters = kwargs\n\n @property\n def _name_suffix(self):\n return '_corr-FWE_method-{}'.format(self.method)\n\n def _transform(self, result):\n p = result.maps['p']\n _, p_corr, _, _ = mc.multipletests(p, alpha=0.05, method=self.method,\n is_sorted=False)\n corr_maps = {'p': p_corr}\n self._generate_secondary_maps(result, corr_maps)\n return corr_maps\n\n\nclass FDRCorrector(Corrector):\n \"\"\"\n Perform false discovery rate correction on a meta-analysis.\n\n Parameters\n ----------\n q : `obj`:float\n The FDR correction rate to use.\n method : `obj`:str\n The FDR correction to use. Either 'indep' (for independent or\n positively correlated values) or 'negcorr' (for general or negatively\n correlated tests).\n \"\"\"\n\n _correction_method = '_fdr_correct'\n\n def __init__(self, method='indep', **kwargs):\n self.method = method\n self.parameters = kwargs\n\n @property\n def _name_suffix(self):\n return '_corr-FDR_method-{}'.format(self.method)\n\n def _transform(self, result):\n p = result.maps['p']\n _, p_corr = mc.fdrcorrection(p, alpha=self.q, method=self.method,\n is_sorted=False)\n corr_maps = {'p': p_corr}\n self._generate_secondary_maps(result, corr_maps)\n return corr_maps\n","sub_path":"nimare/correct/correct.py","file_name":"correct.py","file_ext":"py","file_size_in_byte":4647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"367311734","text":"import numpy as np\nfrom scipy.optimize.optimize import approx_fprime\n\nfrom utils import ensure_1d\n\n\"\"\"\nImplementation of function objects.\nFunction objects encapsulate the behaviour of an objective function that we optimize.\nSimply put, implement evaluate(w, X, y) to get the numerical values corresponding to:\nf, the function value (scalar) and\ng, the gradient (vector).\n\nFunction objects are used with optimizers to navigate the parameter space and\nto find the optimal parameters (vector). See optimizers.py.\n\"\"\"\n\n\nclass FunObj:\n \"\"\"\n Function object for encapsulating evaluations of functions and gradients\n \"\"\"\n\n def evaluate(self, w, X, y):\n \"\"\"\n Evaluates the function AND its gradient w.r.t. w.\n Returns the numerical values based on the input.\n IMPORTANT: w is assumed to be a 1d-array, hence shaping will have to be handled.\n \"\"\"\n raise NotImplementedError(\"This is a base class, don't call this\")\n\n def check_correctness(self, w, X, y):\n n, d = X.shape\n estimated_gradient = approx_fprime(\n w, lambda w: self.evaluate(w, X, y)[0], epsilon=1e-6\n )\n _, implemented_gradient = self.evaluate(w, X, y)\n difference = estimated_gradient - implemented_gradient\n if np.max(np.abs(difference) > 1e-4):\n print(\n \"User and numerical derivatives differ: %s vs. %s\"\n % (estimated_gradient, implemented_gradient)\n )\n else:\n print(\"User and numerical derivatives agree.\")\n\n\nclass LeastSquaresLoss(FunObj):\n def evaluate(self, w, X, y):\n \"\"\"\n Evaluates the function and gradient of least squares objective.\n Least squares objective is the sum of squared residuals.\n \"\"\"\n # help avoid mistakes by potentially reshaping our arguments\n w = ensure_1d(w)\n y = ensure_1d(y)\n\n y_hat = X @ w\n m_residuals = y_hat - y # minus residuals, slightly more convenient here\n\n # Loss is sum of squared residuals\n f = 0.5 * np.sum(m_residuals ** 2)\n\n # The gradient, derived mathematically then implemented here\n g = X.T @ m_residuals # X^T X w - X^T y\n\n return f, g\n\n\nclass RobustRegressionLoss(FunObj):\n def evaluate(self, w, X, y):\n \"\"\"\n Evaluates the function and gradient of ROBUST least squares objective.\n \"\"\"\n # help avoid mistakes by potentially reshaping our arguments\n w = ensure_1d(w)\n y = ensure_1d(y)\n\n y_hat = X @ w\n residuals = y - y_hat\n exp_residuals = np.exp(residuals)\n exp_minuses = np.exp(-residuals)\n\n f = np.sum(np.log(exp_minuses + exp_residuals))\n\n # s is the negative of the \"soft sign\"\n s = (exp_minuses - exp_residuals) / (exp_minuses + exp_residuals)\n g = X.T @ s\n\n return f, g\n\n\nclass LogisticRegressionLoss(FunObj):\n def evaluate(self, w, X, y):\n \"\"\"\n Evaluates the function and gradient of logistics regression objective.\n \"\"\"\n # help avoid mistakes by potentially reshaping our arguments\n w = ensure_1d(w)\n y = ensure_1d(y)\n\n Xw = X @ w\n yXw = y * Xw # element-wise multiply; the y_i are in {-1, 1}\n\n # Calculate the function value\n f = np.sum(np.log(1 + np.exp(-yXw)))\n\n # Calculate the gradient value\n s = -y / (1 + np.exp(yXw))\n g = X.T @ s\n\n return f, g\n\n\nclass LogisticRegressionLossL2(LogisticRegressionLoss):\n def __init__(self, lammy):\n super().__init__()\n self.lammy = lammy\n\n def evaluate(self, w, X, y):\n w = ensure_1d(w)\n y = ensure_1d(y)\n\n \"\"\"YOUR CODE HERE FOR Q2.1\"\"\"\n raise NotImplementedError()\n\n\nclass LogisticRegressionLossL0(FunObj):\n def __init__(self, lammy):\n self.lammy = lammy\n\n def evaluate(self, w, X, y):\n \"\"\"\n Evaluates the function value of of L0-regularized logistics regression objective.\n \"\"\"\n w = ensure_1d(w)\n y = ensure_1d(y)\n\n Xw = X @ w\n yXw = y * Xw # element-wise multiply\n\n # Calculate the function value\n f = np.sum(np.log(1.0 + np.exp(-yXw))) + self.lammy * np.sum(w != 0)\n\n # We cannot differentiate the \"length\" function\n g = None\n return f, g\n\n\nclass SoftmaxLoss(FunObj):\n def evaluate(self, w, X, y):\n w = ensure_1d(w)\n y = ensure_1d(y)\n\n n, d = X.shape\n k = len(np.unique(y))\n\n \"\"\"YOUR CODE HERE FOR Q3.4\"\"\"\n # Hint: you may want to use NumPy's reshape() or flatten()\n # to be consistent with our matrix notation.\n raise NotImplementedError()\n","sub_path":"assignments/a4/code/fun_obj.py","file_name":"fun_obj.py","file_ext":"py","file_size_in_byte":4698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"635642311","text":"from __future__ import unicode_literals\n\nfrom django.views.generic import ListView, DetailView\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom django.contrib.auth.models import User\nfrom photo.models import Photo, ComplaintAtPhoto, get_countries_list\nfrom photo.forms import AddPhotoForm\n\n\nclass PhotoListView(ListView):\n model = Photo\n context_object_name = 'photos'\n template_name = 'base_photo.html'\n ordering = '-pk'\n paginate_by = 4\n\n def get_queryset(self):\n selected_country = self.request.GET.get('selected_country')\n if selected_country and selected_country in get_countries_list():\n photos = Photo.objects.filter(country=selected_country)\n else:\n photos = Photo.objects.all()\n return photos\n\n def get_context_data(self, **kwargs):\n context = super(PhotoListView, self).get_context_data(**kwargs)\n context['get_countries_list'] = get_countries_list()\n context['get_photos_on_map'] = Photo.objects.all()\n if self.request.GET:\n try:\n context['get_photos_on_map'] = Photo.objects.filter(country=self.request.GET.get('selected_country'))\n except:\n context['get_photos_on_map'] = Photo.objects.all()\n try:\n context['view_type'] = self.request.GET['view_type']\n except:\n context['view_type'] = ''\n try:\n context['selected_country'] = self.request.GET['selected_country']\n except:\n context['selected_country'] = ''\n return context\n\n\nclass PhotoDetailView(DetailView):\n model = Photo\n\n def get_context_data(self, **kwargs):\n context = super(PhotoDetailView, self).get_context_data(**kwargs)\n return context\n\n\ndef add_photo(request):\n if request.method == 'POST':\n form = AddPhotoForm(request.POST, request.FILES)\n try:\n if form.is_valid() and request.user.is_authenticated():\n obj = form.save(commit=False)\n obj.created_by = request.user\n obj.save()\n return HttpResponseRedirect('/photos/add-photo')\n except ObjectDoesNotExist:\n return HttpResponseRedirect('/photos/add-photo/error')\n else:\n form = AddPhotoForm()\n form.fields['gis_latitude'].widget.attrs['readonly'] = True\n form.fields['gis_longitude'].widget.attrs['readonly'] = True\n return render(request, 'photo/add_photo.html', {'form': form})\n\n\ndef remove_photo(request, slug):\n photo = Photo.objects.get(slug=slug)\n if request.user == photo.created_by:\n photo.delete()\n return HttpResponseRedirect('/users/%s' % request.user.username)\n\n\ndef complaint_at_photo(request, slug):\n if request.user.is_authenticated():\n photo = Photo.objects.get(slug=slug)\n user = User.objects.get(username=request.user)\n obj = ComplaintAtPhoto.objects.create(photo=photo, complaint_by=user)\n obj.save()\n return HttpResponseRedirect('/photos/')\n return HttpResponseRedirect('/photos/add-complaint/error')\n\n\n","sub_path":"photo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"84862751","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Case Specific Sorting of Strings\n# \n# ## Problem statement\n# Given a string consisting of uppercase and lowercase ASCII characters, write a function, `case_sort`, that sorts uppercase and lowercase letters separately, such that if the $i$th place in the original string had an uppercase character then it should not have a lowercase character after being sorted and vice versa.\n# \n# For example: \n# **Input:** fedRTSersUXJ \n# **Output:** deeJRSfrsTUX\n\n# In[6]:\n\n\ndef case_sort(string):\n \"\"\"\n Here are some pointers on how the function should work:\n 1. Sort the string\n 2. Create an empty output list\n 3. Iterate over original string\n if the character is lower-case:\n pick lower-case character from sorted string to place in output list\n else:\n pick upper-case character from sorted string to place in output list\n \n Note: You can use Python's inbuilt ord() function to find the ASCII value of a character\n \"\"\"\n up_chr_idx = 0\n lw_chr_idx = 0\n \n sorted_str = sorted(string)\n for idx,chr in enumerate(sorted_str):\n if 97 <= ord(chr)<=122:\n lw_chr_idx = idx\n break\n output = ''\n for ch in string:\n if 97 <=ord(ch) <=122:\n output+=sorted_str[lw_chr_idx]\n lw_chr_idx += 1\n else:\n output+=sorted_str[up_chr_idx]\n up_chr_idx += 1\n return output\n\n\n# <span class=\"graffiti-highlight graffiti-id_mw53bf1-id_fsblbn3\"><i></i><button>Show Solution</button></span>\n\n# In[7]:\n\n\ndef test_function(test_case):\n test_string = test_case[0]\n solution = test_case[1]\n \n if case_sort(test_string) == solution:\n print(\"Pass\")\n else:\n print(\"False\")\n\n\n# In[8]:\n\n\ntest_string = 'fedRTSersUXJ'\nsolution = \"deeJRSfrsTUX\"\ntest_case = [test_string, solution]\ntest_function(test_case)\n\n\n# In[9]:\n\n\ntest_string = \"defRTSersUXI\"\nsolution = \"deeIRSfrsTUX\"\ntest_case = [test_string, solution]\ntest_function(test_case)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"basic algo/Case Specific Sorting of Strings.py","file_name":"Case Specific Sorting of Strings.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"426686724","text":"def conv_dec2bin_001(d):\n '''\n Практика 1, Слайд 12 , Задание 1\n Input: число в десятеричной системе счисления\u000B\n output: число в двоичной системе счисления\u000B\n 10 -> 2\n '''\n\n # словарь соответсвия чисел. Можно сделать для систем счисления свыще 16\n ref2 = {0:'0', 1:'1'}\n\n result = \"\"\n memd = d\n\n while d != 0:\n r = d % 2\n d = d // 2\n result += ref2[r]\n print (r, d, ref2[r])\n\n print(result)\n result = result[::-1]\n print(\"dec :\" + str(memd) + \" => bin \" + result)\n\n\ndef conv_bin2dec_002(n):\n '''\n Практика 1, Слайд 12 , Задание 2\n Input: число в двоичной системе счисления\u000B\n output: число в десятичной системе счисления\u000B\n 2 -> 10\n '''\n\n le = len(n)\n lst = list(n)\n pwr = []\n for x in lst:\n pwr.append(int(x))\n print(pwr)\n\n pos = 0\n result=0\n for x in pwr:\n pos += 1\n pwr[pos-1] = x*(2**(le-pos))\n result += pwr[pos-1]\n print(pwr)\n\n print(\"bin:\" + n + \" => dec:\" + str(result))\n\n\ndef conv_hex2dec_003(hexnum):\n '''\n Практика 1, Слайд 12 , Задание 3\n Input: число в шестнадцатеричной системе счисления\u000B\n output: число в десятичной системе счисления\u000B\n 16 -> 10\n '''\n ref16to10 = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,\n 'A': 10, 'B': 11, 'C' : 12, 'D' : 13, 'E': 14, 'F': 15}\n\n le = len(hexnum)\n lst = list(hexnum)\n print(lst)\n\n pwr = []\n pos = 0\n result=0\n for x16 in lst:\n pos += 1\n x10=ref16to10[x16]\n pwr.append(x10*(16**(le-pos)))\n result += pwr[pos - 1]\n print(pwr)\n print(result)\n\n return result\n\ndef conv_dec2hex_004(decnum):\n '''\n Практика 1, Слайд 12 , Задание 4\n 10 -> 16\n '''\n\n # словарь соответсвия чисел. Можно сделать для систем счисления свыще 16\n ref10to16 = {0:'0', 1:'1', 2:'2', 3:'3', 4:'4', 5:'5', 6:'6', 7:'7', 8:'8', 9:'9',\n 10:'A', 11:'B', 12:'C', 13:'D', 14:'E', 15:'F'}\n\n base = 16\n result = \"\"\n memd = decnum\n\n while decnum != 0:\n r = decnum % base\n decnum = decnum // base\n result += ref10to16[r]\n print (r, decnum, ref10to16[r])\n\n print(result)\n result = result[::-1]\n print(\"dec :\" + str(memd) + \" => hex: \" + result)\n\n\n# 1\nd = int(input (\"dec->bin: Введите dec-число: \"))\nconv_dec2bin_001(d)\n\n# 2\nb = input (\"bin->dec: Введите bin-число: \")\nconv_bin2dec_002(b)\n\n# 3\nhexnum = input (\"hex->dec Введите hex-число: \")\nconv_hex2dec_003(hexnum)\n\n# 4\ndecnum = int(input (\"dec->hex Введите dec-число: \"))\nconv_dec2hex_004(decnum)\n\n\n","sub_path":"12_NumberSystems.py","file_name":"12_NumberSystems.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"580410862","text":"import json\r\nimport re\r\n\r\n\r\n# Parser for JSON string that consists of JSON array with JSON objects\r\ndef parse_json(lst):\r\n result = []\r\n structure = []\r\n stack = []\r\n pair = []\r\n for i, j in enumerate(lst):\r\n if '{' in j or '}' in j:\r\n for k in j:\r\n if k != '{' and k != '}':\r\n pass\r\n else:\r\n if k == '{':\r\n structure.append('{')\r\n elif k == '}' and structure[-1] == '{':\r\n structure.pop()\r\n dict_temp = dict(stack)\r\n result.append(dict_temp)\r\n stack = []\r\n else:\r\n print('Error in structure')\r\n\r\n elif ':' in j and ':' in lst[i-1]:\r\n text = re.sub(r'\\s+', ' ', j)\r\n pair.append(text)\r\n stack.append(pair)\r\n pair=[]\r\n elif ':' in j and ':' not in lst[i-1]:\r\n ex = j.strip()\r\n if len(ex)>1:\r\n pair.append(lst[i-1])\r\n l = ex.split()\r\n for k in l:\r\n if k == ':':\r\n pass\r\n else:\r\n text = re.sub('[^А-яA-z0-9]', '', k)\r\n if text.isdigit():\r\n pair.append(int(text))\r\n elif text == 'None':\r\n pair.append(None)\r\n else:\r\n text = re.sub(r'\\s+', ' ', text)\r\n pair.append(text)\r\n stack.append(pair)\r\n pair = []\r\n else:\r\n pair.append(lst[i-1])\r\n elif ':' in lst[i-1] and ':' not in lst[i-2]:\r\n if pair:\r\n text = re.sub(r'\\s+', ' ', j)\r\n pair.append(text)\r\n stack.append(pair)\r\n pair = []\r\n return result\r\n\r\n\r\n# Delete duplicates in the list of dictionaries\r\ndef del_duplicate(lst):\r\n seen = set()\r\n final_d = []\r\n for d in lst:\r\n t = tuple(d.items())\r\n if t not in seen:\r\n seen.add(t)\r\n final_d.append(d)\r\n return final_d\r\n\r\n\r\n# Dump for JSON array with Json objects. Works very slow with big list\r\ndef dump_json(lst):\r\n result = '['\r\n for _ in lst:\r\n items = tuple(_.items())\r\n s = ''\r\n for key, value in items:\r\n s += '\"{}\": \"{}\", '.format(key, value)\r\n result += '{' + s[:-2] + '}, '\r\n return result[:-2] + ']'\r\n\r\n\r\nwith open(\"C:/Users/ekant/Desktop/winedata_1.json\") as f:\r\n s_1 = f.read()\r\n s_1 = s_1.replace('\\\\\"', \"'\")\r\n # s_1 = s_1.encode().decode('unicode_escape')\r\n\r\nwith open(\"C:/Users/ekant/Desktop/winedata_2.json\") as inf:\r\n s_2 = inf.read()\r\n s_2 = s_2.replace('\\\\\"', \"'\")\r\n # s_2 = s_2.encode().decode('unicode_escape')\r\n\r\n\r\nstring = s_1+s_2\r\nstring = string.replace('null', 'None')\r\nd = string.split('\"')\r\n\r\nresult_parse = parse_json(d)\r\nnew_d = del_duplicate(result_parse)\r\nprint('Дубликатов:', len(result_parse)-len(new_d))\r\n\r\n# Sort objects by price, then by wine sort\r\n\r\nwinedata = sorted(new_d, key=lambda x: '' if x['variety'] is None else x['variety'])\r\nwinedata = sorted(winedata, key=lambda x: -1 * float('inf') if x['price'] is None else x['price'], reverse=True)\r\n\r\nresult_json = dump_json(winedata)\r\n\r\nf = open('winedata_full.json', 'tw', encoding='utf-8')\r\nf.write(result_json)\r\nf.close()\r\n","sub_path":"01-Data-Structures/hw/sticks/parser_dumper_json_part1_2.py","file_name":"parser_dumper_json_part1_2.py","file_ext":"py","file_size_in_byte":3549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"137790757","text":"#!/usr/bin/env python2.7\n\nimport sys\nimport os\nimport jinja2\n\nfrom fabric.api import *\nfrom fabric.tasks import execute\nimport getpass\n\ntemplateLoader = jinja2.FileSystemLoader( searchpath=\"/\" )\ntemplateEnv = jinja2.Environment( loader=templateLoader )\nTEMPDOMFILE = os.getcwd()+'/jinja2temps/mszone.conf'\n\ntempdom = templateEnv.get_template( TEMPDOMFILE )\n\nTEMPLDOMFILE = os.getcwd()+'/jinja2temps/lmdom.conf'\n\ntempldom = templateEnv.get_template( TEMPLDOMFILE )\n\nenv.roledefs = {\n 'dns': [str(raw_input('Please enter NS1 IP address: ')), str(raw_input('Please enter NS2 IP address: '))]\n}\n\nenv.user = raw_input('Please enter username for UNIX/Linux server: ')\nenv.password = getpass.getpass()\n\nprint('1. Write domain name which you want to update: ')\nprint('2. For exit, write 2 and click Enter button: ')\nent = raw_input('Write your choose: ')\n\nfor server in env.roledefs['dns']:\n env.host_string = server\n with settings(\n hide('warnings', 'running', 'stdout', 'stderr'),\n warn_only=True\n ):\n osver = run('uname -s')\n lintype = run('cat /etc/redhat-release | awk \\'{ print $1 }\\'')\n ftype = run('uname -v | awk \\'{ print $2 }\\' | cut -f1 -d \\'.\\'')\n if osver == 'FreeBSD' and ftype >= 10:\n getfbindpack = run('which named')\n if getfbindpack == '/usr/local/sbin/named':\n def writemzone():\n if server == env.roledefs['dns'][0]:\n fzonename = run('cat /usr/local/etc/namedb/named.conf | grep '+ent+' | head -1 | awk \\'{ print $2 }\\' | sed \\'s/\"//g\\'')\n fzonefile = run('cat /usr/local/etc/namedb/named.conf | grep '+ent+' | tail -1 | awk \\'{ print $2 }\\' | sed \\'s/\"//g;s/;//g\\' | cut -f 7 -d\\'/\\' | cut -f1,2 -d \\'.\\'')\n if ent == fzonename and fzonefile == ent:\n print(\"This domain name really exists...\")\n print(\"\"\"Please choose record type which you want to create: \n A\n NS\n MX\n TXT\n SRV\n \"\"\")\n rec = raw_input('Write your choose record type and press the enter button: ')\n if rec == \"A\":\n recnameA = raw_input('Please enter A record name: ')\n ipforA = raw_input('Enter IP address for A record: ')\n print('evvel')\n run('ifconfig')\n print('sonra')\n #run('echo \"'+recnameA+' IN A '+ipforA+'\" >> /usr/local/etc/named/master/'+ent+'.zone')\n else:\n print(\"Entered domain name is not exits and you cannot add new record.\")\n print(\"Please use ./python-add-zone.py script for add new nomain.\")\n\n def writeszone():\n if server == env.roledefs['dns'][1]:\n run('service named restart')\n\n if ent != 2 and len(ent) > 4:\n writemzone()\n writeszone()\n else:\n print(\"\\nMinimal symbol count must be 4.\")\n sys.exit()\n elif osver == 'Linux' and lintype == 'CentOS':\n getlbindpack = run('which named')\n bindlpidfile = run('cat /var/run/named/named.pid')\n bindlpid = run('ps waux|grep named | grep -v grep | awk \\'{ print $2 }\\'')\n if getlbindpack == '/usr/sbin/named' and bindlpidfile == bindlpid:\n def writelmzone():\n if server == env.roledefs['dns'][0]:\n a = 5\n b = 6\n print(a+b)\n def writelszone():\n if server == env.roledefs['dns'][1]:\n a = 6 \n b = 7\n print(a+b)\n if ent != 2 and len(ent) > 4:\n writelmzone()\n writelszone()\n else:\n print(\"\\nMinimal symbol count must be 4.\")\n sys.exit()\n else:\n print(\"The script is not determine server type. For this reason you cannot use this script.\")\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"585124115","text":"#Write a Python program to combine two dictionary adding values for common keys. Go to the editor\n#d1 = {'a': 100, 'b': 200, 'c':300}\n#d2 = {'a': 300, 'b': 200, 'd':400}\n#Sample output: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})\n\n\nd1 = {'a': 100, 'b': 200, 'c':300}\nd2 = {'a': 300, 'b': 200, 'd':400}\nd3= dict()\nfor i,j in d1.items():\n for k,l in d2.items():\n if i == k:\n sum=j+l\n d3[i]=sum\n else:\n d3[i]=j\n\nprint(d3)","sub_path":"venv/My programs/Exercises/Exercise14.py","file_name":"Exercise14.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"97904736","text":"import datetime\nfrom dateutil.relativedelta import relativedelta\nimport json\nfrom urllib import urlencode\n\nfrom django.contrib.auth.models import Permission\nfrom django.core.urlresolvers import reverse\n\nfrom timepiece import models as timepiece\nfrom timepiece.tests.base import TimepieceDataTestCase\n\n\nclass TestProductivityReport(TimepieceDataTestCase):\n url_name = 'productivity_report'\n\n def setUp(self):\n self.username = 'test_user'\n self.password = 'password'\n self.user = self.create_user(username=self.username,\n password=self.password)\n self.permission = Permission.objects.get(codename='view_entry_summary')\n self.user.user_permissions.add(self.permission)\n self.client.login(username=self.username, password=self.password)\n\n self.project = self.create_project()\n self.users = []\n self.users.append(self.create_user(first_name='Person', last_name='1'))\n self.users.append(self.create_user(first_name='Person', last_name='2'))\n self.users.append(self.create_user(first_name='Person', last_name='3'))\n self.weeks = []\n self.weeks.append(datetime.datetime(2012, 9, 24))\n self.weeks.append(datetime.datetime(2012, 10, 1))\n self.weeks.append(datetime.datetime(2012, 10, 8))\n self.weeks.append(datetime.datetime(2012, 10, 15))\n\n self._create_entries()\n self._create_assignments()\n\n def _create_entries(self):\n for start_time in (self.weeks[1], self.weeks[3]):\n for user in (self.users[1], self.users[2]):\n end_time = start_time + relativedelta(hours=2)\n data = {'user': user, 'start_time': start_time,\n 'end_time': end_time, 'project': self.project}\n self.create_entry(data)\n\n def _create_assignments(self):\n for week_start in (self.weeks[0], self.weeks[1]):\n for user in (self.users[0], self.users[1]):\n data = {'user': user, 'week_start': week_start,\n 'project': self.project, 'hours': 2}\n self.create_project_hours_entry(**data)\n\n def _get(self, url_name=None, url_kwargs=None, get_kwargs=None, **kwargs):\n \"\"\"Convenience wrapper for test client GET request.\"\"\"\n url_name = url_name or self.url_name\n url = reverse(url_name, kwargs=url_kwargs)\n if get_kwargs:\n url += '?' + urlencode(get_kwargs)\n return self.client.get(url, **kwargs)\n\n def _unpack(self, response):\n form = response.context['form']\n report = json.loads(response.context['report'])\n organize_by = response.context['type']\n worked = response.context['total_worked']\n assigned = response.context['total_assigned']\n return form, report, organize_by, worked, assigned\n\n def _check_row(self, row, correct):\n self.assertEqual(len(row), 3)\n self.assertEqual(row[0], correct[0])\n self.assertEqual(float(row[1]), correct[1])\n self.assertEqual(float(row[2]), correct[2])\n\n def test_not_authenticated(self):\n \"\"\"User must be logged in to see this report.\"\"\"\n self.client.logout()\n response = self._get()\n self.assertEqual(response.status_code, 302) # Redirects to login\n\n def test_no_permission(self):\n \"\"\"This report requires permission to view entry summaries.\"\"\"\n self.user.user_permissions.remove(self.permission)\n response = self._get()\n self.assertEqual(response.status_code, 302) # Redirects to login\n\n def test_retrieval(self):\n \"\"\"No report data should be returned upon initial retrieval.\"\"\"\n response = self._get()\n self.assertEqual(response.status_code, 200)\n form, report, organize_by, worked, assigned = self._unpack(response)\n self.assertEqual(len(form.errors), 0)\n self.assertEqual(len(report), 0)\n self.assertEqual(organize_by, '')\n self.assertEqual(float(worked), 0.0)\n self.assertEqual(float(assigned), 0.0)\n\n def test_no_project(self):\n \"\"\"Form requires specification of project.\"\"\"\n data = {'organize_by': 'week'}\n response = self._get(data=data)\n self.assertEqual(response.status_code, 200)\n form, report, organize_by, worked, assigned = self._unpack(response)\n self.assertEqual(len(form.errors), 1)\n self.assertTrue('project' in form.errors)\n self.assertEqual(len(report), 0)\n self.assertEqual(organize_by, '')\n self.assertEqual(float(worked), 0.0)\n self.assertEqual(float(assigned), 0.0)\n\n def test_invalid_project_id(self):\n \"\"\"Form requires specification of valid project.\"\"\"\n data = {'organize_by': 'week', 'project_1': 12345}\n response = self._get(data=data)\n self.assertEqual(response.status_code, 200)\n form, report, organize_by, worked, assigned = self._unpack(response)\n self.assertEqual(len(form.errors), 1)\n self.assertTrue('project' in form.errors)\n self.assertEqual(len(report), 0)\n self.assertEqual(organize_by, '')\n self.assertEqual(float(worked), 0.0)\n self.assertEqual(float(assigned), 0.0)\n\n def test_no_organize_by(self):\n \"\"\"Form requires specification of organization method.\"\"\"\n data = {'project_1': self.project.pk}\n response = self._get(data=data)\n self.assertEqual(response.status_code, 200)\n form, report, organize_by, worked, assigned = self._unpack(response)\n self.assertEqual(len(form.errors), 1)\n self.assertTrue('organize_by' in form.errors)\n self.assertEqual(len(report), 0)\n self.assertEqual(organize_by, '')\n self.assertEqual(float(worked), 0.0)\n self.assertEqual(float(assigned), 0.0)\n\n def test_invalid_organize_by(self):\n \"\"\"Form requires specification of valid organization method.\"\"\"\n data = {'project_1': self.project.pk, 'organize_by': 'invalid'}\n response = self._get(data=data)\n self.assertEqual(response.status_code, 200)\n form, report, organize_by, worked, assigned = self._unpack(response)\n self.assertEqual(len(form.errors), 1)\n self.assertTrue('organize_by' in form.errors)\n self.assertEqual(len(report), 0)\n self.assertEqual(organize_by, '')\n self.assertEqual(float(worked), 0.0)\n self.assertEqual(float(assigned), 0.0)\n\n def test_no_data(self):\n \"\"\"If no data, report should contain header row only.\"\"\"\n timepiece.Entry.objects.filter(project=self.project).delete()\n timepiece.ProjectHours.objects.filter(project=self.project).delete()\n data = {'project_1': self.project.pk, 'organize_by': 'week'}\n response = self._get(data=data)\n self.assertEqual(response.status_code, 200)\n form, report, organize_by, worked, assigned = self._unpack(response)\n self.assertEqual(len(form.errors), 0)\n self.assertEqual(len(report), 1)\n self.assertEqual(organize_by, 'week')\n self.assertEqual(float(worked), 0.0)\n self.assertEqual(float(assigned), 0.0)\n\n def test_organize_by_week(self):\n \"\"\"Report should contain hours per week on the project.\"\"\"\n data = {'project_1': self.project.pk, 'organize_by': 'week'}\n response = self._get(data=data)\n self.assertEqual(response.status_code, 200)\n form, report, organize_by, worked, assigned = self._unpack(response)\n self.assertEqual(len(form.errors), 0)\n self.assertEqual(organize_by, 'week')\n self.assertEqual(float(worked), 8.0)\n self.assertEqual(float(assigned), 8.0)\n self.assertEqual(len(report), 1 + 4) # Include header row\n self._check_row(report[1], ['2012-09-24', 0.0, 4.0])\n self._check_row(report[2], ['2012-10-01', 4.0, 4.0])\n self._check_row(report[3], ['2012-10-08', 0.0, 0.0])\n self._check_row(report[4], ['2012-10-15', 4.0, 0.0])\n\n def test_organize_by_people(self):\n \"\"\"Report should contain hours per peron on the project.\"\"\"\n data = {'project_1': self.project.pk, 'organize_by': 'person'}\n response = self._get(data=data)\n self.assertEqual(response.status_code, 200)\n form, report, organize_by, worked, assigned = self._unpack(response)\n self.assertEqual(len(form.errors), 0)\n self.assertEqual(organize_by, 'person')\n self.assertEqual(float(worked), 8.0)\n self.assertEqual(float(assigned), 8.0)\n self.assertEqual(len(report), 1 + 3) # Include header row\n self._check_row(report[1], ['Person 1', 0.0, 4.0])\n self._check_row(report[2], ['Person 2', 4.0, 4.0])\n self._check_row(report[3], ['Person 3', 4.0, 0.0])\n\n def test_export(self):\n \"\"\"Data should be exported in CSV format.\"\"\"\n data = {'project_1': self.project.pk, 'organize_by': 'week',\n 'export': True}\n response = self._get(data=data)\n self.assertEqual(response.status_code, 200)\n data = dict(response.items())\n self.assertEqual(data['Content-Type'], 'text/csv')\n disposition = 'attachment; filename={0}_productivity.csv'.format(\n self.project.name)\n self.assertTrue(data['Content-Disposition'].startswith(disposition))\n report = response.content.splitlines()\n self.assertEqual(len(report), 1 + 4) # Include header row\n self._check_row(report[1].split(','), ['2012-09-24', 0.0, 4.0])\n self._check_row(report[2].split(','), ['2012-10-01', 4.0, 4.0])\n self._check_row(report[3].split(','), ['2012-10-08', 0.0, 0.0])\n self._check_row(report[4].split(','), ['2012-10-15', 4.0, 0.0])\n","sub_path":"timepiece/tests/reports/productivity.py","file_name":"productivity.py","file_ext":"py","file_size_in_byte":9716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"277926503","text":"import random\nimport math\n\nclass question5():\n\tdef mutation(self, X: str, chi: float, rep: int):\n\t\tmu = chi / len(X)\n\t\tfor i in range(0, rep):\n\t\t\tX = list(X)\n\t\t\tfor i in range(0, len(X)):\n\t\t\t\ttemp = random.random()\n\t\t\t\tif temp < mu:\n\t\t\t\t\tX[i] = str(int(math.fabs(int(X[i]) - 1)))\n\t\t\tX = ''.join(X)\n\t\treturn (X)\n\n\tdef crossover(self, X: str, Y: str, rep: int):\n\t\tfor i in range(0, rep):\n\t\t\ttemp = [0] * len(X)\n\t\t\tfor i in range(0, len(X)):\n\t\t\t\tp = random.random()\n\t\t\t\ttemp[i] = X[i] if p > 0.5 else Y[i]\n\t\t\ttemp = ''.join(temp)\n\t\treturn temp\n\n\tdef oneMAX(self, X: str):\n\t\tevaluate = sum([int(i) for i in X])\n\t\treturn evaluate\n\n\tdef tournament(self, X: list, k: int, rep: int):\n\t\tX = X\n\t\tmu = 1 / len(X)\n\t\t# mu = 0.9\n\t\tif k > len(X):\n\t\t\treturn False\n\t\telse:\n\t\t\tfor i in range(rep):\n\t\t\t\tx = []\n\t\t\t\tans = [0] * k\n\t\t\t\tm = len(X)\n\t\t\t\tfor i in range(0, m):\n\t\t\t\t\tx.append(self.oneMAX(X[i]))\n\t\t\t\tOut = list(zip(x, X))\n\t\t\t\tx = sorted(Out, key=lambda x: x[0], reverse=True)\n\t\t\t\ti = 0\n\t\t\t\twhile 0 in ans:\n\t\t\t\t\tp = random.random()\n\t\t\t\t\ta = b = 0\n\t\t\t\t\tfor j in range(0, len(X)):\n\t\t\t\t\t\ta = a + bool(j) * mu * (1 - mu) ** (j - 1)\n\t\t\t\t\t\tb = b + mu * (1 - mu) ** (j)\n\t\t\t\t\t\tif a < p <= b:\n\t\t\t\t\t\t\tm = x[j][1]\n\t\t\t\t\t\t\tans[i] = (str(x[j][1]))\n\t\t\t\t\t\t\ti = i + 1\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tcontinue\n\t\t\treturn ans, X\n\n\tdef create(self, n, pop):\n\t\tX = [0] * n\n\t\tfor i in range(0, n):\n\t\t\ttemp = []\n\t\t\tfor j in range(0, pop):\n\t\t\t\tp = random.random()\n\t\t\t\ttemp.append('1' if p > 0.5 else '0')\n\t\t\tX[i] = ''.join(temp)\n\t\treturn X\n\n\tdef Genetic(self, chi, n, Lambda, k, Rep):\n\t\trep = Rep\n\t\tflag = 0\n\t\tX = self.create(n, Lambda)\n\t\tX1, X = self.tournament(X, k, rep)\n\t\tX1[0] = self.crossover(X1[0], X1[1], rep)\n\t\tX1[1] = self.crossover(X1[0], X1[1], rep)\n\t\tX1[0] = self.mutation(X1[0], chi, rep)\n\t\tX1[1] = self.mutation(X1[1], chi, rep)\n\t\tX.extend(X1)\n\t\tX_eva = []\n\t\tfor i in range(len(X)):\n\t\t\tX_eva.append(self.oneMAX(X[i]))\n\t\tOut = list(zip(X, X_eva))\n\t\tOut.sort(key=lambda x: x[0], reverse=True)\n\t\tans = Out[0]\n\t\tif ans[1] == n:\n\t\t\treturn n, chi, Lambda, k, rep, ans[1], ans[0]\n\t\telse:\n\t\t\twhile not int(ans[1]) == n:\n\t\t\t\tif rep <= 20000:\n\t\t\t\t\trep = rep + 1\n\t\t\t\t\tX1, X = self.tournament(X, k, 1)\n\t\t\t\t\tX1[0] = self.crossover(X1[0], X1[1], 1)\n\t\t\t\t\tX1[1] = self.crossover(X1[0], X1[1], 1)\n\t\t\t\t\tX1[0] = self.mutation(X1[0], chi, 1)\n\t\t\t\t\tX1[1] = self.mutation(X1[1], chi, 1)\n\t\t\t\t\tX.extend(X1)\n\t\t\t\t\tX_eva = []\n\t\t\t\t\tfor i in range(len(X)):\n\t\t\t\t\t\tX_eva.append(self.oneMAX(X[i]))\n\t\t\t\t\tOut = list(zip(X, X_eva))\n\t\t\t\t\tOut.sort(key=lambda x: x[1], reverse=True)\n\t\t\t\t# print(Out)\n\t\t\t\t\tans = Out[0]\n\t\t\t\t\tprint(ans[1],rep)\n\t\t\t\telse:\n\t\t\t\t\tbreak\n\t\t\t\t\treturn 'cirlce limits'\n\t\t\t# print(ans)\n\t\t\treturn n, chi, Lambda, k, rep, ans[1], ans[0]\n\n\napp = question5()\n# chi = float(input('please input chi: '))\n# n = int(input('please input n: '))\n# Lambda = int(input('please input population: '))\n# k = int(input('please input k: '))\n# rep = int(input('please input rep: '))\nX = app.create(200, 100)\n# print(X)\nY = app.mutation(X[1], 0.2, 4)\n# print(Y)\nZ = app.crossover(X[3], X[4], 4)\n# print(Z)\nSigma = app.tournament(X, 2, 4)\n# print(Sigma)\nchi = 2\n\nprint(app.Genetic(chi, n=10, Lambda=10, k=2, Rep=4))\n","sub_path":"question5.py","file_name":"question5.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"465518907","text":"import logging\n\nfrom hca_ingest.api.ingestapi import IngestApi\n\nfrom manifest.generator import ManifestGenerator\n\n\nclass ManifestExporter:\n def __init__(self, ingest_api: IngestApi, manifest_generator: ManifestGenerator):\n self.logger = logging.getLogger('ManifestExporter')\n self.ingest_api = ingest_api\n self.manifest_generator = manifest_generator\n\n def export(self, process_uuid: str, submission_uuid: str):\n assay_manifest = self.manifest_generator.generate_manifest(process_uuid, submission_uuid)\n assay_manifest_resource = self.ingest_api.create_bundle_manifest(assay_manifest)\n assay_manifest_url = assay_manifest_resource['_links']['self']['href']\n self.logger.info(f\"Assay manifest was created: {assay_manifest_url}\")\n","sub_path":"manifest/exporter.py","file_name":"exporter.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"362822125","text":"from d3m import container\nfrom d3m.primitive_interfaces.transformer import TransformerPrimitiveBase\nfrom d3m.metadata import hyperparams\nfrom dsbox.datapreprocessing.cleaner import config\nfrom d3m.primitive_interfaces.base import CallResult\nimport common_primitives.utils as common_utils\nimport d3m.metadata.base as mbase\nimport warnings\n\n__all__ = ('Unfold',)\n\nInputs = container.DataFrame\nOutputs = container.DataFrame\n\n\nclass UnfoldHyperparams(hyperparams.Hyperparams):\n unfold_semantic_types = hyperparams.Set(\n elements=hyperparams.Hyperparameter[str](\"str\"),\n default=[\"https://metadata.datadrivendiscovery.org/types/PredictedTarget\"],\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n description=\n \"\"\"\n A set of semantic types that the primitive will unfold.\n Only 'https://metadata.datadrivendiscovery.org/types/PredictedTarget' by default.\n \"\"\",\n )\n use_pipeline_id_semantic_type = hyperparams.UniformBool(\n default=False,\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n description=\n \"\"\"\n Controls whether semantic_type will be used for finding pipeline id column in input dataframe.\n If true, it will look for 'https://metadata.datadrivendiscovery.org/types/PipelineId' for pipeline id column,\n and create attribute columns using header: attribute_{pipeline_id}. \n eg. 'binaryClass_{a3180751-33aa-4790-9e70-c79672ce1278}'\n If false, create attribute columns using header: attribute_{0,1,2,...}.\n eg. 'binaryClass_0', 'binaryClass_1'\n \"\"\",\n )\n\n\nclass Unfold(TransformerPrimitiveBase[Inputs, Outputs, UnfoldHyperparams]):\n \"\"\"\n A primitive which concat a list of dataframe to a single dataframe vertically\n \"\"\"\n\n __author__ = 'USC ISI'\n metadata = hyperparams.base.PrimitiveMetadata({\n \"id\": \"dsbox-unfold\",\n \"version\": config.VERSION,\n \"name\": \"DSBox unfold\",\n \"description\": \"A primitive which unfold a vertically concatenated dataframe\",\n \"python_path\": \"d3m.primitives.data_preprocessing.Unfold.DSBOX\",\n \"primitive_family\": \"DATA_PREPROCESSING\",\n \"algorithm_types\": [\"DATA_CONVERSION\"],\n \"source\": {\n \"name\": config.D3M_PERFORMER_TEAM,\n \"contact\": config.D3M_CONTACT,\n \"uris\": [config.REPOSITORY]\n },\n \"keywords\": [\"unfold\"],\n \"installation\": [config.INSTALLATION],\n })\n\n def __init__(self, *, hyperparams: UnfoldHyperparams) -> None:\n super().__init__(hyperparams=hyperparams)\n self.hyperparams = hyperparams\n self._sorted_pipe_ids = None\n\n def produce(self, *, inputs: Inputs, timeout: float = None, iterations: int = None) -> CallResult[Outputs]:\n primary_key_cols = common_utils.list_columns_with_semantic_types(\n metadata=inputs.metadata,\n semantic_types=[\"https://metadata.datadrivendiscovery.org/types/PrimaryKey\"]\n )\n\n unfold_cols = common_utils.list_columns_with_semantic_types(\n metadata=inputs.metadata,\n semantic_types=self.hyperparams[\"unfold_semantic_types\"]\n )\n\n if not primary_key_cols:\n warnings.warn(\"Did not find primary key column for grouping. Will not unfold\")\n return CallResult(inputs)\n\n if not unfold_cols:\n warnings.warn(\"Did not find any column to unfold. Will not unfold\")\n return CallResult(inputs)\n\n primary_key_col_names = [inputs.columns[pos] for pos in primary_key_cols]\n unfold_col_names = [inputs.columns[pos] for pos in unfold_cols]\n\n if self.hyperparams[\"use_pipeline_id_semantic_type\"]:\n pipeline_id_cols = common_utils.list_columns_with_semantic_types(\n metadata=inputs.metadata,\n semantic_types=[\"https://metadata.datadrivendiscovery.org/types/PipelineId\"]\n )\n\n if len(pipeline_id_cols) >= 2:\n warnings.warn(\"Multiple pipeline id columns found. Will use first.\")\n\n if pipeline_id_cols:\n inputs = inputs.sort_values(primary_key_col_names + [inputs.columns[pos] for pos in pipeline_id_cols])\n self._sorted_pipe_ids = sorted(inputs.iloc[:, pipeline_id_cols[0]].unique())\n else:\n warnings.warn(\n \"No pipeline id column found by 'https://metadata.datadrivendiscovery.org/types/PipelineId'\")\n\n new_df = self._get_new_df(inputs=inputs, use_cols=primary_key_cols + unfold_cols)\n\n groupby_df = inputs.groupby(primary_key_col_names)[unfold_col_names].aggregate(\n lambda x: container.List(x)).reset_index(drop=False)\n\n ret_df = container.DataFrame(groupby_df)\n ret_df.metadata = new_df.metadata\n ret_df = self._update_metadata_dimension(df=ret_df)\n\n split_col_names = [inputs.columns[pos] for pos in unfold_cols]\n\n ret_df = self._split_aggregated(df=ret_df, split_col_names=split_col_names)\n ret_df = common_utils.remove_columns(\n inputs=ret_df,\n column_indices=[ret_df.columns.get_loc(name) for name in split_col_names]\n )\n\n return CallResult(ret_df)\n\n @staticmethod\n def _get_new_df(inputs: container.DataFrame, use_cols: list):\n metadata = common_utils.select_columns_metadata(inputs_metadata=inputs.metadata, columns=use_cols)\n new_df = inputs.iloc[:, use_cols]\n new_df.metadata = metadata\n return new_df\n\n @staticmethod\n def _update_metadata_dimension(df: container.DataFrame) -> container.DataFrame:\n old_metadata = dict(df.metadata.query(()))\n old_metadata[\"dimension\"] = dict(old_metadata[\"dimension\"])\n old_metadata[\"dimension\"][\"length\"] = df.shape[0]\n df.metadata = df.metadata.update((), old_metadata)\n return df\n\n def _split_aggregated(self, df: container.DataFrame, split_col_names: list) -> container.DataFrame:\n lengths = [len(df.loc[0, col_name]) for col_name in split_col_names]\n\n for idx, col_name in enumerate(split_col_names):\n if self._sorted_pipe_ids:\n if len(self._sorted_pipe_ids) == lengths[idx]:\n extend_col_names = [\"{}_{}\".format(col_name, i) for i in self._sorted_pipe_ids]\n else:\n raise ValueError(\"Unique number of pipeline ids not equal to the number of aggregated values\")\n else:\n extend_col_names = [\"{}_{}\".format(col_name, i) for i in range(lengths[idx])]\n\n extends = container.DataFrame(df.loc[:, col_name].values.tolist(), columns=extend_col_names)\n\n df = common_utils.horizontal_concat(left=df, right=extends)\n origin_metadata = dict(df.metadata.query((mbase.ALL_ELEMENTS, df.columns.get_loc(col_name))))\n\n for name in extend_col_names:\n col_idx = df.columns.get_loc(name)\n origin_metadata[\"name\"] = name\n df.metadata = df.metadata.update((mbase.ALL_ELEMENTS, col_idx), origin_metadata)\n\n return df\n","sub_path":"dsbox/datapostprocessing/unfold.py","file_name":"unfold.py","file_ext":"py","file_size_in_byte":7171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"442333828","text":"# -*- coding: utf-8 -*-\nimport logging\nimport requests\nimport json\nimport uuid\nimport re\nimport datetime\nimport time\nimport os\nimport smtplib\nfrom email.mime.text import MIMEText\n\ndef send_email(msg):\n mail_host = 'smtp.qq.com' \n mail_user = '734962820' \n mail_pass = 'QQ邮箱授权码' \n sender = '734962820@qq.com' \n receivers = ['734962820@qq.com'] \n message = MIMEText(msg,'html','utf-8')\n message['Subject'] = '云战役自动签到' \n message['From'] = sender \n message['To'] = receivers[0]\n try:\n smtpObj = smtplib.SMTP_SSL(mail_host)\n smtpObj.login(mail_user,mail_pass) \n smtpObj.sendmail(sender,receivers,message.as_string()) \n smtpObj.quit() \n print('send email success')\n except smtplib.SMTPException as e:\n print('send email error',e)\n\ndef run():\n header = {'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'}\n users = '''\n [\n {\n \"name\": \"111111\",\n \"psswd\": \"111111\",\n \"locationInfo\": \"浙江省杭州市金沙港生活区\"\n },\n {\n \"name\": \"222222\",\n \"psswd\": \"222222\",\n \"locationInfo\": \"浙江省杭州市金沙港生活区\"\n }\n ]\n '''\n users = json.loads(users)\n print('当前时间:', datetime.datetime.now())\n\n user_error_flag = False\n result_error_flag = False\n for user in users:\n s = requests.session()\n s.post('https://nco.zjgsu.edu.cn/login', data=user, headers=header)\n res = s.get('https://nco.zjgsu.edu.cn/', headers=header)\n content = str(res.content, encoding='utf-8')\n if re.search('当天已报送!', content):\n print(datetime.datetime.now().strftime('%Y-%m-%d'), '报送情况: *主动报送*')\n continue\n data = {}\n try:\n for item in re.findall(R'<input.+?>', content):\n key = re.search(R'name=\"(.+?)\"', item).group(1)\n value = re.search(R'value=\"(.*?)\"', item).group(1)\n check = re.search(R'checked', item)\n if key not in data.keys():\n data[key] = value\n elif check is not None:\n data[key] = value\n except:\n print('出现错误,可能是账号密码不正确')\n user_error_flag = True\n continue\n for item in re.findall(R'<textarea.+?>', content):\n key = re.search(R'name=\"(.+?)\"', item).group(1)\n data[key] = ''\n # 为了安全起见,这里还是推荐加上大致的地址和uuid值,虽然经过测试,不填写也可以正常使用\n # ---------------安全线-------------#\n data['uuid'] = str(uuid.uuid1())\n if('locationInfo' not in data):\n data['locationInfo'] = '浙江省杭州市浙江工商大学金沙港生活区'\n # ---------------安全线-------------#\n res = s.post('https://nco.zjgsu.edu.cn/', data=data, headers=header)\n success_flag = re.search('报送成功', str(res.content, encoding='utf-8')) is not None\n print(datetime.datetime.now().strftime('%Y-%m-%d'), '报送情况:', '报送成功' if success_flag\n else '报送失败!!!!!')\n if(not success_flag):\n result_error_flag = True\n if(user_error_flag):\n send_email('存在用户信息错误导致的签到失败')\n elif(result_error_flag):\n send_email('签到网站错误,或签到入口已关闭')\n \ndef handler(event, context): #主要云函数入口名称!\n return run()\n","sub_path":"Ali_tencent_Event.py","file_name":"Ali_tencent_Event.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"307765532","text":"vowels=['a','e','i','o','u','A','E','I','O','U']\nfinalVowel = []\ni=input('enter a string')\ndef vowelfilter():\n for letter in i:\n if letter in vowels:\n finalVowel.append(letter)\n return finalVowel\nk=vowelfilter()\nprint(k)\n","sub_path":"project1/functions/filtervowel.py","file_name":"filtervowel.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"201351101","text":"import requests\nimport os\nimport pandas as pd\nfrom datetime import datetime\nfrom flask import Flask, jsonify\n\napp = Flask(__name__)\n\n# URL = 'https://rsr.akvo.org/rest/v1/'\nURL = 'http://192.168.1.134/rest/v1/'\n#PROJECT_ID = '7283'\nRSR_TOKEN = os.environ['RSR_TOKEN']\nFMT = '/?format=json&limit=1'\nFMT100 = '/?format=json&limit=100'\n\nheaders = {\n 'content-type': 'application/json',\n 'Authorization': RSR_TOKEN\n}\n\ndef get_response(endpoint, param, value):\n uri = '{}{}{}&{}={}'.format(URL, endpoint, FMT100, param, value)\n print(get_time() + ' Fetching - ' + uri)\n data = requests.get(uri, headers=headers)\n data = data.json()\n return data\n\ndef get_time():\n now = datetime.now().time().strftime(\"%H:%M:%S\")\n return now\n\ndef get_children_id(x):\n for k,v in x.items():\n return k\n\ndef get_children_title(x):\n for k,v in x.items():\n return v\n\n@app.route('/api/<project_id>', methods=['GET'])\ndef api(project_id):\n results_indicator = get_response('results_framework','project',project_id)['results']\n indicators = [{'id':x['id'],'title':x['title']} for x in results_indicator]\n results_indicator_df = pd.DataFrame(results_indicator)\n results_indicator_df['child_id'] = results_indicator_df['child_projects'].apply(get_children_id)\n results_indicator_df['child_title'] = results_indicator_df['child_projects'].apply(get_children_title)\n results_indicator = results_indicator_df.to_dict('records')\n indicator_periods = []\n for result in results_indicator:\n for indicator in result['indicators']:\n for period in indicator['periods']:\n period.update({'project_id':result['project']})\n period.update({'project_name':result['project_title']})\n period.update({'project_title':result['title']})\n period.update({'parent_project':result['parent_project']})\n period.update({'parent_result':result['parent_result']})\n period.update({'child_project_id':result['child_id']})\n period.update({'child_project_title':result['child_title']})\n period.update({'dimensions':indicator['dimension_names']})\n indicator_periods.append(period)\n indicator_periods = pd.DataFrame(indicator_periods)\n indicator_periods[['period_end_year','period_end_month','period_end_date']] = indicator_periods['period_end'].str.split('-', expand=True)\n indicator_periods[['period_start_year','period_start_month','period_start_date']] = indicator_periods['period_start'].str.split('-', expand=True)\n period_start = indicator_periods.groupby('period_start').size().to_frame('size').reset_index()\n period_end = indicator_periods.groupby('period_end').size().to_frame('size').reset_index()\n period_start.rename(columns={'period_start_year':'start_year'})\n period_end.rename(columns={'period_end_year':'end_year'})\n period_start = period_start.to_dict('records')\n period_end = period_end.to_dict('records')\n indicator_periods = indicator_periods.to_dict('records')\n api = {\n 'dd_indicators': indicators,\n 'dd_start': period_start,\n 'dd_end': period_end,\n 'dd_region': ['Malawi', 'Zambia', 'Mozambique'],\n 'indicator_periods': indicator_periods,\n }\n return jsonify(api)\n\nif __name__ == '__main__':\n app.run(host= '0.0.0.0',debug=True, port=5000)\n","sub_path":"sites/appsa-api/test/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"198627269","text":"\nimport math as m\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport csv\n\n\ndef spotRates_to_DF(rates, T, feq = -1):\n \"\"\" This function converts the spot rates to discount factors\n \n :param rates: spot rates\n :param T: vector that contains the time indices\n :param feq: compounding frequencies\n \"\"\"\n \n DF = []\n if feq == -1:\n for r, t in zip(rates, T):\n DF.append(m.exp(-r*t))\n else:\n for r, t in zip(rates, T):\n DF.append(m.pow(1+r/feq, -feq*t))\n return DF\n\ndef DF_to_Rates(DF, T, feq=-1):\n \"\"\" This function converts the discount factors to \n \n :param rates: spot rates\n :param T: vector that contains the time indices\n :param feq: compounding frequencies\n \"\"\"\n rates = []\n if feq == -1: ##CONTINUOUS COMPONDING RATES\n for t, df in zip(T, DF):\n rates.append(-m.log(df) / t)\n else: ##DISCRETE COMPOUNDING RATES\n for t, df in zip(T, DF):\n rates.append((pow(df, - 1/(t*feq))-1)*feq)\n return rates\n\nclass YieldCurve(object):\n '''\n The Yield Curve class that stores the the discount factor / time to maturity \n that facilitates automatic rates conversions, rates interpolation etc.\n '''\n\n def __init__(self):\n self.DF = []\n self.T = []\n \n def setCurve(self, T, DF):\n '''\n Initialize the yield curve with time to maturity and discount rates\n \n :param T: Time to maturity\n :param DF: Discount Rate\n \n .. warning:: must make sure that T and DF must have the same length\n '''\n self.DF = DF\n self.T = T\n \n def plotCurve(self,feq = -1):\n '''\n Plot the Curve.\n \n Note the plt.show() is needed in the main code to show the plot\n '''\n spotRates = self.getSpotRates(feq)\n plt.plot(self.T,spotRates, label ='Spot Rates')\n\n def getDiscountFactor(self):\n '''\n Returns discount factor\n \n :returns: Discount factor of the yield curve\n '''\n return self.DF\n \n def getMaturityDate(self):\n '''\n Returns the maturity date of yield curve\n \n :returns: Maturity date\n '''\n return self.T\n \n def getSpotRates(self, feq=-1):\n '''\n Compute the spot rates with respect to certain compounding frequencies, default is -1, which is corresponding to continuous compounding.\n \n :param feq: compounding frequencies, feq = -1 indicates continous compounding\n :returns: Spot rates of certain compounding frequencies\n '''\n \n rates = []\n if feq == -1: ##CONTINUOUS COMPONDING RATES\n for t, df in zip(self.T, self.DF):\n rates.append(-m.log(df) / t)\n else: ##DISCRETE COMPOUNDING RATES\n for t, df in zip(self.T, self.DF):\n rates.append((pow(df, - 1.0/(t*feq))-1)*feq)\n return rates\n\n def exportSpotRates(self, exportFileName, feq=-1):\n '''\n Export the spot rates of certain compounding frequencies to a csv file\n \n :param feq: compounding frequencies\n :param exportFileName: path and the name of the file to be exported\n '''\n rates = self.getSpotRates(feq);\n with open(exportFileName, 'wb') as f:\n writer = csv.writer(f, delimiter = ',')\n writer.writerow(['Maturity', 'Spot Rates'])\n for t, r in zip(self.T, rates):\n writer.writerow([t,r])\n \n def getForwardRates_PeriodByPeriod(self, feq=-1):\n '''\n Compute the forward rates\n '''\n if feq == -1:\n forwardRates = [-m.log(self.DF[0]) / self.T[0]]\n for i in range(len(self.DF)-1):\n dT = self.T[i+1] - self.T[i]\n forwardRates.append(-m.log(self.DF[i+1]/self.DF[i]) / dT)\n else:\n forwardRates = [(pow(self.DF[0], -1/self.T[0] / feq) - 1) * feq]\n for i in range(len(self.DF) -1):\n dT = self.T[i+1] - self.T[i]\n forwardRates.append((pow(self.DF[i+1]/self.DF[i], -1 / dT /feq) - 1) * feq)\n return forwardRates\n \n def getForwardRates(self,startT, endT, feq = -1):\n\n startT, startDF = np.asarray(self.getInterpolatedDF(startT, feq))\n endT, endDF = np.asarray(self.getInterpolatedDF(endT, feq))\n forwardDF = endDF / startDF\n \n return DF_to_Rates(forwardDF, endT - startT, feq)\n \n def getParYield(self,startT = 0):\n '''\n T_i = np.arange(0.25,self.T[-1],0.25)\n T_i, DF_i = self.getInterpolatedDF(T_i, 2)\n DF_i = np.asarray(DF_i) \n f = lambda i: 2*(1-DF_i[i]) / np.sum(DF_i[i::-2])\n return T_i, map(f,range(len(T_i)))\n '''\n T_i = np.arange(startT + 0.5, self.T[-1]+0.5, 0.5)\n T_i, DF_i = self.getInterpolatedDF(T_i, 2)\n \n if startT == 0:\n DF_start = [1];\n else:\n startT, DF_start = self.getInterpolatedDF([startT], 2)\n \n FDF_i = np.asarray(DF_i) / DF_start[0]\n f = lambda i: 2*(1-FDF_i[i]) / np.sum(FDF_i[i::-1])\n return T_i, map(f, range(len(T_i)))\n \n def getInterpolatedRates(self, T_int, feq = -1):\n '''\n Assume that the interpolate points T_int are in increasing order\n '''\n rates = self.getSpotRates(feq) ## Get the current rates\n newT = []\n newrates = []\n i = 1;\n for t in T_int:\n if t < self.T[0]:\n continue\n while i < len(self.T) and not(self.T[i-1] <= t < self.T[i]):\n i += 1\n if i == len(self.T):\n if self.T[i-1] == t:\n newrates.append(rates[i-1])\n newT.append(t)\n break\n range_int = self.T[i] - self.T[i-1]\n new_r = (rates[i] * (t - self.T[i-1]) + rates[i-1] * (self.T[i] - t)) / range_int\n newT.append(t)\n newrates.append(new_r)\n return newT, newrates \n \n def getInterpolatedDF(self, T_int, feq = -1):\n newT, newrates = self.getInterpolatedRates(T_int, feq)\n newDF = spotRates_to_DF(newrates, newT, feq)\n return newT, newDF\n \n \n \n ","sub_path":"FixedIncome_Packages/yieldCurve.py","file_name":"yieldCurve.py","file_ext":"py","file_size_in_byte":6368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"131157696","text":"class Solution:\n # @return a list of lists of length 3, [[val1,val2,val3]]\n def threeSum(self, num):\n num.sort()\n n = len(num)\n\n d = {}\n\n for i, v in enumerate(num):\n d[v] = i\n\n ans = set()\n for i in range(0, n - 2):\n for j in range(i + 1, n - 1):\n if num[i] + num[j] + num[j + 1] > 0:\n break\n\n if - (num[i] + num[j]) in d:\n idx = d[-num[i] - num[j]]\n ans.add((num[i], num[j], num[idx]))\n\n return [ list(a) for a in ans ]","sub_path":"3Sum/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"479692464","text":"\"\"\"Author - Maksim Sapunov, msdir6199@gmail.com 15/01/2021\"\"\"\n\n# Задача #6... реализовать два небольших скрипта:\n# Подзадача #2. Итераторб повторяющий элементы некоторого списка, определенного заранее\n\nfrom random import randint\nfrom itertools import cycle\nfrom sys import argv\n\nscript_name, len_of_list = argv\n# Случайное заполнение списка с помощью генератора\nlist_random = [randint(1, 100) for el in range(int(len_of_list))]\n# Определение условия выхода из цикла\nflag = 0\n# Счетчик для визуального оформления вывода\ndivider = 0\n\nfor el in cycle(list_random):\n flag += 1\n if flag > 50:\n break\n else:\n if divider == len(list_random):\n print('\\n--------------')\n divider = 0\n print(el, end=' ')\n divider += 1\n","sub_path":"Python_basic/Lesson_4/L4_Task_6_2.py","file_name":"L4_Task_6_2.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"356963067","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# Experiment Setup\nnp.random.seed(19680801)\nnum_actions = 10\nnum_trials = 2000\nnum_iter = 10000\nepsilon_values = [1e0, 1e-1, 1e-2, 1e-3]\nepsilons = np.array(epsilon_values * num_trials)\nnum_samples = len(epsilons)\n\nq_star_a = np.repeat(np.random.normal(size=[num_actions, num_trials]), len(epsilon_values), axis=1)\noptimal_action = np.argmax(q_star_a, axis=0)\noptimal_actions = np.zeros([num_iter, num_samples], dtype=np.int32)\nR_t_a = np.zeros([num_iter, num_actions, num_samples])\nQ_a = np.zeros([num_actions, num_samples])\nK_a = np.zeros([num_actions, num_samples], dtype=np.int32)\n\n# The first action is always assumed to be the action at index 0\n# Absent prior knowledge, this is equivalent to a random choice\n\nfor t in range(1, num_iter):\n # Select Action\n is_greedy = np.random.random(num_samples) < (1 - epsilons)\n greedy_actions = np.argmax(Q_a, axis=0)\n random_actions = np.random.randint(num_actions, size=num_samples)\n actions = np.where(is_greedy, greedy_actions, random_actions)\n action_idx = actions, np.arange(num_samples)\n optimal_actions[t, actions == optimal_action] += 1\n\n # Sample Environment\n noise_term = np.random.normal(scale=1., size=num_samples)\n R_t_a[t][action_idx] = q_star_a[action_idx] + noise_term\n\n # Update Estimate\n K_a[action_idx] += 1\n step_size = 1 / K_a[action_idx]\n target = R_t_a[t][action_idx]\n old_estimate = Q_a[action_idx]\n\n Q_a[action_idx] = old_estimate + step_size * (target - old_estimate)\n\n\nR_t = np.mean(np.sum(R_t_a, axis=1).reshape([num_iter, num_trials, -1]), axis=1)\nplt.subplot(211)\nfor eps in range(len(epsilon_values)):\n plt.plot(R_t[:, eps], label=\"eps = %f\" % epsilon_values[eps])\nplt.xlabel('Steps')\nplt.ylabel('Average reward')\nplt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,\n ncol=3, mode=\"expand\", borderaxespad=0.)\nplt.subplot(212)\nplt.plot(np.mean(optimal_actions.reshape([num_iter, num_trials, -1]), axis=1))\nplt.xlabel('Steps')\nplt.ylabel('Optimal action')\nplt.show()\n","sub_path":"bandit.py","file_name":"bandit.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"239763278","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Documentation source:\n# - https://gbdev.gg8.se/wiki/articles/Sound_Controller\n\nfrom vsgb.audio.abstract_sound_channel import AbstractSoundChannel\nfrom vsgb.audio.volume_envelope import VolumeEnvelope\nfrom vsgb.io_registers import IO_Registers\n\nclass SoundChannel2(AbstractSoundChannel):\n\n def __init__(self, cgb_mode):\n super().__init__(IO_Registers.NR_21 - 1, 64, cgb_mode)\n self.freq_divider = 0\n self.volume_envelope = VolumeEnvelope()\n\n def start(self):\n self.i = 0\n if self.cgb_mode:\n self.length.reset()\n self.length.start()\n self.volume_envelope.start()\n\n def trigger(self):\n self.i = 0\n self.freq_divider = 1\n self.volume_envelope.trigger()\n\n def step(self, ticks):\n self.volume_envelope.step(ticks)\n e = self.update_length(ticks) and self.dac_enabled\n if not e:\n return 0\n self.freq_divider -= 1\n if self.freq_divider == 0:\n self.reset_freq_divider()\n self.last_output = (self.get_duty() & (1 >> self.i)) >> self.i\n self.i = (self.i + ticks) % 8\n return self.last_output * self.volume_envelope.get_volume()\n\n def set_nr0(self, value):\n super().set_nr0(value)\n\n def set_nr1(self, value):\n super().set_nr1(value)\n self.length.set_length(64 - (value & 0b00111111))\n\n def set_nr2(self, value):\n super().set_nr2(value)\n self.volume_envelope.set_nr2(value)\n self.dac_enabled = (value & 0b11111000) != 0\n\n\n def get_duty(self):\n return {\n 0: 0b00000001,\n 1: 0b10000001,\n 2: 0b10000111,\n 3: 0b01111110\n }.get(self.get_nr1() >> 6)\n\n def reset_freq_divider(self):\n self.freq_divider = self.get_frequency() * 4\n ","sub_path":"vsgb/audio/sound_channel2.py","file_name":"sound_channel2.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"147540212","text":"from __future__ import print_function\n\nimport functools\nimport json\nimport os\nimport re\nimport requests\n\nfrom ngi_pipeline.log.loggers import minimal_logger\nfrom ngi_pipeline.utils.classes import memoized\n\n# Need a better way to log\nLOG = minimal_logger(__name__)\n\n\ntry:\n CHARON_API_TOKEN = os.environ['CHARON_API_TOKEN']\n CHARON_BASE_URL = os.environ['CHARON_BASE_URL']\n # Remove trailing slashes\n m = re.match(r'(?P<url>.*\\w+)/*', CHARON_BASE_URL)\n if m:\n CHARON_BASE_URL = m.groups()[0]\nexcept KeyError as e:\n raise ValueError(\"Could not get required environmental variable \"\n \"\\\"{}\\\"; cannot connect to database.\".format(e))\n\n\n## TODO Might be better just to instantiate this when loading the module. Do we neeed a new instance every time? I don't think so\nclass CharonSession(requests.Session):\n def __init__(self, api_token=None, base_url=None):\n super(CharonSession, self).__init__()\n\n self._api_token = api_token or CHARON_API_TOKEN\n self._api_token_dict = {'X-Charon-API-token': self._api_token}\n self._base_url = base_url or CHARON_BASE_URL\n\n #def get(url_args, *args, **kwargs):\n # url = self.construct_charon_url(url_args)\n # return validate_response(super(CharonSession, self).get(url,\n # headers=self._api_token_dict,\n # *args, **kwargs))\n\n self.get = validate_response(functools.partial(self.get,\n headers=self._api_token_dict, timeout=3))\n self.post = validate_response(functools.partial(self.post,\n headers=self._api_token_dict, timeout=3))\n self.put = validate_response(functools.partial(self.put,\n headers=self._api_token_dict, timeout=3))\n self.delete = validate_response(functools.partial(self.delete,\n headers=self._api_token_dict, timeout=3))\n\n self._project_params = (\"projectid\", \"name\", \"status\", \"pipeline\", \"bpa\")\n self._sample_params = (\"sampleid\", \"status\", \"received\", \"qc_status\",\n \"genotyping_status\", \"genotyping_concordance\",\n \"lims_initial_qc\", \"total_autosomal_coverage\")\n self._libprep_params = (\"libprepid\", \"limsid\", \"status\")\n self._seqrun_params = ('seqrunid', 'sequencing_status', 'alignment_status',\n 'runid', 'seq_qc_flag', 'demux_qc_flag',\n 'mean_coverage', 'std_coverage', 'GC_percentage',\n 'aligned_bases', 'mapped_bases', 'mapped_reads',\n 'total_reads', 'sequenced_bases', 'windows', 'bam_file',\n 'output_file', 'mean_mapping_quality', 'bases_number',\n 'contigs_number', 'mean_autosomal_coverage', 'lanes',\n 'alignment_coverage', 'reads_per_lane')\n self._seqrun_reset_params = tuple(set(self._seqrun_params) - \\\n set(['demux_qc_flag', 'lanes', 'windows', 'seq_qc_flag',\n 'alignment_coverage', 'alignment_status',\n 'sequencing_status', 'total_reads', 'runid', 'seqrunid']))\n\n\n ## Another option is to build this into the get/post/put/delete requests\n ## --> Do we ever need to call this (or those) separately?\n @memoized\n def construct_charon_url(self, *args):\n \"\"\"Build a Charon URL, appending any *args passed.\"\"\"\n return \"{}/api/v1/{}\".format(self._base_url,'/'.join([str(a) for a in args]))\n\n\n ## FIXME There's a lot of repeat code here that might could be condensed\n\n # Project\n def project_create(self, projectid, name=None, status=None, pipeline=None, bpa=None):\n l_dict = locals()\n data = { k: l_dict.get(k) for k in self._project_params }\n return self.post(self.construct_charon_url('project'),\n data=json.dumps(data)).json()\n\n def project_get(self, projectid):\n return self.get(self.construct_charon_url('project', projectid)).json()\n\n\n def project_get_samples(self, projectid):\n return self.get(self.construct_charon_url('samples', projectid)).json()\n \n def project_update(self, projectid, name=None, status=None, pipeline=None, bpa=None):\n l_dict = locals()\n data = { k: l_dict.get(k) for k in self._project_params if l_dict.get(k)}\n return self.put(self.construct_charon_url('project', projectid),\n data=json.dumps(data)).text\n\n def projects_get_all(self):\n return self.get(self.construct_charon_url('projects')).json()\n\n def project_delete(self, projectid):\n return self.delete(self.construct_charon_url('project', projectid)).text\n\n # Sample\n def sample_create(self, projectid, sampleid, status=None, received=None,\n qc_status=None, genotyping_status=None,\n genotyping_concordance=None, lims_initial_qc=None,\n total_autosomal_coverage=None):\n url = self.construct_charon_url(\"sample\", projectid)\n l_dict = locals()\n data = { k: l_dict.get(k) for k in self._sample_params }\n return self.post(url, json.dumps(data)).json()\n\n def sample_get(self, projectid, sampleid):\n url = self.construct_charon_url(\"sample\", projectid, sampleid)\n return self.get(url).json()\n\n def sample_get_libpreps(self, projectid, sampleid):\n return self.get(self.construct_charon_url('libpreps', projectid, sampleid)).json()\n\n def sample_update(self, projectid, sampleid, status=None, received=None,\n qc_status=None, genotyping_status=None,\n genotyping_concordance=None, lims_initial_qc=None,\n total_autosomal_coverage=None):\n url = self.construct_charon_url(\"sample\", projectid, sampleid)\n l_dict = locals()\n data = { k: l_dict.get(k) for k in self._sample_params if l_dict.get(k)}\n return self.put(url, json.dumps(data)).text\n\n ## Eliminate?\n def samples_get_all(self, projectid):\n return self.project_get_samples(projectid)\n #return self.get(self.construct_charon_url('samples', projectid)).json()\n\n # LibPrep\n def libprep_create(self, projectid, sampleid, libprepid, status=None, limsid=None):\n url = self.construct_charon_url(\"libprep\", projectid, sampleid)\n l_dict = locals()\n data = { k: l_dict.get(k) for k in self._libprep_params }\n return self.post(url, json.dumps(data)).json()\n\n def libprep_get(self, projectid, sampleid, libprepid):\n url = self.construct_charon_url(\"libprep\", projectid, sampleid, libprepid)\n return self.get(url).json()\n\n def libprep_get_seqruns(self, projectid, sampleid, libprepid):\n return self.get(self.construct_charon_url('seqruns', projectid, sampleid, libprepid)).json()\n\n\n def libprep_update(self, projectid, sampleid, libprepid, status=None, limsid=None):\n url = self.construct_charon_url(\"libprep\", projectid, sampleid, libprepid)\n l_dict = locals()\n data = { k: l_dict.get(k) for k in self._libprep_params if l_dict.get(k)}\n return self.put(url, json.dumps(data)).text\n\n ## Eliminate?\n def libpreps_get_all(self, projectid, sampleid):\n return self.sample_get_libpreps(projectid, sampleid)\n #return self.get(self.construct_charon_url('libpreps', projectid, sampleid)).json()\n\n # SeqRun\n def seqrun_create(self, projectid, sampleid, libprepid, seqrunid,\n total_reads, mean_autosomal_coverage, reads_per_lane=None,\n sequencing_status=None, alignment_status=None, runid=None,\n seq_qc_flag=None, demux_qc_flag=None, mean_coverage=None,\n std_coverage=None, GC_percentage=None, aligned_bases=None,\n mapped_bases=None, mapped_reads=None,\n sequenced_bases=None, windows=None, bam_file=None,\n output_file=None, mean_mapping_quality=None,\n bases_number=None, contigs_number=None,\n lanes=None,\n alignment_coverage=None):\n url = self.construct_charon_url(\"seqrun\", projectid, sampleid, libprepid)\n l_dict = locals()\n data = { k: l_dict.get(k) for k in self._seqrun_params }\n return self.post(url, json.dumps(data)).json()\n\n def seqrun_get(self, projectid, sampleid, libprepid, seqrunid):\n url = self.construct_charon_url(\"seqrun\", projectid, sampleid, libprepid, seqrunid)\n return self.get(url).json()\n\n def seqrun_update(self, projectid, sampleid, libprepid, seqrunid,\n total_reads=None, mean_autosomal_coverage=None, reads_per_lane=None,\n sequencing_status=None, alignment_status=None, runid=None,\n seq_qc_flag=None, demux_qc_flag=None, mean_coverage=None,\n std_coverage=None, GC_percentage=None, aligned_bases=None,\n mapped_bases=None, mapped_reads=None,\n sequenced_bases=None, windows=None, bam_file=None,\n output_file=None, mean_mapping_quality=None,\n bases_number=None, contigs_number=None,\n lanes=None, alignment_coverage=None,\n *args, **kwargs):\n ## TODO Consider implementing for allathese functions\n if args: LOG.debug(\"Ignoring extra args: {}\".format(\", \".join(*args)))\n if kwargs: LOG.debug(\"Ignoring extra kwargs: {}\".format(\", \".join([\"{}: {}\".format(k,v) for k,v in kwargs.iteritems()])))\n url = self.construct_charon_url(\"seqrun\", projectid, sampleid, libprepid, seqrunid)\n l_dict = locals()\n data = { k: str(l_dict.get(k)) for k in self._seqrun_params if l_dict.get(k)}\n return self.put(url, json.dumps(data)).text\n\n def seqrun_reset(self, projectid, sampleid, libprepid, seqrunid):\n url = self.construct_charon_url(\"seqrun\", projectid, sampleid, libprepid, seqrunid)\n data = { k: None for k in self._seqrun_reset_params}\n return self.put(url, json.dumps(data)).text\n\n\n def seqruns_get_all(self, projectid, sampleid, libprepid):\n return self.libprep_get_seqruns(projectid, sampleid, libprepid)\n #return self.get(self.construct_charon_url('seqruns', projectid, sampleid, libprepid)).json()\n\n\n## TODO create different CharonError subclasses for different codes (e.g. 400, 404)\nclass CharonError(Exception):\n def __init__(self, message, status_code=None, *args, **kwargs):\n self.status_code = status_code\n super(CharonError, self).__init__(message, *args, **kwargs)\n\n\nclass validate_response(object):\n \"\"\"\n Validate or raise an appropriate exception for a Charon API query.\n \"\"\"\n def __init__(self, f):\n self.f = f\n ## Should these be class attributes? I don't really know\n self.SUCCESS_CODES = (200, 201, 204)\n # There are certainly more failure codes I need to add here\n self.FAILURE_CODES = {\n 400: (CharonError, (\"Charon access failure: invalid input \"\n \"data (reason '{response.reason}' / \"\n \"code {response.status_code} / \"\n \"url '{response.url}')\")),\n 404: (CharonError, (\"Charon access failure: not found \"\n \"in database (reason '{response.reason}' / \"\n \"code {response.status_code} / \"\n \"url '{response.url}')\")), # when else can we get this? malformed URL?\n 405: (CharonError, (\"Charon access failure: method not \"\n \"allowed (reason '{response.reason}' / \"\n \"code {response.status_code} / \"\n \"url '{response.url}')\")),\n 409: (CharonError, (\"Charon access failure: document \"\n \"revision conflict (reason '{response.reason}' / \"\n \"code {response.status_code} / \"\n \"url '{response.url}')\")),}\n\n def __call__(self, *args, **kwargs):\n response = self.f(*args, **kwargs)\n if response.status_code not in self.SUCCESS_CODES:\n try:\n err_type, err_msg = self.FAILURE_CODES[response.status_code]\n except KeyError:\n # Error code undefined, used generic text\n err_type = CharonError\n err_msg = (\"Charon access failure: {response.reason} \"\n \"(code {response.status_code} / url '{response.url}')\")\n raise err_type(err_msg.format(**locals()), response.status_code)\n return response\n","sub_path":"ngi_pipeline/database/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":13033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"649069031","text":"def ready_arguments(fname_or_dict, highRes):\n import numpy as np\n import pickle\n import chumpy as ch\n from chumpy.ch import MatVecMult\n from dataset.smpl_layer.posemapper import posemap\n import scipy.sparse as sp\n\n if not isinstance(fname_or_dict, dict):\n dd = pickle.load(open(fname_or_dict, 'rb'), encoding='latin1')\n # dd = pickle.load(open(fname_or_dict, 'rb'))\n else:\n dd = fname_or_dict\n\n want_shapemodel = 'shapedirs' in dd\n nposeparms = dd['kintree_table'].shape[1] * 3\n\n if 'trans' not in dd:\n dd['trans'] = np.zeros(3)\n if 'pose' not in dd:\n dd['pose'] = np.zeros(nposeparms)\n if 'shapedirs' in dd and 'betas' not in dd:\n dd['betas'] = np.zeros(dd['shapedirs'].shape[-1])\n\n for s in ['v_template', 'weights', 'posedirs', 'pose', 'trans', 'shapedirs', 'betas', 'J']:\n if (s in dd) and isinstance(dd[s], ch.ch.Ch):\n dd[s] = dd[s].r\n\n if want_shapemodel:\n dd['v_shaped'] = dd['shapedirs'].dot(dd['betas']) + dd['v_template']\n v_shaped = dd['v_shaped']\n J_tmpx = MatVecMult(dd['J_regressor'], v_shaped[:, 0])\n J_tmpy = MatVecMult(dd['J_regressor'], v_shaped[:, 1])\n J_tmpz = MatVecMult(dd['J_regressor'], v_shaped[:, 2])\n dd['J'] = ch.vstack((J_tmpx, J_tmpy, J_tmpz)).T\n dd['v_posed'] = v_shaped + dd['posedirs'].dot(posemap(dd['bs_type'])(dd['pose']))\n else:\n dd['v_posed'] = dd['v_template'] + dd['posedirs'].dot(posemap(dd['bs_type'])(dd['pose']))\n\n if highRes is not None:\n with open(highRes, 'rb') as f:\n mapping, hf = pickle.load(f, encoding='latin1')\n num_betas = dd['shapedirs'].shape[-1]\n hv = mapping.dot(dd['v_template'].ravel()).reshape(-1, 3)\n J_reg = dd['J_regressor'].asformat('csr')\n dd['f'] = hf\n dd['v_template'] = hv\n dd['weights'] = np.hstack([\n np.expand_dims(\n np.mean(\n mapping.dot(np.repeat(np.expand_dims(dd['weights'][:, i], -1), 3)).reshape(-1, 3)\n , axis=1),\n axis=-1)\n for i in range(24)\n ])\n dd['posedirs'] = mapping.dot(dd['posedirs'].reshape((-1, 207))).reshape(-1, 3, 207)\n dd['shapedirs'] = mapping.dot(dd['shapedirs'].reshape((-1, num_betas))).reshape(-1, 3, num_betas)\n dd['J_regressor'] = sp.csr_matrix((J_reg.data, J_reg.indices, J_reg.indptr), shape=(24, hv.shape[0]))\n\n return dd\n","sub_path":"dataset/smpl_layer/serialization.py","file_name":"serialization.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"111271814","text":"# sum of digit\n\nnumber = int(input('enter a digit'))\ntotal = 0\nwhile number>0:\n r = number % 10 # get the last digit\n total += r # add the digit to total\n number = number // 10 # remove the last digit from number\n\nprint('total',total)","sub_path":"basics/while_ex2.py","file_name":"while_ex2.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"65495968","text":"# coding=utf-8\nimport codecs\nfrom collections import defaultdict\nimport fileinput\n\nimport os\nimport re\n\nVERNUM_PATTERN = r'REPGA_v(\\d+\\.){3}\\d'\nSCHEMA_NAME_PATTERN = r'\\w+_\\[MIS\\w*\\]'\nRUN_ALL_FNAME_PATTERN = r'run_all_\\d+_' + VERNUM_PATTERN + '_' + SCHEMA_NAME_PATTERN + '\\.sql'\n\n\ndef check_folder_name(value):\n \"\"\" Patch verzioszamamnak ellenorzese \"\"\"\n errors = []\n if not re.match('^' + VERNUM_PATTERN + '$', value):\n errors.append('Érvénytelen verziószám.')\n\n return errors\n\n\ndef check_main_dir(install_desc_fname):\n \"\"\" A patch fokonyvtaranak ellenorzese. \"\"\"\n\n if install_desc_fname not in os.listdir(os.curdir):\n raise IOError('Nem található %s nevű telepítési leírás a főkönyvtárban.' % install_desc_fname)\n\n return parse_install_file(install_desc_fname), __find_run_alls_in_desc(\n install_desc_fname)\n\n\ndef parse_install_file(install_desc_fname):\n \"\"\" Az installaciot leiro fajl ellenorzese \"\"\"\n\n keywords = __get_keywords()\n with codecs.open(install_desc_fname, encoding='cp1252') as descfile:\n for descline in descfile:\n for keyword in keywords:\n if keyword in descline:\n keywords.remove(keyword)\n\n errors = ['Nincs megadva a(z) %s mező' % kw for kw in keywords]\n\n return errors\n\n\ndef __find_run_alls_in_desc(install_desc_fname):\n run_alls = []\n with open(install_desc_fname) as descfile:\n for line in descfile:\n run_all_match = re.search(RUN_ALL_FNAME_PATTERN, line)\n if run_all_match:\n run_alls.append(run_all_match.group())\n\n return set(run_alls)\n\n\ndef __get_keywords():\n ret = []\n try:\n with codecs.open(os.path.join(os.path.dirname(__file__),\n '../../conf/temp_install.txt'),\n encoding='cp1252') as kwfile:\n for keyword in kwfile:\n ret.append(keyword.strip())\n except IOError:\n raise IOError('Hiba a conf/temp_install.txt fájl megnyitása közben.')\n\n return ret\n\n\ndef check_docs_dir(ver):\n \"\"\" A dokumentumok konyvtar ellenorzese. \"\"\"\n docs_dirname = '1_Dokumentumok'\n if docs_dirname not in os.listdir(os.curdir):\n return ['A patchben nincs Dokumentumok könyvtár.']\n\n pattern = '^FAT_' + ver + '.xlsx?$'\n for fn in os.listdir(os.path.join(os.curdir, docs_dirname)):\n if re.match(pattern, fn):\n return []\n return ['Hiányzó vagy hibás nevű FAT állomány.']\n\n\n\ndef check_db_dir(described_run_alls):\n \"\"\" Az adatbazis konyvtar fajljainak ellenorzese. \"\"\"\n errors = []\n db_dirname = 'Adatbazis'\n if db_dirname not in os.listdir(os.curdir):\n raise IOError('Nem található a patch Adatbazis mappája.')\n\n run_alls_in_db_dir = set([fname for fname in os.listdir(db_dirname) if\n re.match('^' + RUN_ALL_FNAME_PATTERN + '$',\n fname)])\n\n not_existing_run_alls = described_run_alls - run_alls_in_db_dir\n undescribed_run_alls = run_alls_in_db_dir - described_run_alls\n errors.extend(\n ['A telepítési fájlban megadott %s fájl nem létezik' % ra for ra in\n not_existing_run_alls])\n errors.extend(\n ['A(z) %s fájl nem található a telepítése leírásban' % ra for ra in\n undescribed_run_alls])\n\n schemas = [re.search('(?<=_)' + SCHEMA_NAME_PATTERN, fn).group() for fn in\n run_alls_in_db_dir]\n\n run_all_file_errors, scripts = check_run_all_files(\n [os.path.join('Adatbazis', ra) for ra in run_alls_in_db_dir])\n return errors, run_all_file_errors, schemas, scripts\n\n\ndef check_run_all_files(run_alls):\n \"\"\" A runall file-ok adatainak beolvasasa. \"\"\"\n errors = []\n scripts = defaultdict(list)\n for line in fileinput.input(run_alls):\n line = line.strip()\n included_script = re.match(\n '@(' + SCHEMA_NAME_PATTERN + r'([/|\\\\]\\w+)+\\.sql)', line)\n fname = os.path.basename(fileinput.filename())\n if included_script:\n scripts[included_script.group(1).replace('\\\\', '/')].append(fname)\n\n if line.startswith('SPOOL ./_Install_Logs/'):\n log_file_match = re.match(\n r'SPOOL \\./_Install_Logs/([\\w\\.\\[\\]]*)(?=_&)', line)\n if not log_file_match or log_file_match.group(1) + '.sql' != fname:\n errors.append('Nem egyezik a log neve a %s fájlban.' % fname)\n\n return errors, scripts\n\n\ndef check_db_folder_dirs(dirs_in_db_folder):\n \"\"\" Az Adatbazis konyvtar konyvtarainak ellenorzese \"\"\"\n if not dirs_in_db_folder:\n return ['Az Adatbázis könyvtár nem tartalmaz könyvtárakat.']\n\n if '_Install_Logs' not in dirs_in_db_folder:\n return ['Az Adatbázis konyvtarban nincs _Install_Logs nevű konyvtár']\n\n return []\n\n\ndef check_schema_dirs(schemas, dirs_in_db_folder):\n errors = []\n existing_schema_folders = set(schemas).intersection(dirs_in_db_folder)\n errors.extend(['A(z) %s sémához nem található mappa.' % schema for schema in\n set(schemas) - existing_schema_folders])\n errors.extend(['A(z) %s séma mappája üres.' % schema for schema in\n existing_schema_folders if\n not os.listdir(os.path.join('Adatbazis', schema))])\n\n return errors\n\n\ndef check_script_dirs(dirs_in_db_folders, scripts_in_run_alls):\n \"\"\" A semakonyvtarak ellenorzese \"\"\"\n ilog_folder_name = '_Install_Logs'\n if ilog_folder_name in dirs_in_db_folders:\n dirs_in_db_folders.remove('_Install_Logs')\n\n sql_files = []\n\n for schema_dir in dirs_in_db_folders:\n sql_files_dir = os.path.join('Adatbazis', schema_dir)\n for dirpath, dirnames, fnames in os.walk(sql_files_dir):\n sql_files.extend(\n [dirpath.replace('Adatbazis\\\\', '').replace('\\\\', '/') + '/' + fname for fname in fnames if\n fname.endswith('.sql')])\n\n errors = []\n existing_sql_files = set(sql_files)\n referenced_scripts_in_run_alls = set(scripts_in_run_alls.keys())\n\n errors.extend(\n ['A(z) %s nevű script egy run_all fájlban sem szerepel.' % sql for sql\n in existing_sql_files - referenced_scripts_in_run_alls])\n\n not_existing_scripts = referenced_scripts_in_run_alls - existing_sql_files\n errors.extend([\n 'A(z) %s nevű script benne van a %s fájl(ok)ban, de nem létezik.' % (\n script, ','.join(scripts_in_run_alls[script])) for script in\n not_existing_scripts])\n\n return errors\n\n\ndef check_install_logs_folder():\n ilog_folder_path = 'Adatbazis/_Install_Logs'\n if not os.path.isdir(ilog_folder_path):\n return ['A patch nem tartalmaz %s mappát.' % ilog_folder_path]\n logs = os.listdir(ilog_folder_path)\n if not logs:\n return ['A patch %s mappája üres.' % ilog_folder_path]\n return ['A(z) %s install log fájl kiterjesztése érvénytelen.' % fname for fname\n in logs if not fname.endswith('.log')]\n\n\ndef find_errors():\n \"\"\" A hibak ellenorzeset vegzo fuggvenyek meghivasa \"\"\"\n\n # TODO eliminate the repeated errors.extend(...) calls -> something similar to a list literal\n vernum = os.path.basename(os.getcwd())\n errors = []\n errors.extend(check_folder_name(vernum))\n\n install_desc_fname = 'Telepitesi_leiras_' + vernum + \".txt\"\n main_dir_errors, run_alls = check_main_dir(install_desc_fname)\n errors.extend(main_dir_errors)\n\n errors.extend(check_docs_dir(vernum))\n\n db_dir_errors, run_all_errors, schemas, scripts = check_db_dir(set(run_alls))\n errors.extend(db_dir_errors)\n errors.extend(run_all_errors)\n\n dirs_in_db_folder = [os.path.basename(dirname) for dirname in\n os.listdir('Adatbazis') if\n os.path.isdir(os.path.join('Adatbazis', dirname))]\n errors.extend(check_db_folder_dirs(dirs_in_db_folder))\n\n errors.extend(check_schema_dirs(schemas, dirs_in_db_folder))\n\n errors.extend(check_script_dirs(dirs_in_db_folder, scripts))\n\n errors.extend(check_install_logs_folder())\n\n return errors\n\ndef run_old_checks():\n try:\n return find_errors()\n except IOError as detail:\n raise ValueError(detail)\n\n\n","sub_path":"pyv/pyv/engine/old.py","file_name":"old.py","file_ext":"py","file_size_in_byte":8251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"26198796","text":"import xlrd\nimport xlwt\nimport json\n\nmainObj = {}\nheadLines = []\noutputRows = []\nloc = \"/Users/joel/Documents/DataFiles/HistoryOMX.xls\"\noutLoc = \"/Users/joel/Documents/DataFiles/HistoryOMXformatted.xlsx\"\n\nwb = xlrd.open_workbook(loc)\nsheet = wb.sheet_by_index(0)\nprint(sheet)\nnumCols = sheet.ncols\nnRows = sheet.nrows\n\n\ndef looper():\n rowList = []\n for i in range(nRows):\n if i != 0:\n for j in range(len(sheet.row(i))-4):\n rowList.append(sheet.cell_value(i, j))\n recAdd(rowList, mainObj)\n rowList = []\n else:\n for j in range(len(sheet.row(i))-1):\n headLines.append(sheet.cell_value(i, j))\n mainObj['HeadLines'] = headLines\n\n\ndef recAdd(data, obj):\n if len(data) > 0:\n if data[0] in obj:\n sendObj = obj[data[0]]\n data.pop(0)\n recAdd(data, sendObj)\n else:\n obj[data[0]] = {}\n sendObj = obj[data[0]]\n data.pop(0)\n recAdd(data, sendObj)\n \n return\n\ndef prepForSum(myDict):\n del myDict[\"HeadLines\"]\n myDict = sumLastRow(myDict, [])\n myDict[\"HeadLines\"] = headLines\n return myDict\n\n\ndef sumLastRow(myDict, keys):\n if(len(myDict) != 0):\n for key in myDict.keys():\n keys.append(key)\n \n if(len(myDict[key]) == 0):\n myDict = sum(myDict.keys())/len(myDict.keys())\n return myDict\n else:\n myDict[key] = sumLastRow(myDict[key], keys)\n return myDict\n\ndef concatRowVector(obj, values):\n for key in obj.keys():\n myValues = [] + values\n if(key != \"HeadLines\"):\n if type(obj[key]) is dict:\n myValues.append(key)\n concatRowVector(obj[key], myValues)\n else:\n valVec = myValues + [key, obj[key]]\n outputRows.append(valVec)\n\ndef writeToExcel():\n outWb = xlwt.Workbook(encoding = 'ascii')\n worksheet = outWb.add_sheet('Sheet')\n for i in range(len(outputRows)):\n for j in range(len(outputRows[i])):\n worksheet.write(i, j, label = outputRows[i][j])\n outWb.save(outLoc)\n\n\n\n#Calc length of the lowest tier. May not be used\ndef calcLength(obj):\n for key in obj.keys():\n if(key != \"HeadLines\"):\n if type(obj[key]) is dict:\n length = calcLength(obj[key])\n else:\n length = len(obj)\n return length\n\n\nlooper()\nmaiObj = prepForSum(mainObj)\n\nconcatRowVector(mainObj, [])\n\nif True:\n headLines = ['Year', 'Month', 'Cost']\n mainObj[\"HeadLines\"] = headLines\n outputRows.insert(0, headLines)\n\nwriteToExcel()\nprint(\"Finish\")","sub_path":"generalExcelFormatter.py","file_name":"generalExcelFormatter.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"488029123","text":"import numpy as np\nimport scipy.io as scio\nimport matplotlib.pyplot as plt\nimport torch.utils.data.dataset\n\n\nclass matSet(torch.utils.data.dataset.Dataset):\n def __init__(self, path, mode):\n super(matSet, self).__init__()\n self.mat = scio.loadmat(path)[mode]\n self.mode = mode\n\n\n def __getitem__(self, item):\n return torch.tensor(self.mat[item], dtype=torch.float)\n\n def __len__(self):\n return self.mat.shape[0]\n\n def show_plt(self):\n plt.scatter(self.mat.T[0], self.mat.T[1], label=self.mode, alpha=0.2, c='r')\n\n\nif __name__ == '__main__':\n pointsA = matSet('./points.mat', 'a')\n pointsB = matSet('./points.mat', 'b')\n pointsC = matSet('./points.mat', 'c')\n pointsD = matSet('./points.mat', 'd')\n pointsXX = matSet('./points.mat', 'xx')\n # xx 8192\n #\n # print(points.mat.shape)\n # points.mat = points.mat.T\n # print(points.mat.shape)\n # plt.plot(points.mat[0], points.mat[1], '.')\n # for x in range(len(points)):\n # plt.scatter(points[x][0], points[x][1])\n # pointsA.show_plt()\n # pointsB.show_plt()\n # pointsC.show_plt()\n # pointsD.show_plt()\n pointsXX.show_plt()\n plt.legend()\n plt.show()\n\n","sub_path":"lab5/data_load.py","file_name":"data_load.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"232526589","text":"from selenium import webdriver\n\nfrom webdriver_manager.chrome import ChromeDriverManager\n\n\ndef test_chrome_manager_with_selenium():\n driver_path = ChromeDriverManager().install()\n driver = webdriver.Chrome(driver_path)\n driver.get(\"http://automation-remarks.com\")\n driver.close()\n","sub_path":"tests_xdist/test_cuncurent_2.py","file_name":"test_cuncurent_2.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"654479646","text":"# coding: utf-8\n\n'''\n分别用 Lax-Friedrichs, Lax-Wendroff, Roe, ENO 求解一维激波管问题.\n\n方程(下标表示偏导数):\n (rho, rho*u, E)_t + (rho*u, rho*u**2 + p, u*(E + p))_x = 0\n初始条件:\n (rho, u, p) = x<=0.5: (0.5, 0, 0.571); x>0.5: (0.445, 0.698, 3.528)\n\n参考教材: 计算流体力学基础及其应用,John D. Anderson(中文版)\n'''\n\nfrom __future__ import division\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib import animation\n\n\ndef Animation(x=None, u=None, nt=0):\n '''\n :param x:\n :param u: 所有时间步的数值解,是一个二维矩阵,矩阵每一行表示某个时间步的数值解\n :param nt:\n :return:\n '''\n # 图像所在区域的大小\n xmin, xmax = -0.01, 1.01\n ymin, ymax = -1, 2\n # xmin, xmax = 0, 1\n # ymin, ymax = 0.22, 0.72\n\n fig = plt.figure()\n ax = plt.axes(xlim=(xmin, xmax), ylim=(ymin, ymax))\n ln, = ax.plot([], [], lw=2, animated=True)\n\n def init():\n ln.set_data([], [])\n return ln,\n\n def update(frame): # 这里参数表示帧数frame\n un = u[frame, :]\n # print(un)\n ln.set_data(x, un)\n return ln,\n\n ani = animation.FuncAnimation(fig, update, frames=nt, init_func=init, blit=True, interval=200)\n ani.save('/home/fan/Lax_Wendroff_pressure.mpeg', writer=\"ffmpeg\")\n\n plt.title(\"Lax_Wendroff_pressure\")\n plt.show()\n\n\ndef Lax_Friedrichs(rho=0, rho_u=0, E=0, dx=0, dt=0, nx=0, nt=0, animate=1):\n '''\n 利用Lax-Friedrichs格式求解,守恒形式的差分格式为: \\partial F / \\partial t + \\partial G / \\partial x = 0\n animate: 1, 2, 3 分别画出 rho, u, p 的动图\n '''\n if dt > dx:\n raise ValueError(\"The scheme is not stable!!!\")\n def conserv2origin(rho=0, rho_u=0, E=0):\n '''\n 把守恒变量 (rho, rho*u, E) 转化为原始变量 (rho, u, p).\n 重点计算 E,见参考教材p58,p62\n '''\n u = rho_u / rho\n gamma = 1.4 # 对于空气,是个常数\n p = (gamma - 1) * (E - 0.5 * rho * u**2)\n return (rho, u, p)\n\n rho, u, p = conserv2origin(rho=rho, rho_u=rho_u, E=E) # 将初始的守恒变量转换成初始的原始变量\n\n # 保存所有时间部的计算结果,可以用来画动画\n rho_n = np.zeros([nt, nx])\n rho_u_n = np.zeros([nt, nx])\n E_n = np.zeros([nt, nx])\n\n # 初值\n rho_n[0, :] = rho\n rho_u_n[0, :] = rho_u\n E_n[0, :] = E\n\n # 假定边界条件如下\n rho_n[:, 0] = 0.5\n rho_n[:, -1] = 0.445\n rho_u_n[:, 0] = rho_u[0]\n rho_u_n[:, -1] = rho_u[-1]\n E_n[:, 0] = E[0]\n E_n[:, -1] = E[-1]\n\n for t in range(1, nt):\n for i in range(1, nx-1):\n rho_n[t, i] = 0.5 * (rho_n[t-1, i+1] + rho_n[t-1, i-1]) \\\n - dt * (rho[i+1]*u[i+1] - rho[i-1]*u[i-1]) / (2 * dx)\n\n rho_u_n[t, i] = 0.5 * (rho_u_n[t-1, i+1] + rho_u_n[t-1, i-1]) \\\n - dt * ((rho[i+1]*u[i+1]**2 + p[i+1]) - (rho[i-1]*u[i-1]**2 + p[i-1])) / (2 * dx)\n\n E_n[t, i] = 0.5 * (E_n[t-1, i+1] + E_n[t-1, i-1]) \\\n - dt * (u[i+1]*(E_n[t-1, i+1] + p[i+1]) - u[i-1]*(E_n[t-1, i-1] + p[i-1])) / (2 * dx)\n\n # 更新当前步的值\n rho, u, p = conserv2origin(rho=rho_n[t, :], rho_u=rho_u_n[t, :], E=E_n[t, :])\n\n # 把得到的所有时间步步的守恒变量的值转换为原始变量的值\n rho_n, u_n, p_n = conserv2origin(rho=rho_n, rho_u=rho_u_n, E=E_n)\n\n if animate == 1:\n Animation(x=np.linspace(0, 1, nx), u=rho_n, nt=nt)\n elif animate == 2:\n Animation(x=np.linspace(0, 1, nx), u=u_n, nt=nt)\n elif animate == 3:\n Animation(x=np.linspace(0, 1, nx), u=p_n, nt=nt)\n else: raise ValueError(\"No matches!\")\n\n\ndef Lax_Wendroff(rho=0, rho_u=0, E=0, dx=0, dt=0, nx=0, nt=0, animate=1):\n '''\n 利用Lax-Wendroff格式求解,守恒形式的差分格式为: \\partial F / \\partial t + \\partial G / \\partial x = 0\n animate: 1, 2, 3 分别画出 rho, u, p 的动图\n '''\n if dt > dx:\n raise ValueError(\"The scheme is not stable!!!\")\n def conserv2origin(rho=0, rho_u=0, E=0):\n '''\n 把守恒变量 (rho, rho*u, E) 转化为原始变量 (rho, u, p).\n 重点计算 E,见参考教材p58,p62\n '''\n u = rho_u / rho\n gamma = 1.4 # 对于空气,是个常数\n p = (gamma - 1) * (E - 0.5 * rho * u**2)\n return (rho, u, p)\n\n rho, u, p = conserv2origin(rho=rho, rho_u=rho_u, E=E) # 将初始的守恒变量转换成初始的原始变量\n\n # 保存所有时间步的计算结果,可以用来画动画\n rho_n = np.zeros([nt, nx])\n rho_u_n = np.zeros([nt, nx])\n E_n = np.zeros([nt, nx])\n\n # 初值\n rho_n[0, :] = rho\n rho_u_n[0, :] = rho_u\n E_n[0, :] = E\n\n # 假定任意时刻的边界条件如下\n rho_n[:, 0] = 0.5\n rho_n[:, -1] = 0.445\n rho_u_n[:, 0] = rho_u[0]\n rho_u_n[:, -1] = rho_u[-1]\n E_n[:, 0] = E[0]\n E_n[:, -1] = E[-1]\n\n for t in range(1, nt):\n for i in range(1, nx-1):\n rho_n[t, i] = rho_n[t-1, i] \\\n - (dt/dx) * (rho[i+1]*u[i+1] - rho[i-1]*u[i-1]) / 2 \\\n + (dt/dx)**2 * (rho[i+1]*u[i+1] - 2*rho[i]*u[i] + rho[i-1]*u[i-1]) / 2\n\n rho_u_n[t, i] = rho_u_n[t-1, i] \\\n - (dt/dx) * ((rho[i+1]*u[i+1]**2 + p[i+1]) - (rho[i-1]*u[i-1]**2 + p[i-1])) / 2 \\\n + (dt/dx)**2 * ((rho[i+1]*u[i+1]**2 + p[i+1]) - 2*(rho[i]*u[i]**2 + p[i]) + (rho[i-1]*u[i-1]**2 + p[i-1])) / 2\n\n E_n[t, i] = E_n[t-1, i] \\\n - (dt/dx) * (u[i+1]*(E_n[t-1, i+1] + p[i+1]) - u[i-1]*(E_n[t-1, i-1] + p[i-1])) / 2 \\\n + (dt/dx)**2 * (u[i+1] * (E_n[t-1, i+1] + p[i+1]) - 2*u[i]*(E_n[t-1, i] + p[i]) + u[i-1]*(E_n[t-1, i-1] + p[i-1])) / 2\n\n # 更新当前步的值\n rho, u, p = conserv2origin(rho=rho_n[t, :], rho_u=rho_u_n[t, :], E=E_n[t, :])\n\n rho_n, u_n, p_n = conserv2origin(rho=rho_n, rho_u=rho_u_n, E=E_n)\n\n if animate == 1:\n Animation(x=np.linspace(0, 1, nx), u=rho_n, nt=nt)\n elif animate == 2:\n Animation(x=np.linspace(0, 1, nx), u=u_n, nt=nt)\n elif animate == 3:\n Animation(x=np.linspace(0, 1, nx), u=p_n, nt=nt)\n else: raise ValueError(\"No matches!\")\n\n\ndef Roe():\n\n pass\ndef ENO():\n\n pass\n\n\nif __name__ == '__main__':\n nx = 101 # 区间[0, 1]的节点个数\n dx = 1 / (nx - 1) # 空间步长\n nt = 30 # 模拟多少个时间步\n dt = 0.0005 # 时间步长\n\n # 密度rho的初值\n rho = np.zeros(nx)\n rho[0: int(0.5 / dx + 1)] = 0.5\n # rho[int(0.5 / dx + 1): int(1 / dx + 1)] = 0.445\n rho[int(0.5 / dx + 1):] = 0.445\n\n # 速度u的初值\n u = np.zeros(nx)\n u[int(0.5/dx + 1):] = 0.698\n\n # 能量E的初值\n E = np.zeros(nx)\n E[0: int(0.5 / dx + 1)] = 0.571\n # E[int(0.5 / dx + 1): int(1 / dx + 1)] = 3.528\n E[int(0.5 / dx + 1):] = 3.528\n\n\n # ------------------------------------- Lax-Friedrichs 格式 -----------------------------------------------\n # Lax_Friedrichs(rho=rho, rho_u=rho*u, E=E, dx=dx, dt=dt, nx=nx, nt=nt, animate=3) # animate: 1, 2, 3 分别画出 rho, u, p 的动图\n\n\n # -------------------------------------- Lax-Wendroff 格式 -------------------------------------------------\n Lax_Wendroff(rho=rho, rho_u=rho*u, E=E, dx=dx, dt=dt, nx=nx, nt=nt, animate=3) # animate: 1, 2, 3 分别画出 rho, u, p 的动图\n\n\n # ------------------------------------------- Roe 格式 -----------------------------------------------------\n\n\n # ------------------------------------------- ENO 格式 -----------------------------------------------------\n","sub_path":"cfd_python/difference_schemes.py","file_name":"difference_schemes.py","file_ext":"py","file_size_in_byte":7742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"594097019","text":"import requests, csv\nimport numpy as np\nfrom bs4 import BeautifulSoup\nimport re, os, requests\nfrom url import url\nfrom file import file\nfrom multiprocessing import Pool\n\nmonth = 5\nyear = 2020\n\nif __name__=='__main__':\n\n # 测试file.py 文件功能\n path = \"F:\\H_img\"\n folder_name = str(year) + \"-\" + str(month)\n os.chdir(path)\n os.mkdir(folder_name)\n os.chdir(path + \"\\\\\" + folder_name)\n \n p = Pool(8)\n \n # 测试 url.py 文件功能\n total_info = url().get_info(year, month)\n print(len(total_info[1]))\n pre_url = total_info[4]\n ori_url = url().ori_url(pre_url)\n # print(ori_url)\n # 测试成功!\n\n print(total_info)\n \n \n rank = 1\n for url in ori_url:\n p.apply_async(file().download, args=(url, rank, total_info[1][rank-1]))\n rank += 1\n p.close()\n p.join()\n\n# headers = {\n# \"user-agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36\",\n# \"referer\":\"https://www.pixiv.net/ranking.php\"\n# }\n\n# baseurl='https://www.pixiv.net/ranking.php?mode=monthly&content=illust&date=20200501'\n\n\n# html=requests.get(baseurl, headers=headers)\n# soup = BeautifulSoup(html.content, 'lxml')\n\n# all_infos = soup.find_all(class_=\"ranking-item\")\n\n# l_urls = []\n# l_ranks = []\n# l_pids = []\n# l_titles = []\n# l_authors = []\n\n# rank = 1\n# for info in all_infos:\n# url = info.find(\"img\").get('data-src')\n# pid = re.search('\\d{7,9}', url).group()\n# l_pids.append(pid)\n# l_urls.append(url)\n# l_titles.append(info.get(\"data-title\"))\n# l_authors.append(info.get(\"data-user-name\"))\n# l_ranks.append(rank)\n# rank += 1\n\n# total_info = np.transpose(np.array([l_ranks, l_titles, l_authors, l_pids,l_urls]))\n# print(total_info)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"171370998","text":"\"\"\"Tools to preprocess GPR lines before processing in third-party software such as ReflexW\"\"\"\n\nfrom os.path import isfile, join\nimport numpy as np\nimport pandas as pd\nimport math\nfrom collections import Counter\n\nfrom .gpr import MetaData, x_flip, empty_array\nfrom .mala import rad2dict, RD3, arr2rd3, Line\nfrom .filesystem import list_gpr_data, get_folder_and_filename\nfrom .calculations import ns2mm\n\n\nclass Coordinates(MetaData):\n \"\"\"Append coordinate data to a loaded collection of parallel segments. It may be sensible to put the loaded data through a grouping class to enable filtering of non-parallel segments.\"\"\"\n\n def __init__(self, segments, filename='segment_coordinates.csv', columns=[]):\n \"\"\"\n Attributes:\n dat <object>: A LoadDAT object from the gpr module containing a list of GPR data files;\n filename <str>: Name of a CSV file containing, or to contain, segment coordinate data;\n columns <list>: List of filed names for the CSV file containing, or to contain, segment coordinate data.\n \"\"\"\n segs = segments\n self.data_directory = segs.data_directory\n self.filename = filename\n\n self.segment_coordinates_csv = self._outfile()\n\n MetaData.__init__(self, self.segment_coordinates_csv, self._columns(columns))\n\n if self.metadata_is_empty():\n print('WARNING: No segment coordinates exist.')\n\n self.segments = [self._segment(i) for i in segs.segments]\n \n def _outfile(self):\n d = self.data_directory\n f = self.filename\n o = join(d, f)\n return(o)\n\n def _columns(self, columns):\n \"\"\"Return a list of column names.\"\"\"\n column_names = [\n 'id', # unique integer identifier\n 'x0', # x-coordinate at start of segment measurement\n 'y0', # y-coordinate at end of segment measurement\n 'x1', # x-coordinate at end of segment measurement\n 'y1', # y-coordinate at end of segment measurement\n 'coord_note'\n ]\n columns = columns if columns else column_names\n return(columns)\n\n def _segment(self, seg):\n \"\"\"Return a Line object and append data from segment metadata.\"\"\"\n uid = seg.id\n m = self.metadata\n meta = m.loc[m['id']==uid,].iloc[0]\n seg.x0 = meta.x0\n seg.y0 = meta.y0\n seg.x1 = meta.x1\n seg.y1 = meta.y1\n seg.coord_note = meta.coord_note\n return(seg)\n\n def _attr_to_dict(self, seg):\n \"\"\"Return a dictionary of segment attributes\"\"\"\n m = seg\n d = {\n 'id': m.id,\n 'traces': m.traces,\n 'samples': m.samples,\n 'step': m.step,\n 'frequency': m.frequency,\n 'start_position': m.start_position,\n 'x0': m.x0,\n 'y0': m.y0,\n 'x1': m.x1,\n 'y1': m.y1,\n 'coord_note': m.coord_note,\n }\n return(d)\n\nfrom copy import copy\n\nclass ParallelGrid(MetaData):\n \"\"\"Merge a collection of parallel segments into lines for processing as a grid. It is expected that the segments were measured from a single sub-grid.\"\"\"\n\n def __init__(self, data, xd, yd, velocity=None):\n \"\"\"\n Attributes:\n dat <object>: A LoadDAT object from the gpr module containing a list of GPR data files;\n \"\"\"\n #self.data = segments\n self.segments = data.segments\n print(dir(self.segments[0].metadata))\n a = self.segments[0].metadata\n a.transect_coordinate = 6\n print(self.segments[5].metadata.transect_coordinate)\n exit()\n\n # define grid metadata\n self.axis = self._parallel_axis(s)\n self.distance_datum = xd if self.axis=='x' else yd\n self.transect_datum = xd if self.axis=='y' else yd\n self.step = self._grid_step(s)\n self.samples = self._grid_samples(s)\n self.frequency = self._grid_frequency(s)\n self.system_calibration = self._grid_system_calibration(s)\n self.line_spacing = self._line_spacing(s)\n self.time = self._grid_time()\n\n self.line_coords = self._transect_coords(s)\n\n directions = [self._segment_direction(i) for i in s]\n start = [self._start_position(i, d) for i, d in zip(s, directions)]\n xvalues = [self._x_values(i, x0) for i, x0 in zip(s, start)]\n\n print(s[7].metadata.start_position)\n for n, i in enumerate(s):\n i.metadata.start_position = start[n]\n\n print(s[7].metadata.start_position)\n exit()\n \n\n self.traces = self._traces(xvalues)\n\n self.distance_coords = [round(self.distance_datum + (i * self.step), 6) for i in range(self.traces)]\n self.velocity = velocity\n\n # segments to lines\n lines = []\n for c in self.line_coords:\n l = self._line()\n l.transect_coord = c\n lines.append(l)\n ax = 'x0' if self.axis=='y' else 'y0'\n segs = [i for i in s if getattr(i, ax)==c]\n #print(segs)\n\n #for i in segs:\n #print(i.array.shape)\n #x0, a = i\n #for n, j in enumerate(a):\n #if x0+n < self.traces: # when a line was started forward of the grid datum, innacuracy in the filed position may cause the line to have more traces than the calculated empty array. The array must therefore be cut before an overrun occurs.\n # line.array[:,x0+n] = j\n #line.array = np.int16(line.array)\n \n #print(lines)\n #print(lines[0].transect_coord)\n #print(lines[1].transect_coord)\n #l = [self._line() for n, i in enumerate(self.line_coords)]\n #a, b = l[0:2]\n #a.transect_coord = 5\n #b.transect_coord = 6\n #print(a.transect_coord)\n #print([.transect_coord for i in l])\n exit()\n self.lines = [self._line(i) for n, i in enumerate(self.line_coords)]\n #print(dir(s[0]))\n #print(s[0].x0)\n print([i.metadata for i in self.lines])\n print(dir(self.lines[0].metadata))\n exit()\n for i in self.lines:\n t_coord = i.metadata.transect_coord\n print(t_coord)\n wee = 'x0' if self.axis=='y' else 'y0'\n #print(wee)\n segs = [copy(i) for i in s if getattr(i, wee)==t_coord]\n segs = [copy(i) for i in s if getattr(i, wee)==110.0]\n print(segs)\n\n #print([i.x0 for i in s])\n \n #self.set_line_filenames()\n\n #arrays = [self._x_flip(i, d) for i, d in zip(s, directions)]\n #self.array = self._3darray()\n\n def _parallel_axis(self, segment_list):\n \"\"\"Determine the parallel grid axis.\"\"\"\n ax = list(set([self._segment_axis(i) for i in segment_list]))\n if len(ax)>1:\n raise Exception('ERROR: segments must be parallel. Please check segment metadata.')\n print(self.get_metadata())\n return(ax.pop())\n\n def _segment_axis(self, seg):\n \"\"\"Determine the axis each segment is parallel to.\"\"\"\n try:\n float(seg.x1)\n axis = 'y'\n except:\n axis = 'x'\n try:\n float(seg.y1)\n except:\n print('Line is not parallel. Please check segment geometry.')\n return(axis)\n\n def _grid_step(self, segment_list):\n step = list(set([i.metadata.step for i in segment_list]))\n if len(step)>1:\n raise Exception('ERROR: segments steps must be equal. Please check segment metadata.')\n return(step.pop())\n\n def _grid_samples(self, segment_list):\n \"\"\"\"\"\"\n samples = list(set([i.metadata.samples for i in segment_list]))\n if len(samples)>1:\n raise Exception('ERROR: segments samples must be equal. Please check segment metadata.')\n return(samples.pop())\n \n def _grid_frequency(self, segment_list):\n \"\"\"\"\"\"\n frequency = Counter([i.metadata.frequency for i in segment_list]).most_common()[0][0]\n return(frequency)\n\n def _grid_system_calibration(self, segment_list):\n \"\"\"\"\"\"\n calib = Counter([i.metadata.system_calibration for i in segment_list]).most_common()[0][0]\n return(calib)\n\n def _line_spacing(self, segment_list):\n \"\"\"Return the line spacing\"\"\"\n ax = 'x0' if self.axis=='y' else 'y0'\n t = list(set([getattr(i, ax) for i in segment_list]))\n t.sort(reverse=True)\n spacing = min(list(set([t[i]-t[i+1] for i in range(len(t)-1)])))\n return(spacing)\n\n def _transect_coords(self, segments):\n \"\"\"Return the transect coordinates of a group of segments.\"\"\"\n ax = 'x0' if self.axis=='y' else 'y0'\n t = list(set([getattr(i, ax) for i in segments]))\n t0, t1 = min(t), max(t)\n line_count = math.floor((t1-t0)/self.line_spacing)\n coordinates = [t0 + i * self.line_spacing for i in range(line_count)]\n return(coordinates)\n\n def _grid_time(self):\n \"\"\"\"\"\"\n time = [round((i) * 1 / self.frequency * 1000, 6) for i in range(self.samples)]\n return(time)\n\n def _segment_direction(self, seg):\n \"\"\"Return the positive or negative direction of a segment.\"\"\"\n x1, y1, ax = seg.x1, seg.y1, self.axis\n d = x1 if ax=='x' else y1\n return(d)\n\n def _start_position(self, seg, direction):\n \"\"\"Set the start position of a segment.\"\"\"\n start = seg.x0 if self.axis=='x' else seg.y0\n start = start if direction=='+' else start - (seg.metadata.traces * self.step)\n x0 = self.distance_datum\n distance = round(start - x0, 6)\n traces = round(distance / self.step, 6)\n tmin = round(math.floor(traces) * self.step, 6)\n tmax = round(math.ceil(traces) * self.step, 6)\n start = tmin if abs(distance-tmin)<=abs(distance-tmax) else tmax\n start = round(start + x0, 6)\n return(start)\n\n def _x_values(self, seg, x0):\n \"\"\"\"\"\"\n m = seg.metadata\n traces = m.traces\n dx = m.step\n x = [x0 + (i * dx) for i in range(traces)]\n return(x)\n \n def _x_flip(self, seg, direction):\n \"\"\"Flip the segment array along the radargram x-axis if direction is negative.\"\"\"\n a = seg.array if direction=='+' else x_flip(seg.array)\n return(a)\n\n def _traces(self, xvalues):\n \"\"\"\"\"\"\n x0 = min([min(i) for i in xvalues])\n x1 = max([max(i) for i in xvalues])\n t = int((x1 - x0) / self.step)\n return(t)\n\n def _line(self):\n \"\"\"Fill an empty line with associated segments and return.\"\"\"\n m, n = len(self.time), self.traces\n line = Line(m, n)\n line.metadata.start_position = self.distance_datum\n line.metadata.traces = self.traces\n line.metadata.samples = self.samples\n line.metadata.time = self.time\n line.metadata.step = self.step\n line.metadata.frequency = self.frequency\n line.metadata.system_calibration = self.system_calibration\n return(line)\n\n def wee(self, line):\n \"\"\"\"\"\"\n print(line.metadata)\n print(line.metadata.transect_coord)\n print(dir(line.metadata))\n seg = self._line_segments(line.metadata.transect_coord)\n print(seg)\n #for i in self._line_segments(coord):\n #print(i)\n # x0, a = i\n # for n, j in enumerate(a):\n # if x0+n < self.traces: # when a line was started forward of the grid datum, innacuracy in the filed position may cause the line to have more traces than the calculated empty array. The array must therefore be cut before an overrun occurs.\n # line.array[:,x0+n] = j\n #line.array = np.int16(line.array)\n return(line)\n\n def _line_segments(self, coord):\n \"\"\"Return an iterater including the start trace and transposed array of all segments occurring at a given transect coordinate. The segment arrays are returned transposed to allow iteration through columns.\"\"\"\n s = [i for i in self.data.segments if i.x0==coord]\n #if coord==108:\n # a, b = s\n # print(a.metadata.start_position)\n # print(b.metadata.start_position)\n\n a = [i.array.T for i in s]\n t0 = [int(round((i.metadata.start_position - self.distance_datum) / self.step, 6)) for i in s]\n #print(t0)\n return(zip(t0, a))\n \n def _3darray(self):\n \"\"\"Stack and rotate a 3D array so that the lines are oriented to the survey grid. Iteration should occur through the time dimension.\"\"\"\n a = np.stack([i.array for i in self.lines])\n return(a)\n\n def set_line_filenames(self, prefix='LINE', name_list=None, suffix=''):\n \"\"\"Set the output filename for each line.\"\"\"\n if not name_list:\n name_list = [prefix + str(int(i*100)) + suffix for i in self.line_coords]\n for l, n in zip(self.lines, name_list):\n l.filename = n\n\n def radargrams(self, directory, time=True, distance=True, depth=True):\n \"\"\"Output jpg radargrams.\"\"\"\n d = directory\n for i in self.lines:\n i.plot()\n if distance:\n i.x_axis(self.distance_coords)\n if time:\n i.y_axis(self.time)\n if depth:\n i.y2_axis([round(ns2mm(i, 0.1) / 1000, 3) for i in self.time])\n path = join(d, i.filename + '.jpg')\n if not isfile(path):\n i.jpg(path)\n i.close()\n \n def export_line_arrays(self, directory):\n \"\"\"\"\"\"\n d = directory\n for i in self.lines:\n path = join(directory, i.filename + '.rd3')\n rd3 = join(directory, i.filename + '.rd3')\n if not isfile(rd3):\n arr2rd3(i.array, rd3)\n rad = join(directory, i.filename + '.rad')\n if not isfile(rad):\n with open(rad, 'w') as f:\n f.write('SAMPLES:' + str(self.samples) + '\\r\\n')\n f.write('FREQUENCY:' + str(self.frequency) + '\\r\\n')\n f.write('FREQUENCY STEPS: 1' + '\\r\\n')\n f.write('SIGNAL POSITION: 0' + '\\r\\n')\n f.write('RAW SIGNAL POSITION: 0' + '\\r\\n')\n f.write('DISTANCE FLAG: 1' + '\\r\\n')\n f.write('TIME FLAG: 0' + '\\r\\n')\n f.write('PROGRAM FLAG: 0' + '\\r\\n')\n f.write('EXTERNAL FLAG: 0' + '\\r\\n')\n f.write('TIME INTERVAL: 0' + '\\r\\n')\n f.write('DISTANCE INTERVAL:' + ' ' + str(self.step) + '\\r\\n')\n f.write('OPERATOR:' + '\\r\\n')\n f.write('CUSTOMER:' + '\\r\\n')\n f.write('SITE:' + '\\r\\n')\n f.write('ANTENNAS: 500' + '\\r\\n')\n f.write('ANTENNA ORIENTATION:' + '\\r\\n')\n f.write('ANTENNA SEPARATION: 0.1800' + '\\r\\n')\n f.write('COMMENT:Unknown=6' + '\\r\\n')\n f.write('TIMEWINDOW: 29.1982' + '\\r\\n')\n f.write('STACKS: 1' + '\\r\\n')\n f.write('STACK EXPONENT: 1' + '\\r\\n')\n f.write('STACKING TIME: 0' + '\\r\\n')\n f.write('LAST TRACE:' + str(self.traces) + '\\r\\n')\n f.write('STOP POSITION:' + ' ' + str.format('{0:.6f}', max(self.distance_coords)) + '\\r\\n')\n f.write('SYSTEM CALIBRATION:' + str.format('{0:.10f}', self.system_calibration) + '\\r\\n')\n f.write('START POSITION:' + str.format('{0:.6f}', min(self.distance_coords)) + '\\r\\n')\n \n\nclass Segment:\n \"\"\"A line object. This class should be in the 'gpr' module but I can't seem to work out how to import it. It may be a circular import problem because gpr also imports from 'mala'\"\"\"\n\n def get_empty_array(self, m, n):\n \"\"\"Return an empty array\"\"\"\n arr = np.zeros([m, n])\n return(arr)\n\n\n","sub_path":"geo/geophys/gpr/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":16056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"163394396","text":"#http://nbviewer.jupyter.org/github/jmportilla/Python-for-Algorithms--Data-Structures--and-Interviews/blob/master/Array%20Sequences/Array%20Sequences%20Interview%20Questions/Array%20Sequence%20Interview%20Questions/Anagram%20Check%20.ipynb\ndef isAnagram(s1, s2):\n s1 = s1.replace(' ', '').lower()\n s2 = s2.replace(' ', '').lower()\n if len(s1) != len(s2):\n return False\n \n # note: only one dictionary needed to get the job done!!!\n count = {}\n\n for letter in s1:\n if letter in count:\n count[letter] += 1\n else:\n count[letter] = 1\n\n for letter in s2:\n if letter in count and count[letter] > 0:\n count[letter] -= 1\n else:\n return False\n\n return True\n\ndef test_isAnagram():\n assert isAnagram('abc', 'bca') == True\n assert isAnagram('clint eastwood', 'olsd west action') == False\n assert isAnagram('clint eastwood', 'old west action') == True","sub_path":"Python-Algorithms/ArraySequences/01_AnagramCheck.py","file_name":"01_AnagramCheck.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"7058000","text":"\"\"\"\nCopyright (c) 2018 Cisco Systems, Inc.\n\nAuthor:\n Christian Oeien <coien@cisco.com>\n\"\"\"\nfrom tng.api import runner\nfrom tng_sl.contrib.pitstop_helper import PitstopTestCase\nfrom pitstop.exp import (\n Receive, Poll, Wait, Command, Send, LocalOffer, RemoteAnswer, Flag)\n\n\nclass Test(PitstopTestCase):\n\n def test_medialine_selected_in_offer_and_reoffer(self):\n '''\n Give DUT an offer with the 2nd medialine being unusable, and a 1st\n one deemed to be desireable. Verify that DUT zero-ports the 2nd line\n in its answer. Validate the same behaviour on re-offer still a bad 2st\n Numbers: 19; it's an unassigned static audio payload type ref RFC 3551\n Accommodates for MPP: will fail when swap 1st and 2nd in above descr.\n '''\n\n bad_extra = \"m=audio\\nm=audio _ _ 19\"\n with_extra_portrejected = \"m=audio [^0].+m=audio 0\"\n\n self.spec.update({\"test\": [\n Wait(\"idle\").then([\n LocalOffer(\"a\", bad_extra),\n Send(\"INVITE\", {\"\\n\": \"$a\"}, transaction_label=\"i\")]),\n Receive(\"18.\", {}, on_transaction=\"i\").then([]),\n Poll(self.dut.is_ringing).then([\n Command(self.dut.accept_call)]),\n Receive(\n \"200\", {}, on_transaction=\"i\", dialog_label=\"d\",\n captures={\"A\": \"\\n(.+)\"},\n verify=[(\"\\n\", with_extra_portrejected)]).then([\n RemoteAnswer(\"$A\"),\n Send(\"ACK\", {}, in_dialog=\"d\"),\n LocalOffer(\"b\", bad_extra),\n Send(\n \"INVITE\", {\"\\n\": \"$b\"},\n transaction_label=\"r\", in_dialog=\"d\")]),\n Receive(\n \"200\", {}, on_transaction=\"r\",\n captures={\"B\": \"\\n(.+)\"},\n verify=[(\"\\n\", with_extra_portrejected)]).then([\n RemoteAnswer(\"$B\"),\n Send(\"ACK\", {}, in_dialog=\"d\"),\n Command(self.dut.end_call)]),\n Receive(\"BYE\", {}, in_dialog=\"d\", transaction_label=\"b\").then([\n Send(\"200\", {}, on_transaction=\"b\")]),\n Poll(self.dut.is_line_idle).then([Flag(\"idle\")])]})\n\n self.pitstop()\n\n\ndef main():\n runner()\n","sub_path":"pitstop_tests/basic/medialine_selected_in_offer_and_reoffer.py","file_name":"medialine_selected_in_offer_and_reoffer.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"407081782","text":"import unittest\nimport re\nimport time\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.keys import Keys\n\n\nclass FirstWebDriverTest(unittest.TestCase):\n # set_up\n driver = webdriver.Chrome()\n URL = 'http://www.bestbuy.com'\n ITEM = \"moto x pure\"\n CHARACTERISTICS = '32'\n PRICE = '199.99'\n STATE = 'Refurbished'\n Quantity = '2'\n SHOP = 'MCALLEN TX'\n\n def test_buy_motox(self):\n self.driver.get(self.URL)\n self.driver.implicitly_wait(10)\n c_url = self.driver.current_url\n self.driver.find_element_by_class_name('intl_drop').send_keys('u')\n self.driver.find_element_by_class_name('go_button').click()\n if c_url != self.URL:\n try:\n self.driver.find_element_by_class_name('close').click()\n except NoSuchElementException:\n pass\n self.driver.find_element_by_id('gh-search-input').send_keys(self.ITEM)\n self.driver.find_element_by_class_name('hf-icon-search').click()\n x = self.driver.find_elements_by_class_name('facet-value ')\n for element in x:\n if re.search(self.CHARACTERISTICS, element.text):\n element.click()\n time.sleep(2)\n break\n prices = self.driver.find_elements_by_class_name('list-item-price-content')\n for element in prices:\n if re.search(self.PRICE, element.text):\n time.sleep(2)\n element.find_element_by_link_text('Add to Cart').click()\n time.sleep(5)\n self.driver.find_element_by_class_name('go-to-cart').click()\n desc = self.driver.find_element_by_class_name('emphasized-copy').text\n assert re.search(self.STATE, desc)\n time.sleep(2)\n box = self.driver.find_element_by_xpath('/html/body/div[3]/div[2]/div/div/div[4]/div/div[1]/div[2]/div[2]/ul/l'\n 'i/div[2]/div/div/div[3]/div[2]/div/div/div[1]/input')\n box.clear()\n box.send_keys(2)\n box.send_keys(Keys.RETURN)\n time.sleep(5)\n self.driver.find_element_by_link_text('Select a store').click()\n time.sleep(2)\n stores = self.driver.find_elements_by_class_name('store-name')\n for element in stores:\n if element.text == self.SHOP:\n element.click()\n self.driver.find_element_by_class_name('modal-select-store--primary').click()\n time.sleep(5)\n p_total = self.driver.find_elements_by_xpath('//*[@id=\"order-summary\"]/div/div[1]/div/div[3]/div[2]')\n assert re.search((str(float(self.PRICE) * 2)), p_total[0].text)\n self.driver.find_element_by_link_text('Checkout').click()\n time.sleep(5)\n self.driver.find_element_by_link_text('Continue as Guest').click()\n\n def tear_down(self):\n self.driver.close()\n","sub_path":"Moto X Pure.py","file_name":"Moto X Pure.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"267123347","text":"# -*-coding: utf-8 -*-\n# !/usr/bin/python3\n\"\"\"\n collect 10000 images from camera and labeled.\n\"\"\"\nimport os\nimport random\n\nimport cv2\nimport dlib\n\nroot_path = os.getcwd()\noutput_dir = root_path + '/my_faces'\nfile_prefix = 'murphy_' # this is a label we used for detection later, please use correct name label instead.\nsize = 64\n\nif not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n\n# adjust brightness and contrast\ndef relight(img, light=1, bias=0):\n w = img.shape[1]\n h = img.shape[0]\n for i in range(0, w):\n for j in range(0, h):\n for c in range(3):\n tmp = int(img[j, i, c] * light + bias)\n if tmp > 255:\n tmp = 255\n elif tmp < 0:\n tmp = 0\n img[j, i, c] = tmp\n return img\n\n\n# Extract features by dlib frontal_face_detector\ndetector = dlib.get_frontal_face_detector()\n# Open camera, para=video stream, you can use local video file instead '0', e.g. 'video.mp4'.\ncamera = cv2.VideoCapture(0)\n\nindex = 1\nwhile True:\n if index <= 10000:\n print('Being processed picture %s' % index)\n # get image from camera\n success, img = camera.read()\n # RBG --> GRAY\n gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # The 1 in the second argument indicates that we should upsample the image\n # 1 time. This will make everything bigger and allow us to detect more\n # faces.\n dets = detector(gray_img, 1)\n\n for i, d in enumerate(dets):\n x1 = d.top() if d.top() > 0 else 0\n y1 = d.bottom() if d.bottom() > 0 else 0\n x2 = d.left() if d.left() > 0 else 0\n y2 = d.right() if d.right() > 0 else 0\n\n face = img[x1:y1, x2:y2]\n # Increasing diversity in the samples\n face = relight(face, random.uniform(0.5, 1.5), random.randint(-50, 50))\n face = cv2.resize(face, (size, size))\n cv2.imshow('image', face)\n cv2.imwrite(output_dir + '/' + file_prefix + str(index) + '.jpg', face)\n\n index += 1\n key = cv2.waitKey(30) & 0xff\n # Exit when get 'ESC'\n if key == 27:\n break\n else:\n print('Finished!')\n break\n","sub_path":"get_my_faces.py","file_name":"get_my_faces.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"523952877","text":"from tkinter import *\nimport sqlite3\nconn = sqlite3.connect('database1.sql')\n\ndef invoer_incheckzuil():\n global e1\n master = Tk()\n Label(master, text=\"Voer ov-chipkaartnummer in\").grid(row=0)\n e1 = Entry(master)\n e1.grid(row=0, column=1)\n Button(master, text='Invoeren', command=master.quit).grid(row=0, column=4 , sticky=W, pady=20)\n mainloop()\n f = e1.get()\n return f\n\ndef vergelijk_database():\n global f\n global conn\n # for row in conn:\n # if f == row:\n # print( row[0])\n # else:\n # print(\"werkt niet\")\n #\n with conn:\n\n cur = conn.cursor()\n cur.execute(\"SELECT * FROM NSReizigers\")\n\n while True:\n\n row = cur.fetchone()\n\n if row == None:\n break\n\n print(row[0], row[1], row[2])\n\ninvoer_incheckzuil()\nvergelijk_database()\n","sub_path":"incheckzuil.py","file_name":"incheckzuil.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"223222584","text":"import os.path\nfrom utils.dataload import (load_start, load_done, tab2dict)\nfrom config import DATA_ARCHIVE_ROOT\nDATA_FOLDER = os.path.join(DATA_ARCHIVE_ROOT, 'by_resources/reporters')\nplatform_li = ['snowball']\n\n\ndef loaddata():\n #Snowball array\n DATAFILE = os.path.join(DATA_FOLDER, 'pigatlas', 'snowball_array_annotation.txt')\n load_start(DATAFILE)\n gene2snowball = tab2dict(DATAFILE, (0, 1), 1, header=0)\n load_done('[%d]' % len(gene2snowball))\n return {'snowball': gene2snowball}\n","sub_path":"src/dataload/sources/reporter/pigatlas_reporter.py","file_name":"pigatlas_reporter.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"184946017","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: marta\n\"\"\"\n\nimport warnings\nfrom astropy import log\nfrom astropy.logger import AstropyUserWarning\nimport numpy as np\nfrom stingray.varenergyspectrum import (\n RmsEnergySpectrum,\n _decode_energy_specification,\n)\nfrom stingray.varenergyspectrum import LagEnergySpectrum\n\n# from stingray.covariancespectrum import AveragedCovariancespectrum\n\nfrom .base import hen_root, interpret_bintime\nfrom .io import load_events\nfrom .io import save_as_qdp\n\n\ndef main(args=None):\n import argparse\n from .base import _add_default_args, check_negative_numbers_in_args\n\n description = \"Calculates variability-energy spectra\"\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument(\"files\", help=\"List of files\", nargs=\"+\")\n parser.add_argument(\n \"-f\",\n \"--freq-interval\",\n nargs=2,\n type=float,\n default=[0.0, 100],\n help=\"Frequence interval\",\n )\n parser.add_argument(\n \"--energy-values\",\n nargs=4,\n type=str,\n default=\"0.3 12 5 lin\".split(\" \"),\n help=\"Choose Emin, Emax, number of intervals,\"\n \"interval spacing, lin or log\",\n )\n parser.add_argument(\n \"--segment-size\",\n type=float,\n default=512,\n help=\"Length of the light curve intervals to be \" \"averaged\",\n )\n parser.add_argument(\n \"--ref-band\",\n nargs=2,\n type=float,\n default=None,\n help=\"Reference band when relevant\",\n )\n parser.add_argument(\n \"--rms\", default=False, action=\"store_true\", help=\"Calculate rms\"\n )\n parser.add_argument(\n \"--covariance\",\n default=False,\n action=\"store_true\",\n help=\"Calculate covariance spectrum\",\n )\n parser.add_argument(\n \"--use-pi\",\n default=False,\n action=\"store_true\",\n help=\"Energy intervals are specified as PI channels\",\n )\n parser.add_argument(\n \"--cross-instr\",\n default=False,\n action=\"store_true\",\n help=\"Use data files in pairs, for example with the\"\n \"reference band from one and the subbands from \"\n \"the other (useful in NuSTAR and \"\n \"multiple-detector missions)\",\n )\n parser.add_argument(\n \"--lag\",\n default=False,\n action=\"store_true\",\n help=\"Calculate lag-energy\",\n )\n\n _add_default_args(parser, [\"bintime\", \"loglevel\", \"debug\"])\n\n args = check_negative_numbers_in_args(args)\n args = parser.parse_args(args)\n args.bintime = np.longdouble(interpret_bintime(args.bintime))\n\n if args.debug:\n args.loglevel = \"DEBUG\"\n\n log.setLevel(args.loglevel)\n with log.log_to_file(\"HENvarenergy.log\"):\n filelist = []\n energy_spec = (\n float(args.energy_values[0]),\n float(args.energy_values[1]),\n int(args.energy_values[2]),\n args.energy_values[3],\n )\n\n from .io import sort_files\n\n if args.cross_instr:\n log.info(\"Sorting file list\")\n sorted_files = sort_files(args.files)\n\n warnings.warn(\n \"Beware! For cpds and derivatives, I assume that the \"\n \"files are from only two instruments and in pairs \"\n \"(even in random order)\"\n )\n\n instrs = list(sorted_files.keys())\n\n files1 = sorted_files[instrs[0]]\n files2 = sorted_files[instrs[1]]\n else:\n files1 = args.files\n files2 = args.files\n\n for fnames in zip(files1, files2):\n fname = fnames[0]\n fname2 = fnames[1]\n\n events = load_events(fname)\n events2 = load_events(fname2)\n if not args.use_pi and (\n events.energy is None or events2.energy is None\n ):\n raise ValueError(\n \"If --use-pi is not specified, event lists must \"\n \"be calibrated! Please use HENcalibrate.\"\n )\n\n if args.rms:\n rms = RmsEnergySpectrum(\n events,\n args.freq_interval,\n energy_spec,\n segment_size=args.segment_size,\n bin_time=args.bintime,\n events2=events2,\n use_pi=args.use_pi,\n )\n out1 = hen_root(fname) + \"_rms\" + \".qdp\"\n start_energy = np.asarray(rms.energy_intervals)[:, 0]\n stop_energy = np.asarray(rms.energy_intervals)[:, 1]\n save_as_qdp(\n [start_energy, stop_energy, rms.spectrum],\n [None, None, rms.spectrum_error],\n filename=out1,\n )\n filelist.append(out1)\n\n if args.lag:\n lag = LagEnergySpectrum(\n events,\n args.freq_interval,\n energy_spec,\n args.ref_band,\n segment_size=args.segment_size,\n bin_time=args.bintime,\n events2=events2,\n use_pi=args.use_pi,\n )\n start_energy = np.asarray(lag.energy_intervals)[:, 0]\n stop_energy = np.asarray(lag.energy_intervals)[:, 1]\n out2 = hen_root(fname) + \"_lag\" + \".qdp\"\n save_as_qdp(\n [start_energy, stop_energy, lag.spectrum],\n [None, None, lag.spectrum_error],\n filename=out2,\n )\n filelist.append(out2)\n\n if args.covariance:\n from stingray.covariancespectrum import (\n AveragedCovariancespectrum,\n )\n\n energies = _decode_energy_specification(energy_spec)\n energies = list(zip(energies[:-1], energies[1:]))\n cov = AveragedCovariancespectrum(\n events,\n dt=args.bintime,\n band_interest=energies,\n ref_band_interest=args.ref_band,\n segment_size=args.segment_size,\n )\n\n start_energy = np.asarray(energies)[:, 0]\n stop_energy = np.asarray(energies)[:, 1]\n out2 = hen_root(fname) + \"_cov\" + \".qdp\"\n save_as_qdp(\n [start_energy, stop_energy, cov.covar],\n [None, None, cov.covar_error],\n filename=out2,\n )\n filelist.append(out2)\n\n return filelist\n","sub_path":"hendrics/varenergy.py","file_name":"varenergy.py","file_ext":"py","file_size_in_byte":6645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"640196320","text":"import sys\r\nsys.path.append('./modules/')\r\n\r\nimport numpy as np\r\nfrom docopt import docopt\r\nfrom composes.utils import io_utils\r\nfrom composes.semantic_space.space import Space\r\nfrom composes.matrix.dense_matrix import DenseMatrix\r\nfrom sklearn.utils.extmath import randomized_svd\r\nfrom dsm import save_pkl_files, load_pkl_files\r\nimport logging\r\nimport time\r\n\r\n\r\ndef main():\r\n \"\"\"\r\n Perform dimensionality reduction on a (normally PPMI) matrix by applying truncated SVD as described in\r\n\r\n Omer Levy, Yoav Goldberg, and Ido Dagan. 2015. Improving distributional similarity with lessons learned from word embeddings. Trans. ACL, 3.\r\n\r\n \"\"\"\r\n\r\n # Get the arguments\r\n args = docopt('''Perform dimensionality reduction on a (normally PPMI) matrix by applying truncated SVD and save it in pickle format.\r\n\r\n Usage:\r\n svd.py [-l] <dsm_prefix> <dim> <gamma> <outPath>\r\n\r\n <dsm_prefix> = the prefix for the input files (.sm for the matrix, .rows and .cols) and output files (.svd)\r\n <dim> = dimensionality of low-dimensional output vectors\r\n <gamma> = eigenvalue weighting parameter\r\n <outPath> = output path for space\r\n\r\n Options:\r\n -l, --len normalize final vectors to unit length\r\n\r\n ''')\r\n\r\n is_len = args['--len']\r\n dsm_prefix = args['<dsm_prefix>']\r\n dim = int(args['<dim>'])\r\n gamma = float(args['<gamma>'])\r\n outPath = args['<outPath>']\r\n\r\n logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\r\n logging.info(__file__.upper())\r\n start_time = time.time() \r\n\r\n # Get space with sparse matrix\r\n dsm = load_pkl_files(dsm_prefix)\r\n \r\n id2row = dsm.get_id2row()\r\n\r\n # Get matrix from space\r\n matrix_ = dsm.get_cooccurrence_matrix()\r\n\r\n # Apply SVD\r\n u, s, v = randomized_svd(matrix_.get_mat(), n_components=dim, n_iter=5, transpose=False)\r\n\r\n # Weight matrix\r\n if gamma == 0.0:\r\n matrix_ = u\r\n elif gamma == 1.0:\r\n #matrix_ = np.dot(u, np.diag(s)) # This is equivalent to the below formula (because s is a flattened diagonal matrix)\r\n matrix_ = s * u \r\n else:\r\n #matrix_ = np.dot(u, np.power(np.diag(s), gamma)) # This is equivalent to the below formula\r\n matrix_ = np.power(s, gamma) * u\r\n\r\n if is_len:\r\n # L2-normalize vectors\r\n l2norm1 = np.linalg.norm(matrix_, axis=1, ord=2)\r\n l2norm1[l2norm1==0.0] = 1.0 # Convert 0 values to 1\r\n matrix_ /= l2norm1.reshape(len(l2norm1),1)\r\n \r\n dsm = Space(DenseMatrix(matrix_), id2row, [])\r\n \r\n # Save the Space object in pickle format\r\n save_pkl_files(dsm, outPath + \".svd.dm\", save_in_one_file=True, save_as_w2v=True)\r\n logging.info(\"--- %s seconds ---\" % (time.time() - start_time)) \r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"representations/svd.py","file_name":"svd.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"498036067","text":"import random\n\nfrom selenium.webdriver.common.by import By\n\nfrom conf.base_page import BasePage\nfrom conf.decorator import teststep\n\n\nclass UnitPage(BasePage):\n\n @teststep\n def wait_check_select_unit_page(self):\n \"\"\"选择单元页面检查点\"\"\"\n locator = (By.CSS_SELECTOR, '.subtitle')\n return self.get_wait_check_page_ele(locator)\n\n @teststep\n def wait_check_empty_page(self):\n \"\"\"暂无复习数据页面检查点\"\"\"\n locator = (By.CSS_SELECTOR, '.empty')\n return self.get_wait_check_page_ele(locator)\n\n @teststep\n def current_book(self):\n \"\"\"当前课程名称\"\"\"\n locator = (By.CSS_SELECTOR, '.highlighted')\n return self.get_wait_check_page_ele(locator)\n\n @teststep\n def unit_list(self):\n \"\"\"单元列表\"\"\"\n locator = (By.CSS_SELECTOR, '.unit-list .item')\n return self.get_wait_check_page_ele(locator, single=False)\n\n @teststep\n def unit_back_btn(self):\n \"\"\"选择单元回退页面\"\"\"\n locator = (By.CSS_SELECTOR, '.NavigationBar-index--back')\n return self.get_wait_check_page_ele(locator)\n\n @teststep\n def select_unit_operate(self, book_name, book_studied_count):\n \"\"\"选择单元操作\"\"\"\n if not self.wait_check_select_unit_page():\n self.base_assert.except_error('未进入选择单元页面')\n else:\n if self.current_book().text != book_name:\n self.base_assert.except_error(\"页面的课程名称与已选择的书籍名称不一致\")\n if book_studied_count:\n if self.wait_check_empty_page():\n self.base_assert.except_error('书籍存在已学习单词, 但是选择单元页面无单元可选')\n\n if not book_studied_count:\n if not self.wait_check_empty_page():\n self.base_assert.except_error('书籍不存在已学单词, 但是选择单元页面存在可选择单元')\n\n unit_list = self.unit_list()\n if unit_list:\n range_num = len(unit_list) if len(unit_list) < 8 else 8\n random_index = random.choice(range(range_num))\n unit_list[random_index].click()\n return random_index\n return False\n","sub_path":"app/passion_applets/object_page/applets/books/unit_page.py","file_name":"unit_page.py","file_ext":"py","file_size_in_byte":2290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"280267439","text":"#!/usr/bin/env python\n# (C) 2017 OpenEye Scientific Software Inc. All rights reserved.\n#\n# TERMS FOR USE OF SAMPLE CODE The software below (\"Sample Code\") is\n# provided to current licensees or subscribers of OpenEye products or\n# SaaS offerings (each a \"Customer\").\n# Customer is hereby permitted to use, copy, and modify the Sample Code,\n# subject to these terms. OpenEye claims no rights to Customer's\n# modifications. Modification of Sample Code is at Customer's sole and\n# exclusive risk. Sample Code may require Customer to have a then\n# current license or subscription to the applicable OpenEye offering.\n# THE SAMPLE CODE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT\n# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall OpenEye be\n# liable for any damages or liability in connection with the Sample Code\n# or its use.\n\nfrom openeye import oechem\nfrom openeye import oedepict\n\n###############################################################\n# USED TO GENERATE CODE SNIPPETS FOR THE OEDEPICT DOCUMENTATION\n###############################################################\n\nmol = oechem.OEGraphMol()\noechem.OESmilesToMol(mol, \"c1ccccc1\")\noedepict.OEPrepareDepiction(mol)\n\n# @ <SNIPPET-MOL-DISPLAY-DIMENSIONS>\nwidth, height, scale = 0.0, 0.0, 50.0\nopts = oedepict.OE2DMolDisplayOptions(width, height, scale)\ndisp = oedepict.OE2DMolDisplay(mol, opts)\nprint(\"width %.1f\" % disp.GetWidth())\nprint(\"height %.1f\" % disp.GetHeight())\nprint(\"scale %.1f\" % disp.GetScale())\n# @ </SNIPPET-MOL-DISPLAY-DIMENSIONS>\n","sub_path":"venv/Lib/site-packages/openeye/docexamples/depict/DepictMolRealSize.py","file_name":"DepictMolRealSize.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"346703195","text":"#Fichier daq.py\n#Routines de mesure de la distance et des signaux pour le temps de vol.\n#Auteur: Jonathan Lafrenière-Greig\n#2021-05-06\n\nimport nidaqmx\nfrom nidaqmx import Task\nimport numpy as np\n\n#fonction qui prend un grand nombre de mesures de la longueur de la tige\ndef distance(rate=1000, nsamples=1000):\n with Task() as ai_task,Task() as ao_task,Task() as do0_task:\n ai_task.ai_channels.add_ai_voltage_chan(\"myDAQ1/ai1\")\n ao_task.ao_channels.add_ao_voltage_chan(\"myDAQ1/ao1\")\n do0_task.do_channels.add_do_chan('myDAQ1/port0/line0:1')\n \n ao_task.timing.cfg_samp_clk_timing(\n rate,sample_mode=nidaqmx.constants.AcquisitionType.FINITE,\n samps_per_chan=nsamples)\n do0_task.write(True,auto_start = True)\n ao_task.write(5*np.ones(nsamples),auto_start = False)\n ai_task.timing.cfg_samp_clk_timing(rate,samps_per_chan=nsamples)\n ai_task.start()\n ao_task.start()\n ai_task.wait_until_done()\n ao_task.wait_until_done()\n do0_task.write(False)\n return ai_task.read(nsamples,timeout=nidaqmx.constants.WAIT_INFINITELY)\n \n#fonction qui envoi une impulsion et qui capte le signal du piezo d'entrée et\n#de sortie\ndef impulsion(impulse,rate=10000,nsamples=10000):\n with nidaqmx.Task() as ai_task,nidaqmx.Task() as ao_task:\n ai_task.ai_channels.add_ai_voltage_chan(\"myDAQ1/ai0\")\n ai_task.ai_channels.add_ai_voltage_chan(\"myDAQ1/ai1\")\n ao_task.ao_channels.add_ao_voltage_chan(\"myDAQ1/ao0\")\n ao_task.timing.cfg_samp_clk_timing(\n rate,sample_mode=nidaqmx.constants.AcquisitionType.FINITE,\n samps_per_chan=nsamples)\n \n ao_task.write(impulse, auto_start = False)\n ai_task.timing.cfg_samp_clk_timing(\n rate,sample_mode=nidaqmx.constants.AcquisitionType.FINITE,\n samps_per_chan=nsamples)\n ai_task.start()\n ao_task.start()\n ai_task.wait_until_done()\n ao_task.wait_until_done()\n return ai_task.read(nsamples,timeout=nidaqmx.constants.WAIT_INFINITELY)\n \n","sub_path":"Projet_Metrologie/daq.py","file_name":"daq.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"381900072","text":"\"\"\"\nScript to mergetime on all feedback monthly data\n\"\"\"\n\n# Import modules\n\nfrom cdo import *\ncdo = Cdo()\nimport my_shell_tools\nimport os\nimport os.path\nimport CMIP5_functions as cmip5\n\n# import functions from file\nfrom GLENS_functions import *\n\n\"\"\"\nDefine variables\n\"\"\"\n\nrun = '001'\n\nfeedback_name = \"feedback.{run}.cam.h0.{var}.202001-209912{append}.nc\"\ncontrol_name = \"control.{run}.cam.h0.{var}.201001-209912{append}.nc\"\n\nin_dir = \"/n/home03/pjirvine/keithfs1_pji/GLENS/combined_monthly_data/\"\nout_dir = \"/n/home03/pjirvine/keithfs1_pji/GLENS/GEOL0013_seasons/\"\n\nmean_vars = ['TREFHT','PRECT','P-E']\nmax_vars = ['TREFHTMX','PRECTMX']\n\n\"\"\"\nCreate a function to CDO process the seasonal and annual timeseries\n\"\"\"\n\ndef cdo_all_seas(filename, var, run, mean=True):\n \n infile = in_dir + filename.format(var=var, run=run, append='')\n \n if mean:\n cdo.yearmean(input = infile, output = out_dir + filename.format(var=var, run=run, append='.ann'))\n seas_temp = cdo.seasmean(input = infile)\n else:\n cdo.yearmax(input = infile, output = out_dir + filename.format(var=var, run=run, append='.ann'))\n seas_temp = cdo.seasmax(input = infile)\n \n cdo.selseas('DJF', input = seas_temp, output = out_dir + filename.format(var=var, run=run, append='.djf'))\n cdo.selseas('MAM', input = seas_temp, output = out_dir + filename.format(var=var, run=run, append='.mam'))\n cdo.selseas('JJA', input = seas_temp, output = out_dir + filename.format(var=var, run=run, append='.jja'))\n cdo.selseas('SON', input = seas_temp, output = out_dir + filename.format(var=var, run=run, append='.son'))\n\n# Loop over all mean_vars\nfor var in mean_vars:\n cdo_all_seas(control_name, var, run, mean=True)\n cdo_all_seas(feedback_name, var, run, mean=True)\n \nfor var in max_vars:\n cdo_all_seas(control_name, var, run, mean=False)\n cdo_all_seas(feedback_name, var, run, mean=True)\n\n#end","sub_path":"processing_scripts/GEOL0013_data.py","file_name":"GEOL0013_data.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"342548588","text":"# Given an array of equal-length strings, check if it is possible to rearrange the strings\n# in such a way that after the rearrangement the strings at consecutive positions would\n# differ by exactly one character.\n#\n# Example\n#\n# For inputArray = [\"aba\", \"bbb\", \"bab\"], the output should be\n# stringsRearrangement(inputArray) = false.\n#\n# All rearrangements don't satisfy the description condition.\n#\n# For inputArray = [\"ab\", \"bb\", \"aa\"], the output should be\n# stringsRearrangement(inputArray) = true.\n#\n# Strings can be rearranged in the following way: \"aa\", \"ab\", \"bb\".\n\n\nfrom itertools import permutations\n\n\ndef diffLetters(first_string, second_string):\n # create a letter pair\n letter_pairs = zip(first_string, second_string)\n # compare letter pair\n misses = (a != b for (a, b) in letter_pairs)\n # return True if sum(misses) == 1 else False\n if sum(misses) == 1:\n return True\n else:\n return False\n\n\ndef stringsRearrangement(inputArray):\n # create all possible orderings\n arrangements = permutations(inputArray)\n\n for current_arrangement in arrangements:\n # create string pairs where second input doesn't start with first letter\n string_comparisons = zip(current_arrangement, current_arrangement[1:])\n # compare letters and return a true/false pair\n comparison_results = (diffLetters(a, b) for (a, b) in string_comparisons)\n if all(comparison_results):\n return True\n return False\n\n\nprint(stringsRearrangement([\"aba\", \"bbb\", \"bab\"]))\nprint(stringsRearrangement([\"ab\", \"bb\", \"aa\"]))\n\n\n","sub_path":"arcade/stringsRearrangement.py","file_name":"stringsRearrangement.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"469676001","text":"import pyvista\nfrom pyvista import examples\nfilename = examples.download_rectilinear_grid(load=False)\nfilename.split(\"/\")[-1] # omit the path\n# Expected:\n## 'RectilinearGrid.vtr'\nreader = pyvista.get_reader(filename)\nmesh = reader.read()\nsliced_mesh = mesh.slice('y')\nsliced_mesh.plot(scalars='Void Volume Fraction', cpos='xz',\n show_scalar_bar=False)\n","sub_path":"version/0.37/api/readers/_autosummary/pyvista-XMLRectilinearGridReader-1.py","file_name":"pyvista-XMLRectilinearGridReader-1.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"58406989","text":"import os\nimport threading\nimport time\n\nfrom PIL import Image\nfrom PyQt5 import QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QMainWindow, qApp, QMessageBox, QApplication, QListView, QListWidgetItem, QWidget\nfrom PyQt5.QtGui import QStandardItemModel, QStandardItem, QBrush, QColor\nfrom PyQt5.QtCore import pyqtSlot, QEvent, Qt\nimport sys\nimport json\nimport logging\n\nfrom client.profile import UserProfile\nfrom plyer import notification\n\nsys.path.append('../')\nfrom client.main_window_conv import Ui_MainClientWindow\nfrom client.add_contact import AddContactDialog\nfrom client.del_contact import DelContactDialog\nfrom client.clients_database import ClientDatabase\nfrom client.transport import ClientTransport\nfrom client.start_dialog import UserNameDialog\n\nlogger = logging.getLogger('client')\n\n\n# Класс основного окна\nclass ClientMainWindow(QMainWindow):\n def __init__(self, database, server_database, transport, username):\n super().__init__()\n # основные переменные\n self.database = database\n self.server_database = server_database\n self.transport = transport\n self.username = username\n\n self.avatar = self.server_database.get_user(self.username).avatar\n self.description = self.server_database.get_user(self.username).description\n self.background = self.server_database.get_user_style(self.username).background\n print(self.background)\n # Загружаем конфигурацию окна из дизайнера\n self.ui = Ui_MainClientWindow(self.username, self.avatar, self.description, self.background)\n self.ui.setupUi(self)\n\n self.ui.rgb_background_color_1.valueChanged.connect(self.set_background)\n self.ui.rgb_background_color_2.valueChanged.connect(self.set_background)\n self.ui.rgb_background_color_3.valueChanged.connect(self.set_background)\n\n # Кнопка \"Выход\"\n self.ui.menu_exit.triggered.connect(qApp.exit)\n\n self.ui.btn_crop_image.clicked.connect(self.scale_profile_photo)\n\n # text formating\n # set bold text\n self.ui.btn_bold.clicked.connect(self.set_bold_text)\n # set italic text\n self.ui.btn_italic.clicked.connect(self.set_italic_text)\n # set underlined text\n self.ui.btn_underlined.clicked.connect(self.set_underlined_text)\n\n # show smileys\n self.ui.btn_smiles.clicked.connect(self.show_smileys)\n\n # smileys\n # funny emoji\n self.ui.btn_funny_smiley.clicked.connect(lambda: self.insert_smiley('ab.gif'))\n # sad emoji\n self.ui.btn_sad_smiley.clicked.connect(lambda: self.insert_smiley('ac.gif'))\n # crazy emoji\n self.ui.btn_crazy_smiley.clicked.connect(lambda: self.insert_smiley('ai.gif'))\n\n # show formatting buttons\n self.ui.btn_formating.clicked.connect(self.show_format_buttons)\n\n # Кнопка отправить сообщение\n self.ui.btn_send.clicked.connect(self.send_message)\n\n # save background\n self.ui.save_background.clicked.connect(self.save_background)\n\n # \"добавить контакт\"\n self.ui.btn_add_contact.clicked.connect(self.add_contact_window)\n self.ui.btn_search_contact.clicked.connect(self.show_contacts_search)\n self.ui.menu_add_contact.triggered.connect(self.add_contact_window)\n\n # save profile description\n self.ui.save_descr.clicked.connect(self.save_profile_description)\n\n # Удалить контакт\n self.ui.btn_remove_contact.clicked.connect(self.delete_contact_window)\n self.ui.menu_del_contact.triggered.connect(self.delete_contact_window)\n self.ui.profile.triggered.connect(self.view_profile)\n\n self.ui.upload_photo.clicked.connect(self.upload_photo)\n\n self.ui.search_contact_btn.clicked.connect(self.find_contact)\n\n # Дополнительные требующиеся атрибуты\n self.contacts_model = None\n self.history_model = None\n self.smileys_buttons_show = False\n self.format_buttons_show = False\n self.contacts_search_show = False\n self.is_styled_text = False # if styled, set name of style\n self.messages = QMessageBox()\n self.current_chat = None\n self.is_profile_visible = True\n self.ui.list_messages.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n self.ui.list_messages.setWordWrap(True)\n\n # Даблклик по листу контактов отправляется в обработчик\n self.ui.list_contacts.doubleClicked.connect(self.select_active_user)\n\n # self.global_chat = threading.Thread(target=self.update_global_chat)\n # self.global_chat.daemon = True\n # self.global_chat.start()\n\n self.clients_list_update()\n self.set_disabled_input()\n self.show()\n\n def update_global_chat(self):\n while 1:\n if self.current_chat == 'Global Chat':\n self.history_list_update()\n time.sleep(3)\n\n def save_background(self):\n print('save background')\n value = 'rgb({0}, {1}, {2})'.format(self.ui.rgb_background_color_1.value(),\n self.ui.rgb_background_color_2.value(),\n self.ui.rgb_background_color_3.value())\n self.server_database.save_user_style(self.username, value)\n\n def upload_photo(self):\n avatar = \\\n QtWidgets.QFileDialog.getOpenFileName(self, \"QFileDialog.getSaveFileName()\", \"\",\n \"JPEG (*.jpg);;PNG (*.png)\")[0]\n\n try:\n\n # saving file name\n self.server_database.save_avatar(self.username)\n\n photo = Image.open(f\"{avatar}\")\n print('avatar->', avatar)\n avatar = avatar.split('/')[-1]\n print(avatar)\n fileformat = '.' + avatar.split('.')[-1]\n print(fileformat)\n print(self.username, fileformat)\n photo.save(os.path.join(os.getcwd(), 'media', 'avatars', f'{self.username + fileformat}'))\n print('photo-> ', photo)\n print('path ->', os.path.join(os.getcwd(), 'media', 'avatars', f'{self.username + fileformat}'))\n\n # set photo again\n self.ui.set_profile_photo(self)\n except:\n QtWidgets.QMessageBox.warning(self, 'Error', \"We can't save your photo\")\n\n def save_profile_description(self):\n # save in database\n text = self.ui.descr.toPlainText()\n self.server_database.save_profile_description(self.username, text)\n\n def scale_profile_photo(self):\n if self.ui.profile_picture_height > 80 and self.ui.profile_picture_width > 120:\n self.ui.profile_picture_height -= 10\n self.ui.profile_picture_width -= 15\n # save photo in storage\n\n photo = self.ui.image\n format = '.jpg'\n print(photo.size)\n try:\n photo.save(os.path.join(os.getcwd(), 'media', 'avatars', f'{self.username + format}'))\n except:\n format = '.png'\n photo.save(os.path.join(os.getcwd(), 'media', 'avatars', f'{self.username + format}'))\n\n # and set it\n self.ui.set_profile_photo(self)\n\n # changes background color\n def set_background(self):\n value = f'rgb({self.ui.rgb_background_color_1.value()}, {self.ui.rgb_background_color_2.value()}, {self.ui.rgb_background_color_3.value()})'\n self.setStyleSheet('background-color: %s;' % value)\n\n def show_contacts_search(self):\n print(self.contacts_search_show)\n if self.contacts_search_show: # if true\n self.ui.search_contact_text_field.show()\n self.ui.search_contact_btn.show()\n self.contacts_search_show = False\n\n else: # if false\n self.ui.search_contact_text_field.hide()\n self.ui.search_contact_btn.hide()\n self.contacts_search_show = True\n\n # function which init, and load profile\n def view_profile(self):\n print(self.is_profile_visible)\n if self.is_profile_visible: # if true\n self.ui.username.show()\n self.ui.upload_photo.show()\n self.ui.descr.show()\n self.ui.btn_crop_image.show()\n self.ui.rgb_background_label.show()\n self.ui.rgb_background_color_1.show()\n self.ui.save_background.show()\n self.ui.rgb_background_color_2.show()\n self.ui.rgb_background_color_3.show()\n self.ui.photo.show()\n self.ui.save_descr.show()\n self.is_profile_visible = False\n\n else: # if false\n self.ui.username.hide()\n self.ui.upload_photo.hide()\n self.ui.descr.hide()\n self.ui.photo.hide()\n self.ui.btn_crop_image.hide()\n self.ui.rgb_background_label.hide()\n self.ui.rgb_background_color_1.hide()\n self.ui.rgb_background_color_2.hide()\n self.ui.save_background.hide()\n self.ui.rgb_background_color_3.hide()\n self.ui.save_descr.hide()\n self.is_profile_visible = True\n\n # function which inserts emoji into message text area\n def insert_smiley(self, filename):\n self.cursor = QtGui.QTextCursor(self.ui.text_message.document())\n path = os.path.join(os.getcwd(), 'assets', filename)\n print(path)\n self.ui.text_message.insertHtml(f'<img src=\"%s\">' % path)\n\n def show_format_buttons(self): # function which displays format buttons on the screen\n if self.format_buttons_show: # if true\n self.ui.btn_underlined.show()\n self.ui.btn_bold.show()\n self.ui.btn_italic.show()\n self.format_buttons_show = False\n\n else: # if false\n self.ui.btn_underlined.hide()\n self.ui.btn_bold.hide()\n self.ui.btn_italic.hide()\n self.format_buttons_show = True\n\n def show_smileys(self):\n if self.smileys_buttons_show: # if true\n self.ui.btn_funny_smiley.show()\n self.ui.btn_sad_smiley.show()\n self.ui.btn_crazy_smiley.show()\n self.smileys_buttons_show = False\n\n else: # if false\n self.ui.btn_funny_smiley.hide()\n self.ui.btn_sad_smiley.hide()\n self.ui.btn_crazy_smiley.hide()\n self.smileys_buttons_show = True\n\n # function which sets bold text to message text edit\n def set_bold_text(self):\n myFont = QtGui.QFont()\n myFont.setBold(True)\n self.ui.text_message.setFont(myFont)\n self.is_styled_text = 'Bold'\n\n # function which sets italic text to message text edit\n def set_italic_text(self):\n myFont = QtGui.QFont()\n myFont.setItalic(True)\n self.ui.text_message.setFont(myFont)\n self.is_styled_text = 'Italic'\n\n # function which sets bold text to message text edit\n def set_underlined_text(self):\n myFont = QtGui.QFont()\n myFont.setUnderline(True)\n self.ui.text_message.setFont(myFont)\n self.is_styled_text = 'Underlined'\n\n # Деактивировать поля ввода\n def set_disabled_input(self):\n # Надпись - получатель.\n self.ui.label_new_message.setText('Для выбора получателя дважды кликните на нем в окне контактов.')\n self.ui.text_message.clear()\n if self.history_model:\n self.history_model.clear()\n\n # Поле ввода и кнопка отправки неактивны до выбора получателя.\n self.ui.btn_clear.setDisabled(True)\n self.ui.btn_send.setDisabled(True)\n self.ui.text_message.setDisabled(True)\n\n # Заполняем историю сообщений.\n def history_list_update(self):\n try:\n print('history_list_update')\n # Получаем историю сортированную по дате\n list = []\n\n if self.current_chat == 'Global Chat':\n message_text_index = 1\n message_date_index = 2\n for message in self.database.get_messages_history_global():\n list.append(message)\n else:\n message_text_index = 3\n message_date_index = 4\n for message in self.database.get_messages_history(from_user=self.current_chat):\n list.append(message)\n for message in self.database.get_messages_history(to_user=self.current_chat):\n list.append(message)\n\n list = sorted(list, key=lambda item: item[message_date_index])\n\n print('list------------>', list)\n print('self.current_chat ', self.current_chat)\n print(self.database.get_messages_history(self.current_chat))\n\n # Если модель не создана, создадим.\n print(self.history_model)\n if not self.history_model:\n self.history_model = QStandardItemModel()\n self.ui.list_messages.setModel(self.history_model)\n # Очистим от старых записей\n self.history_model.clear()\n # Берём не более 20 последних записей.\n length = len(list)\n start_index = 0\n if length > 20:\n start_index = length - 20\n # Заполнение модели записями, так-же стоит разделить входящие и исходящие выравниванием и разным фоном.\n # Записи в обратном порядке, поэтому выбираем их с конца и не более 20\n for i in range(start_index, length):\n item = list[i]\n if item[1] == self.username:\n print('FONT STYLE -> ', item[-1])\n print('FONT STYLE TYPE -> ', type(item[-1]))\n if str(item[-1]) == '0': # if there is no font style\n mess = QStandardItem(f'{self.current_chat}:\\n {item[message_text_index]}')\n mess.setEditable(False)\n mess.setBackground(QBrush(QColor(255, 213, 213)))\n mess.setTextAlignment(Qt.AlignLeft)\n self.history_model.appendRow(mess)\n elif item[-1] == 'Bold': # if font style is bold\n mess = QStandardItem(f'{self.current_chat}:\\n {item[message_text_index]}')\n mess.setEditable(False)\n mess.setBackground(QBrush(QColor(255, 213, 213)))\n myFont = QtGui.QFont()\n myFont.setBold(True)\n mess.setFont(myFont)\n mess.setTextAlignment(Qt.AlignLeft)\n self.history_model.appendRow(mess)\n elif item[-1] == 'Italic': # if font style is italic\n mess = QStandardItem(f'{self.current_chat}:\\n {item[message_text_index]}')\n mess.setEditable(False)\n mess.setBackground(QBrush(QColor(255, 213, 213)))\n myFont = QtGui.QFont()\n myFont.setItalic(True)\n mess.setFont(myFont)\n mess.setTextAlignment(Qt.AlignLeft)\n self.history_model.appendRow(mess)\n elif item[-1] == 'Underlined': # if font style is underlined\n mess = QStandardItem(f'{self.current_chat}:\\n {item[message_text_index]}')\n mess.setEditable(False)\n mess.setBackground(QBrush(QColor(255, 213, 213)))\n myFont = QtGui.QFont()\n myFont.setUnderline(True)\n mess.setFont(myFont)\n mess.setTextAlignment(Qt.AlignLeft)\n self.history_model.appendRow(mess)\n\n else:\n print('FONT STYLE -> ', item[-1])\n print('FONT STYLE TYPE -> ', str(item[-1]))\n if str(item[-1]) == '0': # if there is no font style\n mess = QStandardItem(f'{self.username}:\\n {item[message_text_index]}')\n mess.setEditable(False)\n mess.setBackground(QBrush(QColor(204, 255, 204)))\n mess.setTextAlignment(Qt.AlignLeft)\n self.history_model.appendRow(mess)\n elif item[-1] == 'Bold': # if font style is bold\n mess = QStandardItem(f'{self.username}:\\n {item[message_text_index]}')\n mess.setEditable(False)\n mess.setBackground(QBrush(QColor(204, 255, 204)))\n myFont = QtGui.QFont()\n myFont.setBold(True)\n mess.setFont(myFont)\n mess.setTextAlignment(Qt.AlignLeft)\n self.history_model.appendRow(mess)\n elif item[-1] == 'Italic': # if font style is italic\n mess = QStandardItem(f'{self.username}:\\n {item[message_text_index]}')\n mess.setEditable(False)\n mess.setBackground(QBrush(QColor(204, 255, 204)))\n myFont = QtGui.QFont()\n myFont.setItalic(True)\n mess.setFont(myFont)\n mess.setTextAlignment(Qt.AlignLeft)\n self.history_model.appendRow(mess)\n elif item[-1] == 'Underlined': # if font style is underlined\n mess = QStandardItem(f'{self.username}:\\n {item[message_text_index]}')\n mess.setEditable(False)\n mess.setBackground(QBrush(QColor(204, 255, 204)))\n myFont = QtGui.QFont()\n myFont.setUnderline(True)\n mess.setFont(myFont)\n mess.setTextAlignment(Qt.AlignLeft)\n self.history_model.appendRow(mess)\n\n self.ui.list_messages.scrollToBottom()\n except Exception as e:\n print(e)\n\n # Функция обработчик даблклика по контакту\n def select_active_user(self):\n try:\n # Выбранный пользователем (даблклик) находится в выделеном элементе в QListView\n self.current_chat = self.ui.list_contacts.currentIndex().data()\n print(self.current_chat)\n # вызываем основную функцию\n self.set_active_user()\n except Exception as e:\n print(e)\n\n # Функция устанавливающяя активного собеседника\n def set_active_user(self):\n # Ставим надпись и активируем кнопки\n self.ui.label_new_message.setText(f'Введите сообщенние для {self.current_chat}:')\n self.ui.btn_clear.setDisabled(False)\n self.ui.btn_send.setDisabled(False)\n self.ui.text_message.setDisabled(False)\n\n # Заполняем окно историю сообщений по требуемому пользователю.\n self.history_list_update()\n\n def find_contact(self):\n try:\n query = self.ui.search_contact_text_field.toPlainText()\n contacts_query = self.database.find_contacts(self.username, query)\n print(contacts_query)\n self.contacts_model = QStandardItemModel()\n for i in sorted(contacts_query):\n print(i)\n item = QStandardItem(i[0])\n item.setEditable(False)\n self.contacts_model.appendRow(item)\n self.ui.list_contacts.setModel(self.contacts_model)\n except Exception as e:\n print(e)\n\n # Функция обновляющяя контакт лист\n def clients_list_update(self):\n contacts_list = self.database.get_contacts(self.username)\n self.contacts_model = QStandardItemModel()\n for i in sorted(contacts_list):\n item = QStandardItem(i)\n item.setEditable(False)\n self.contacts_model.appendRow(item)\n\n item = QStandardItem('Global Chat')\n item.setEditable(False)\n self.contacts_model.appendRow(item)\n self.ui.list_contacts.setModel(self.contacts_model)\n\n # Функция добавления контакта\n def add_contact_window(self):\n global select_dialog\n select_dialog = AddContactDialog(self.transport, self.database, self.username)\n select_dialog.btn_ok.clicked.connect(lambda: self.add_contact_action(select_dialog))\n select_dialog.show()\n\n # Функция - обработчик добавления, сообщает серверу, обновляет таблицу и список контактов\n def add_contact_action(self, item):\n try:\n new_contact = item.selector.currentText()\n print(new_contact)\n print(self.username)\n self.add_contact(self.username, new_contact)\n item.close()\n except Exception as e:\n print(e)\n\n # Функция добавляющяя контакт в базы\n def add_contact(self, username, new_contact):\n self.database.add_contact(username, new_contact)\n new_contact = QStandardItem(new_contact)\n new_contact.setEditable(False)\n self.contacts_model.appendRow(new_contact)\n logger.info(f'Успешно добавлен контакт {new_contact}')\n self.messages.information(self, 'Успех', 'Контакт успешно добавлен.')\n\n # Функция удаления контакта\n def delete_contact_window(self):\n global remove_dialog\n remove_dialog = DelContactDialog(self.database, self.username)\n remove_dialog.btn_ok.clicked.connect(lambda: self.delete_contact(remove_dialog))\n remove_dialog.show()\n\n # Функция обработчик удаления контакта, сообщает на сервер, обновляет таблицу контактов\n def delete_contact(self, item):\n selected = item.selector.currentText()\n self.database.del_contact(self.username, selected)\n self.clients_list_update()\n logger.info(f'Успешно удалён контакт {selected}')\n self.messages.information(self, 'Успех', 'Контакт успешно удалён.')\n item.close()\n # Если удалён активный пользователь, то деактивируем поля ввода.\n if selected == self.current_chat:\n self.current_chat = None\n self.set_disabled_input()\n\n # Функция отправки собщения пользователю.\n def send_message(self):\n print(self.current_chat)\n\n # Текст в поле, проверяем что поле не пустое затем забирается сообщение и поле очищается\n message_text = self.ui.text_message.toPlainText()\n self.ui.text_message.clear()\n if not message_text:\n return\n try:\n\n print('trying to send message')\n print('self.current_chat ', self.current_chat)\n self.transport.send_message(self.current_chat, message_text, self.is_styled_text)\n pass\n except OSError as err:\n print(err)\n if err.errno:\n self.messages.critical(self, 'Ошибка', 'Потеряно соединение с сервером!')\n self.close()\n self.messages.critical(self, 'Ошибка', 'Таймаут соединения!')\n except (ConnectionResetError, ConnectionAbortedError):\n self.messages.critical(self, 'Ошибка', 'Потеряно соединение с сервером!')\n self.close()\n else:\n if self.current_chat == 'Global Chat':\n print('saving to global chat')\n self.database.save_message_to_global(self.username, message_text, self.is_styled_text)\n logger.debug(f'Отправлено сообщение для {self.current_chat}: {message_text}')\n self.history_list_update()\n else:\n self.database.save_message(self.username, self.current_chat, 'out', message_text, self.is_styled_text)\n logger.debug(f'Отправлено сообщение для {self.current_chat}: {message_text}')\n self.history_list_update()\n\n # Слот приёма нового сообщений\n @pyqtSlot(str)\n def message(self, sender):\n print('message')\n notification.notify(\n title=f'SuperChat - Message from {sender}',\n message=\"You've got a new message\",\n # app_icon=os.path.join(os.getcwd(), 'assets', 'superchat.png'),\n app_icon=None,\n timeout=3, # seconds\n )\n print(os.path.join(os.getcwd(), 'assets', 'superchat.png'))\n\n if sender == self.current_chat:\n self.history_list_update()\n else:\n # Проверим есть ли такой пользователь у нас в контактах:\n if self.database.check_contact(sender, self.username):\n # Если есть, спрашиваем и желании открыть с ним чат и открываем при желании\n if self.messages.question(self, 'Новое сообщение', \\\n f'Получено новое сообщение от {sender}, открыть чат с ним?', QMessageBox.Yes,\n QMessageBox.No) == QMessageBox.Yes:\n self.current_chat = sender\n self.set_active_user()\n else:\n print('NO')\n # Раз нету,спрашиваем хотим ли добавить юзера в контакты.\n if self.messages.question(self, 'Новое сообщение', \\\n f'Получено новое сообщение от {sender}.\\n Данного пользователя нет в вашем контакт-листе.\\n Добавить в контакты и открыть чат с ним?',\n QMessageBox.Yes,\n QMessageBox.No) == QMessageBox.Yes:\n self.add_contact(self.username, sender)\n self.current_chat = sender\n self.set_active_user()\n\n # Слот потери соединения\n # Выдаёт сообщение о ошибке и завершает работу приложения\n @pyqtSlot()\n def connection_lost(self):\n self.messages.warning(self, 'Сбой соединения', 'Потеряно соединение с сервером. ')\n self.close()\n\n def make_connection(self, trans_obj):\n trans_obj.new_message.connect(self.message)\n trans_obj.connection_lost.connect(self.connection_lost)\n","sub_path":"hw19/client/main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":27899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"555692775","text":"r\"\"\"\n ____ _\n | _ \\ ___ __| |_ __ _ _ _ __ ___\n | |_) / _ \\ / _` | '__| | | | '_ ` _ \\\n | __/ (_) | (_| | | | |_| | | | | | |\n |_| \\___/ \\__,_|_| \\__,_|_| |_| |_|\n \n Copyright 2021 Podrum Team.\n \n This file is licensed under the GPL v2.0 license.\n The license file is located in the root directory\n of the source code. If not you may not use this file.\n\"\"\"\n\nfrom nbt_utils.tag_identifiers import TagIdentifiers\nfrom nbt_utils.utils.nbt import Nbt\n\n\nclass ListTag:\n def __init__(self, name: str = \"\", value: list = [], list_type: int = 1):\n self.id: int = TagIdentifiers.LIST_TAG\n self.name: str = name\n self.value: list = value\n self.list_type: int = list_type\n \n def read(self, stream) -> None:\n self.list_type = stream.read_byte_tag()\n size: int = stream.read_int_tag()\n result: list = []\n for i in range(0, size):\n tag = Nbt.new_tag(self.list_type)\n tag.read(stream)\n result.append(tag)\n self.value = result\n \n def write(self, stream) -> None:\n stream.write_byte_tag(self.list_type)\n stream.write_int_tag(len(self.value))\n for item in self.value:\n item.write(stream)\n","sub_path":"nbt_utils/tag/list_tag.py","file_name":"list_tag.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"38642888","text":"import json;\nfrom selenium import webdriver;\n\ndef termOptionsScrape():\n chromeOptions = webdriver.ChromeOptions();\n chromeOptions.add_argument(\"--incognito\");\n chromeOptions.binary_location = \"/usr/bin/brave-browser\"\n\n driver = webdriver.Chrome(executable_path=\"./chromedriver\", options=chromeOptions);\n driver.get(\"https://central.carleton.ca/prod/bwysched.p_select_term?wsea_code=EXT\");\n terms = driver.find_elements_by_xpath(\"//select[@id='term_code']/option\");\n data = {}\n for i in range(len(terms)):\n term = terms[i];\n text = term.text;\n termNum = term.get_attribute(\"value\");\n data[\"option\"+str(i)] = {\n \"text\": text,\n \"termNum\": termNum\n }\n \n termOptions = open(\"termOptions.json\", \"w\");\n termOptions.write(json.dumps(data));\n termOptions.close();\n driver.close();\n driver.quit();","sub_path":"termOptionsScrape.py","file_name":"termOptionsScrape.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"162271053","text":"# A simple script that uses blender to render views of a single object by rotation the camera around it.\r\n# Also produces depth map at the same time.\r\n#\r\n# Example:\r\n# /home/yuexin/blender-2.78c-linux-glibc219-x86_64/blender --background --python render_blender.py -- --views 10 ./obj_11.py\r\n#\r\n\r\nimport argparse, sys, os\r\nimport numpy as np\r\nimport math\r\nsys.path.append('./')\r\nfrom pysixd_stuff.pysixd import transform\r\nfrom pysixd_stuff.pysixd import view_sampler\r\nimport data_utils\r\nimport bpy\r\nfrom mathutils import Matrix, Vector\r\nimport cv2\r\n\r\nparser = argparse.ArgumentParser(description='Renders given obj file by rotation a camera around it.')\r\nparser.add_argument('obj', type=str,\r\n help='Path to the obj file to be rendered.')\r\nparser.add_argument('--sid',type=int)\r\nparser.add_argument('--eid',type=int)\r\n\r\n#parser.add_argument('--remove_doubles', type=bool, default=False,\r\n# help='Remove double vertices to improve mesh quality.')\r\n#parser.add_argument('--edge_split', type=bool, default=False,\r\n# help='Adds edge split filter.')\r\n#parser.add_argument('--depth_scale', type=float, default=1.4,\r\n# help='Scaling that is applied to depth. Depends on size of mesh. Try out various values until you get a good result. Ignored if format is OPEN_EXR.')\r\n#parser.add_argument('--color_depth', type=str, default='8',\r\n# help='Number of bit per channel used for output. Either 8 or 16.')\r\n#parser.add_argument('--format', type=str, default='PNG',help='Format of files generated. Either PNG or OPEN_EXR')\r\n\r\n\r\nargv = sys.argv[sys.argv.index(\"--\") + 1:]\r\nargs = parser.parse_args(argv)\r\n\r\npath_obj= args.obj\r\noutput_dir='D:/MSRA/BlenderRenderer/embedding92232s_camera/'\r\nis_shapenet= path_obj.split('.')[-1]=='obj'\r\ncam_K=np.array([[577.5, 0, 319.5], [0., 577.5, 239.5], [0., 0., 1.]]).reshape((3,3))\r\n#cam_K=np.array([1075.65, 0, 720 / 2, 0, 1073.90, 540 / 2, 0, 0, 1]).reshape(3, 3)\r\ncanonical_info=data_utils.get_canonical_config(is_shapenet)\r\nrender_w,render_h= 640,480\r\nout_shape = canonical_info['out_shape']\r\npad_factor = canonical_info['pad_factor']\r\ndist_z = canonical_info['dist_z']\r\n\r\npath_splits = path_obj.split('/')\r\nmodel_identifier = path_splits[-3] + '_' + path_splits[-2] if is_shapenet else '11'\r\ndir_imgs = os.path.join(os.path.join(output_dir, model_identifier), 'imgs')\r\npath_obj_bbs=os.path.join(os.path.join(output_dir, model_identifier), 'obj_bbs.npy')\r\npath_rot=os.path.join(os.path.join(output_dir, model_identifier), 'rot_infos.npz')\r\ndepth_scale=1.\r\n\r\n#############################################\r\ndata_utils.init_scene()\r\ndata_utils.load_obj(path_obj,depth_scale=depth_scale,remove_doubles=True,edge_split=True)\r\nlight_diffuse,light_specular=data_utils.init_lighting(canonical_info)\r\n\r\n##############################################\r\n# Set camera intrinsic\r\nscene = bpy.context.scene\r\ncam = scene.objects['Camera']\r\nif not is_shapenet:\r\n clip_start,clip_end=10,10000\r\n\r\nelif model_identifier.split('_')[0] in ['03642806']:\r\n clip_start,clip_end=dist_z-1.2, dist_z+1.2\r\nelse:\r\n clip_start,clip_end=0.1,100\r\ndata_utils.set_camera(cam_K,(render_w,render_h),scene,cam,clip_start,clip_end)\r\n#double check camera\r\nif False:\r\n fx,fy,ux,uy=cam_K[0,0],cam_K[1,1],cam_K[0,2],cam_K[1,2]\r\n print(fx,fy,ux,uy)\r\n fx2=cam.data.lens/cam.data.sensor_width*scene.render.resolution_x\r\n fy2=fx2*scene.render.pixel_aspect_y/scene.render.pixel_aspect_x\r\n\r\n cx2=scene.render.resolution_x*(0.5-cam.data.shift_x)\r\n cy2=scene.render.resolution_y*0.5+scene.render.resolution_x*cam.data.shift_y\r\n print(fx2,fy2,cx2,cy2,'\\n',scene.render.pixel_aspect_y,cam.data.sensor_height,scene.render.pixel_aspect_x,cam.data.sensor_width)\r\n\r\n\r\nview_Rs = data_utils.viewsphere_for_embedding_v2(num_sample_views=2000, num_cyclo=36, use_hinter=True)\r\nembedding_size=view_Rs.shape[0]\r\nif args.sid != 0:\r\n obj_bbs = np.load(path_obj_bbs)\r\nelse:\r\n obj_bbs = np.empty((5, 4))\r\n\r\ndebug=False\r\nif debug:\r\n img_poses=np.zeros((128,128*7,3),dtype=np.uint8)\r\n\r\nprint(args.sid)\r\nprint(\"obj_bbs size:\")\r\nprint(obj_bbs.shape)\r\n\r\nfor iid in range(args.sid, 5):\r\n R=view_Rs[iid]\r\n #R_m2c= np.array([-0.05081750, 0.99733198, -0.05241400, 0.93482399, 0.02903240, -0.35392201, -0.35145599, -0.06698330, -0.93380499]).reshape((3, 3))\r\n #t_m2c=np.array([50.10567277, -77.01673570, 958.81105256]).reshape((3,1))\r\n #R_m2c = np.array([0.22732917, -0.13885391, -0.96386789, -0.93565258, 0.24323566, -0.25571487, 0.26995383, 0.95997719, -0.07462456]).reshape((3, 3))\r\n #t_m2c = np.array([-42.09236434, -97.50670441, 799.79210049]).reshape((3, 1))\r\n\r\n R_m2c=R.copy()\r\n t_m2c=np.array([0,0,dist_z]).reshape((3,1))\r\n\r\n R_c2m = np.linalg.inv(R_m2c.copy())\r\n t_c2m = -R_c2m[:3,:3].dot(t_m2c)\r\n q_c2m_gl=data_utils.get_q_c2m_gl(R_c2m)\r\n\r\n #R_c2m*(R_m2c M+T_m2c)+T_c2m=M\r\n cam.location= t_c2m\r\n cam.rotation_quaternion=q_c2m_gl\r\n print(cam.location)\r\n print(cam.matrix_world)\r\n\r\n #Process lighting\r\n cur_lamp_loc = -R_c2m[:3,:3].dot(canonical_info['canonic_lamp_loc'])\r\n light_diffuse.location=cur_lamp_loc\r\n light_specular.location=cur_lamp_loc\r\n\r\n scene.render.image_settings.file_format = 'PNG'\r\n scene.render.filepath = os.path.join(dir_imgs, './{:05d}'.format(iid))\r\n\r\n bpy.ops.render.render(write_still=True)\r\n\r\n #####Post Process####\r\n print(\"Post process path:%s\" % os.path.join(dir_imgs, './{:05d}.png'.format(iid)))\r\n img_bgra = cv2.imread(os.path.join(dir_imgs, './{:05d}.png'.format(iid)), cv2.IMREAD_UNCHANGED)\r\n depth_y=img_bgra[:,:,3]\r\n for cc in range(0,3):\r\n img_bgra[:,:,cc]=np.where(depth_y,img_bgra[:,:,cc],255)\r\n\r\n if False:\r\n cv2.imwrite(os.path.join(output_dir,'./{:s}_{:d}.png'.format(model_identifier,iid)),img_bgra[:,:,:3].copy())\r\n\r\n ys, xs = np.nonzero(depth_y > 0)\r\n obj_bb = view_sampler.calc_2d_bbox(xs, ys, (render_w,render_h))\r\n obj_bbs[iid]=obj_bb\r\n\r\n bgr_y = img_bgra[:,:,0:3].copy()\r\n resized_bgr_y = data_utils.extract_square_patch(bgr_y, obj_bb, pad_factor, resize=out_shape[:2],\r\n interpolation=cv2.INTER_NEAREST)\r\n\r\n cv2.imwrite(os.path.join(dir_imgs, './{:05d}.png'.format(iid)),resized_bgr_y)\r\n\r\n if debug:\r\n img_poses[:,iid*128:(iid+1)*128,:]=resized_bgr_y.copy()\r\n if not is_shapenet:# and debug:\r\n obj_bbs0=np.load('../Edge-Network/embedding20s/11/obj_bbs.npy')\r\n print(obj_bbs0[iid],obj_bb)\r\n\r\nif debug:\r\n cv2.imwrite(os.path.join(output_dir,'./{:s}.png'.format(model_identifier)),img_poses)\r\nelse:\r\n print(\"save bbs:%s\" % path_obj_bbs)\r\n print(obj_bbs.shape)\r\n np.save(path_obj_bbs,obj_bbs)\r\n np.savez(path_rot, rots=view_Rs)\r\n\r\n\r\n\r\n\r\n\r\n\r\n'''\r\nif data in ['real_train', 'real_test']:\r\n intrinsics = np.array([[591.0125, 0, 322.525], [0, 590.16775, 244.11084], [0, 0, 1]])\r\nelse: ## CAMERA data\r\n intrinsics = np.array([[577.5, 0, 319.5], [0., 577.5, 239.5], [0., 0., 1.]])\r\n \r\ngt_pkl_path = os.path.join(gt_dir, 'results_{}_{}_{}.pkl'.format(data, image_path_parsing[-2], image_path_parsing[-1]))\r\nprint(gt_pkl_path)\r\nif (os.path.exists(gt_pkl_path)):\r\n with open(gt_pkl_path, 'rb') as f:\r\n gt = cPickle.load(f)\r\n result['gt_RTs'] = gt['gt_RTs']\r\n if 'handle_visibility' in gt:\r\n result['gt_handle_visibility'] = gt['handle_visibility']\r\n assert len(gt['handle_visibility']) == len(gt_class_ids)\r\n print('got handle visibiity.')\r\n else: \r\n result['gt_handle_visibility'] = np.ones_like(gt_class_ids)\r\n'''\r\n","sub_path":"BlenderScripts/render_codebook_postprocess.py","file_name":"render_codebook_postprocess.py","file_ext":"py","file_size_in_byte":7612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"337592657","text":"def cargar():\n lista=[]\n for x in range(10):\n valor=int(input(\"Cargar valor: \"))\n lista.append(valor)\n return lista\n\n\ndef retornar_mitad(lista):\n mitad=len(lista)//2\n return lista[:mitad]\n\n\ndef imprimir(datos):\n print(\"Contenido de la lista\")\n print(datos)\n\n\n# bloque principal\n\nlista=cargar()\nlista2=retornar_mitad(lista)\nimprimir(lista)\nimprimir(lista2)\n","sub_path":"ejercicio173.py","file_name":"ejercicio173.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"237638737","text":"import django.db\nimport django_filters.rest_framework\nfrom django.db.models import QuerySet\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import permissions, viewsets, generics, status\nfrom rest_framework.response import Response\n\nfrom .filters import TeamListFilter, MatchListFilter\nfrom .serializers import *\nfrom stadiums.models import Stadium\n\n\nclass LeagueViewSet(viewsets.ModelViewSet):\n serializer_class = LeagueSerializer\n queryset = League.objects.all()\n\n def get_permissions(self):\n if self.action in ['list', 'retrieve']:\n permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n else:\n permission_classes = [permissions.IsAdminUser]\n return [permission() for permission in permission_classes]\n\n\nclass SeasonViewSet(viewsets.ModelViewSet):\n serializer_class = SeasonSerializer\n queryset = Season.objects.all()\n\n def get_permissions(self):\n if self.action in ['list', 'retrieve']:\n permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n else:\n permission_classes = [permissions.IsAdminUser]\n return [permission() for permission in permission_classes]\n\n def partial_update(self, request, *args, **kwargs):\n return Response({'message': 'Method Not Allowed', 'status': 405}, status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n\nclass TeamsViewSet(viewsets.ModelViewSet):\n\n def get_serializer_class(self):\n if self.action in ['list', 'retrieve']:\n return TeamsListSerializer\n else:\n return TeamsCreateSerializer\n\n def get_permissions(self):\n if self.action in ['list', 'retrieve']:\n permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n else:\n permission_classes = [permissions.IsAdminUser]\n return [permission() for permission in permission_classes]\n\n def get_queryset(self):\n query_set = Team.objects.all() if self.request.user.is_staff else Team.objects.filter(is_active=True)\n if self.action == 'list':\n get_filters = TeamListFilter(self.request.GET, query_set)\n return get_filters.qs\n return query_set\n\n\nclass TeamMatchesGenericView(generics.ListAPIView):\n serializer_class = MatchListSerializer\n filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)\n filterset_class = MatchListFilter\n\n def get_queryset(self):\n return Match.objects.filter(\n Q(guest__id=self.kwargs.get('team_id')) | Q(host__id=self.kwargs.get('team_id'))).order_by(\n 'match_date').reverse()\n\n\nclass MatchesViewSet(viewsets.ModelViewSet):\n\n def get_serializer_class(self):\n if self.action in ['list', 'retrieve']:\n return MatchListSerializer\n else:\n return MatchCreateSerializer\n\n def get_permissions(self):\n if self.action in ['list', 'retrieve']:\n permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n else:\n permission_classes = [permissions.IsAdminUser]\n return [permission() for permission in permission_classes]\n\n def get_queryset(self):\n query_set = Match.objects.all()\n if self.action == 'list':\n get_filters = TeamListFilter(self.request.GET, query_set)\n query_set = get_filters.qs\n province = self.request.GET.get('province', None)\n stad_qs = Stadium.objects\n if province:\n stad_qs = stad_qs.filter(province__icontains=province)\n city = self.request.GET.get('city', None)\n if city:\n stad_qs = stad_qs.filter(city__icontains=province)\n stadium = self.request.GET.get('stadium', None)\n if stadium:\n stad_qs = stad_qs.filter(name__icontains=stadium)\n if isinstance(stad_qs, QuerySet):\n ids = set([std.id for std in stad_qs])\n query_set = query_set.filter(stadium__in=ids)\n return query_set\n\n def partial_update(self, request, *args, **kwargs):\n return Response({'message': 'Method Not Allowed', 'status': 405}, status=status.HTTP_405_METHOD_NOT_ALLOWED)\n\n\nclass MatchSeatsViewSet(viewsets.ModelViewSet):\n \"\"\"\n Viewset for creating match seats,\n match seat can be created solo, or in rows with respecting serializers\n \"\"\"\n serializer_class = MatchSeatsSerializer\n\n def get_queryset(self):\n return MatchSeats.objects.filter(match__id=self.kwargs.get('match_id', 0))\n\n def get_permissions(self):\n if self.action in ['list', 'retrieve']:\n permission_classes = [permissions.IsAuthenticatedOrReadOnly]\n else:\n permission_classes = [permissions.IsAdminUser]\n return [permission() for permission in permission_classes]\n\n def create(self, request, *args, **kwargs):\n match = self.kwargs.get('match_id', 0)\n match = get_object_or_404(Match, id=match)\n data = request.data\n if data.get('solo', None):\n data = data.get('solo')\n data['match'] = match.id\n ser = MatchSeatsSerializer(data=data)\n ser.is_valid(raise_exception=True)\n instance = ser.save()\n return Response({\n 'status': 201,\n 'message': 'Created Successfully',\n 'data': MatchSeatsSerializer(instance).data\n })\n elif data.get('rows'):\n data = data.get('rows')\n data['match'] = match.id\n ser = RowMatchSeatSerializer(data=data)\n ser.is_valid(raise_exception=True)\n ser.save()\n return Response({\n 'status': 201,\n 'message': 'Created Successfully',\n 'data': None\n })\n else:\n raise serializers.ValidationError({'data': 'Invalid Data sent'})\n\n def update(self, request, *args, **kwargs):\n request.data.update({'match': kwargs.get('match_id', 0)})\n return super(MatchSeatsViewSet, self).update(request, args, kwargs)\n\n def patch(self, request, match_id, *args, **kwargs):\n match = get_object_or_404(Match, id=match_id)\n data = request.data\n try:\n if data.get('solo', None):\n data = data.get('solo')\n instance = get_object_or_404(MatchSeats, match=match, id=data.pop('id', 0))\n data['match'] = instance.match.id\n print(data)\n ser = MatchSeatsSerializer(data=data)\n ser.is_valid(raise_exception=True)\n print(ser.validated_data)\n\n instance = ser.update(instance, ser.validated_data)\n return Response({\n 'status': 200,\n 'message': 'Updated Successfully',\n 'data': MatchSeatsSerializer(instance).data\n })\n elif data.get('rows'):\n data = data.get('rows')\n data['match'] = match.id\n ser = RowMatchSeatSerializer(data=data, partial=True)\n ser.is_valid(raise_exception=True)\n ser.update(None, ser.validated_data)\n return Response({\n 'status': 200,\n 'message': 'Updated Successfully',\n 'data': None\n })\n else:\n raise serializers.ValidationError({'data': 'Invalid Data sent'})\n except django.db.utils.IntegrityError:\n return Response({'message': {\n 'general': 'Seat is already defined',\n }, 'status': 400}, status=status.HTTP_400_BAD_REQUEST)\n\n","sub_path":"matches/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"509371249","text":"\"\"\"\nDownload router logs from ECM.\n\"\"\"\n\nfrom . import base\n\n\nclass Logs(base.ECMCommand):\n \"\"\" Show or clear router logs. \"\"\"\n\n name = 'logs'\n levels = ['debug', 'info', 'warning', 'error', 'critical']\n\n def setup_args(self, parser):\n parser.add_argument('idents', metavar='ROUTER_ID_OR_NAME', nargs='*')\n parser.add_argument('--clear', action='store_true', help=\"Clear logs\")\n parser.add_argument('-l', '--level', choices=self.levels)\n\n def run(self, args):\n if args.idents:\n routers = map(self.api.get_by_id_or_name, args.idents)\n else:\n routers = self.api.get_pager('routers')\n if args.clear:\n self.clear(args, routers)\n else:\n self.view(args, routers)\n\n def clear(self, args, routers):\n for rinfo in routers:\n print(\"Clearing logs for: %s (%s)\" % (rinfo['name'], rinfo['id']))\n self.api.delete('logs', rinfo['id'])\n\n def view(self, args, routers):\n filters = {}\n if args.level:\n filters['levelname'] = args.level.upper()\n for rinfo in routers:\n print(\"Logs for: %s (%s)\" % (rinfo['name'], rinfo['id']))\n for x in self.api.get_pager('logs', rinfo['id'], **filters):\n x['mac'] = rinfo['mac']\n print('%(timestamp)s [%(mac)s] [%(levelname)8s] '\n '[%(source)18s] %(message)s' % x)\n\ncommand_classes = [Logs]\n","sub_path":"ecmcli/commands/logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"619618492","text":"import hashlib\nimport logging\nfrom abc import ABC, abstractmethod\n\ntry:\n import botocore\n import boto3\n import s3fs\n EXTRA_S3_INSTALLED = True\nexcept ModuleNotFoundError:\n EXTRA_S3_INSTALLED = False\n\ntry:\n import gcsfs\n EXTRA_GS_INSTALLED = True\nexcept ModuleNotFoundError:\n EXTRA_GS_INSTALLED = False\n\nfrom useful.resource import mimetypes\n\n_log = logging.getLogger(__name__)\n\n\nclass ResourceURL:\n \"\"\"\n An object that parses url and defines a resource by its location, schema\n and mimetype.\n\n Args:\n url (str): String represeting URL specified in RFC 1738.\n mimetype (str, optional): MIME type conforming definions in RFC 2045,\n RFC 2046, RFC 2047, RFC 4288, RFC 4289 and RFC 2049. Allow\n additional non-standard \"application/yaml\" mimetype for \".yaml\" and\n \".yml\" extensions. Override extracted mimetype from url if\n specified. Defaults to None.\n \"\"\"\n def __init__(self, url, mimetype=None):\n self.url = url\n split = url.split(\"://\", 1)\n if len(split) == 1:\n self.scheme, self.path = \"file\", split[0]\n else:\n self.scheme, self.path = split\n\n # specify mimetype from argument or read from url extension\n self.mimetype = mimetype or mimetypes.guess_type(url)[0]\n\n\nclass Reader(ABC):\n def __init__(self, url):\n \"\"\"\n Wrap ResourceURL in a way that provides an interface to open resource,\n read through it and also calculate the hash sum without opening the\n file.\n\n Args:\n url (ResourceURL): resource URL representing mimetype, scheme and\n location of the resource.\n \"\"\"\n self.url = url\n\n @abstractmethod\n def open(*args, **kwargs):\n pass\n\n @abstractmethod\n def hash(self):\n pass\n\n\nclass LocalFile(Reader):\n def __init__(self, url):\n \"\"\"\n Read data and calculate sha256sum for a resource from local storage.\n\n Args:\n url (ResourceURL): resource URI representing mimetype, scheme and\n location of the resource.\n\n Raises:\n AssertionError: If ResourceURL.scheme is not `file` the resource is\n not a local file.\n \"\"\"\n assert url.scheme == \"file\"\n super().__init__(url)\n\n def open(self, *args, **kwargs):\n \"\"\"\n Method with arguments compatible with open() with `file=self.path`.\n For more details check out\n\n https://docs.python.org/3/library/functions.html#open\n \"\"\"\n return open(self.url.path, *args, **kwargs)\n\n def hash(self):\n \"\"\"\n Calculate sha256sum of a local file.\n\n Returns:\n str: sha256sum for file located on `self.path`\n \"\"\"\n _log.debug(f\"Started calculating sha256sum for '{self.url.path}'\",\n extra={\"path\": self.url.path})\n h = hashlib.sha256()\n b = bytearray(128 * 1024)\n mv = memoryview(b)\n with open(self.url.path, 'rb', buffering=0) as f:\n for n in iter(lambda: f.readinto(mv), 0):\n h.update(mv[:n])\n\n sha256sum = h.hexdigest()\n _log.debug(f\"Finished calculating sha256sum for '{self.url.path}'\",\n extra={\"path\": self.url.path, \"sha256sum\": sha256sum})\n return sha256sum\n\n\nclass S3File(Reader):\n def __init__(self, url):\n \"\"\"\n Read data from s3 and use etag as hash.\n\n Args:\n url (ResourceURL): resource URI representing mimetype, scheme and\n location of the resource.\n Raises:\n AssertionError: If extra useful-resource[s3] is not installed\n AssertionError: If ResourceURL.scheme is not `s3` the resource is\n not an s3 resource.\n \"\"\"\n assert EXTRA_S3_INSTALLED is True\n assert url.scheme == \"s3\"\n super().__init__(url)\n self.bucket, self.key = self.url.path.split(\"/\", 1)\n self.fs = s3fs.S3FileSystem(anon=False)\n\n def open(self, *args, **kwargs):\n \"\"\"\n Method with arguments compatible with open() with `file=path`. For more\n details check out\n\n https://s3fs.readthedocs.io/en/latest/api.html\n \"\"\"\n return self.fs.open(f\"{self.bucket}/{self.key}\", *args, **kwargs)\n\n def hash(self):\n \"\"\"\n Get etag for s3 document.\n\n Returns:\n str: etag hash string\n \"\"\"\n try:\n return boto3.client('s3').head_object(Bucket=self.bucket,\n Key=self.key)['ETag'][1:-1]\n except botocore.exceptions.ClientError:\n _log.warning(f\"Document {self.url.url} not found\",\n extra={\"url\": self.url.url})\n\n\nclass GSFile(Reader):\n def __init__(self, url):\n \"\"\"\n Read data from Google Storage and use crc32c sum as hash.\n\n Args:\n url (ResourceURL): resource URI representing mimetype, scheme and\n location of the resource.\n Raises:\n AssertionError: If extra useful-resource[gs] is not installed\n AssertionError: If ResourceURL.scheme is not `gs` the resource is\n not an Google Storage resource.\n \"\"\"\n assert EXTRA_GS_INSTALLED is True\n assert url.scheme == \"gs\"\n super().__init__(url)\n self.fs = gcsfs.GCSFileSystem()\n\n def open(self, *args, **kwargs):\n \"\"\"\n Method with arguments compatible with open() with `file=path`. For more\n details check out\n\n https://gcsfs.readthedocs.io/en/latest/api.html\n \"\"\"\n return self.fs.open(self.url.path, *args, **kwargs)\n\n def hash(self):\n \"\"\"\n Get crc32c sum for a google storage document.\n\n Returns:\n str: crc32c checksum\n \"\"\"\n try:\n return self.fs.info(self.url.path)[\"crc32c\"]\n except FileNotFoundError:\n _log.warning(f\"Document {self.url.url} not found\",\n extra={\"url\": self.url.url})\n except KeyError:\n _log.warning(f\"Checksum 'crc32c' for {self.url.url} not found\",\n extra={\"url\": self.url.url})\n\n\n# a simple dict of supported resource readers\nreaders = {\n \"file\": LocalFile,\n \"s3\": S3File,\n \"gs\": GSFile\n}\n","sub_path":"useful/resource/readers.py","file_name":"readers.py","file_ext":"py","file_size_in_byte":6392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"451811436","text":"import os\nimport requests\nimport json\nfrom datetime import datetime\nimport sys\nimport yagmail\nimport os\nimport socket\nimport time\nimport urllib.request\nfrom flask.json import jsonify\nfrom flask import Flask, request, render_template, url_for, flash, redirect, session, abort\nfrom flask_sqlalchemy import SQLAlchemy\n\n# pymysql.install_as_MySQLdb()\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://myadmin:QWert!@345@localhost/project1'\n# app.config['SQLALCHEMY_DATABASE_URI'] =\ndb = SQLAlchemy(app)\napp.secret_key = 'some_secret'\n\nclass User(db.Model):\n id=db.Column(db.Integer, primary_key=True)\n username=db.Column(db.String(80), unique=True)\n email=db.Column(db.String(120), unique=True)\n\n def __init__(self, username, email):\n self.username=username\n self.email=email\n\n def __repr__(self):\n return '<User %r>' % self.username\n\nclass Post(db.Model):\n id=db.Column(db.Integer, primary_key=True)\n title=db.Column(db.String(80))\n body=db.Column(db.Text)\n pub_date=db.Column(db.DateTime)\n\n category_id=db.Column(db.Integer, db.ForeignKey('category.id'))\n category=db.relationship('Category', backref=db.backref('posts', lazy='dynamic'))\n\n def __init__(self, title, body, category, pub_date=None):\n self.title=title\n self.body=body\n self.category=category\n if pub_date is None:\n pub_date = datetime.utcnow()\n self.pub_date=pub_date\n\n def __repr__(self):\n return '<Post %r>' % self.title\n\nclass Category(db.Model):\n id=db.Column(db.Integer, primary_key=True)\n name=db.Column(db.String(50))\n\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return '<Category %r>' % self.name\n\n\n@app.route(\"/\")\ndef hello():\n # return \"Hello world!\"\n # print(os.environ['CLEARDB_DATABASE_URL'])\n return render_template('index.html')\n\n@app.route(\"/dns\")\ndef dns():\n return render_template('dns.html')\n\n@app.route(\"/dnsshow\", methods=['GET','POST'])\ndef dnsshow():\n if request.method == 'POST':\n domain_suffix=request.form['domain']\n try:\n # DECLARING EMPTY LISTS TO STORE THE KEY VALUE PAIRS THAT RETURN FROM THE HTTP RESPONSE\n all_a_records=[]\n all_aaaa_records=[]\n all_mx_records=[]\n all_cn_records=[]\n all_soa_records=[]\n all_txt_records=[]\n all_ns_records=[]\n # DOMAIN PREFIXES\n a_domain_prefix='http://dns-api.org/A/'\n aaaa_domain_prefix = 'http://dns-api.org/AAAA/'\n mx_domain_prefix='http://dns-api.org/MX/'\n cn_domain_prefix='http://dns-api.org/CNAME/'\n soa_domain_prefix='http://dns-api.org/SOA/'\n txt_domain_prefix='http://dns-api.org/TXT/'\n ns_domain_prefix='http://dns-api.org/NS/'\n # @ RECORD LOOPUP==================\n domain_to_lookup=a_domain_prefix+domain_suffix\n resp = requests.get(domain_to_lookup)\n for a in resp.json():\n all_a_records.append(a)\n # =================================\n # AAAA RECORD LOOKuP\n domain_to_lookup = aaaa_domain_prefix+domain_suffix\n resp = requests.get(domain_to_lookup)\n print(\"finished the second lookup\")\n for aaaa in resp.json():\n all_aaaa_records.append(aaaa)\n # =================================\n # MX RECORD LOOKUP\n domain_to_lookup=mx_domain_prefix+domain_suffix\n resp=requests.get(domain_to_lookup)\n print(\"finished the 3rd lookup\")\n for mx in resp.json():\n all_mx_records.append(mx)\n # =================================\n # CNAME RECORD LOOKUP\n domain_to_lookup=cn_domain_prefix+domain_suffix\n resp=requests.get(domain_to_lookup)\n print(\"finished the 4th lookup\")\n for cn in resp.json():\n all_cn_records.append(cn)\n # =================================\n # SOA RECORD LOOKUP\n domain_to_lookup=soa_domain_prefix+domain_suffix\n resp=requests.get(domain_to_lookup)\n print(\"finished the 5th lookup\")\n for soa in resp.json():\n all_soa_records.append(soa)\n # =================================\n # TXT RECORD LOOKUP\n domain_to_lookup=txt_domain_prefix+domain_suffix\n resp=requests.get(domain_to_lookup)\n print(\"finished the sixth lookup\")\n for txt in resp.json():\n all_txt_records.append(txt)\n # =================================\n # NAMESERVER RECORD LOOKUP\n domain_to_lookup=ns_domain_prefix+domain_suffix\n resp=requests.get(domain_to_lookup)\n print(\"finished the 7th lookup\")\n for ns in resp.json():\n all_ns_records.append(ns)\n return render_template('dns.html',\n all_a_records = all_a_records,\n all_aaaa_records = all_aaaa_records,\n all_mx_records = all_mx_records,\n all_cn_records = all_cn_records,\n all_soa_records = all_soa_records,\n all_txt_records = all_txt_records,\n all_ns_records = all_ns_records,\n domain = domain_suffix)\n except:\n e = sys.exc_info()[0]\n flash('Please enter a domain')\n error = 'Please enter a domain'\n return redirect(url_for('dns'))\n # a_name = a_name, a_ttl = a_ttl, a_type = a_type, a_value = a_value)\n@app.route(\"/exception\", methods=['GET', 'POST'])\ndef exception():\n if request.method == 'POST':\n # GET ALL VALUES FROM FORM\n agent_name=request.form['agent_name']\n agent_email=request.form['agent_email']\n # sup_name=request.form['sup_name']\n sup_email=request.form['sup_email']\n approved_by=request.form['approved_by']\n exception_date=request.form['exception_date']\n start_time=request.form['start_time']\n end_time=request.form['end_time']\n reason = request.form['reason']\n yag = yagmail.SMTP('exappv2', 'QWErty!@#456')\n title = '<h2>Exception Submission</h2>'\n sender = '<p><b>Agent: </b>{}</p>'.format(agent_name)\n sender_email = '<p><b>Agent Email: </b>{}</p>'.format(agent_email)\n # manager = '<p><b>Manager: </b>{}</p>'.format(sup_name)\n approved_by = '<p><b>Approved by: </b>{}</p>'.format(approved_by)\n exception_date = '<p><b>Date: <b>{}</p>'.format(exception_date)\n start_time = '<p><b>Start Time: </b>{}</p>'.format(start_time)\n end_time = '<p><b>End Time: </b>{}</p>'.format(end_time)\n reason = '<p><b>Reason: </b>{}</p>'.format(reason)\n email_footer = '<br><p>=====================================</p></br><p>This email was automagically created and sent using python 3, yag, and some coding judo.'\n contents = [title, sender, sender_email, approved_by, exception_date, start_time, end_time, reason, email_footer]\n # Send the email to the manager | Change the email in the functiion to the variable recipient\n if agent_name and agent_email and sup_email and approved_by and exception_date and start_time and end_time and reason:\n yag.send(sup_email, 'Exception Submission', contents)\n # Send the confirmation email\n yag.send(agent_email, 'Exception Confirmation', 'Your exception was successfuly submited.')\n flash('Submitted Exception')\n return render_template('exception.html')\n else:\n flash(\"Error submitting exception! Verify all fields filled out\")\n return render_template('exception.html')\n elif request.method == \"GET\":\n return render_template('exception.html')\n else: return render_template('error.html')\n\n@app.route(\"/templates\")\ndef templates():\n return render_template('templates.html')\n\n@app.route(\"/feedback\", methods=['GET', 'POST'])\ndef feedback():\n if request.method == 'POST':\n fb_agent_email = request.form['fb_agent_email']\n fb_agent_name = request.form['fb_agent_name']\n feedback = request.form['feedback']\n print(fb_agent_email)\n print(fb_agent_name)\n print(feedback)\n yag = yagmail.SMTP('exappv2', 'QWErty!@#456')\n title = '<h2>Feedback Submission</h2>'\n sender = '<p><b>Agent: </b>{}</p>'.format(fb_agent_name)\n sender_email = '<p><b>Agent Email: </b>{}</p>'.format(fb_agent_email)\n feedback = '<p><b>Feedback: </b>{}</p>'.format(feedback)\n contents = [title, sender, sender_email, feedback]\n default_reply= '<p>Thanks for the feedback. Your submission will go a long way towards making this project a better resource for everyone that uses it</p>'\n yag.send('steven.antonio.dev@gmail.com', 'TBP Feedback Submission', contents)\n yag.send(fb_agent_email, 'Thanks you for your feedback', default_reply)\n # flash('Feedback Sent')\n return render_template('feedback.html')\n elif request.method == 'GET':\n return render_template('feedback.html')\n else: return render_template('error.html')\n\n@app.route(\"/products\", methods=['POST', 'GET', 'DELETE'])\ndef products():\n return \"The products GEet\"\n\n@app.route(\"/products-login\", methods=['POST', 'GET'])\ndef productslogin():\n return \"The login page\"\n\n@app.route(\"/speedtest\", methods=['POST', 'GET'])\ndef speedtest():\n if request.method == 'POST':\n hostname = request.form['speed-domain']\n # hostname=\"stevenanton.io\"\n # print(hostname)\n dns_start = time.time()\n ip_address = socket.gethostbyname(hostname)\n dns_end = time.time()\n dns_time = (dns_end - dns_start) * 1000\n\n url = 'http://%s/' % ip_address\n req = urllib.request.Request(url)\n req.add_header('Host', hostname)\n\n handshake_start = time.time()\n stream = urllib.request.urlopen(req)\n handshake_end = time.time()\n handshake_time = (handshake_end - handshake_start) * 1000\n\n data_start = time.time()\n data_length = len(stream.read())\n data_end = time.time()\n data_time = (data_end - data_start) * 1000\n\n print(\"=====================================\")\n print(\"DOMAIN: = %s\" % hostname)\n print('DNS time = %.2f ms' % ((dns_end - dns_start) * 1000))\n print('HTTP handshake time = %.2f ms' % ((handshake_end - handshake_start) * 1000))\n print('HTTP data time = %2.f ms' % ((data_end - data_start) * 1000))\n print('Data received = %d bytes' % data_length)\n print(\"=====================================\")\n print (\"post method used\")\n return render_template(\"speedtest.html\",\n dns_start = dns_start,\n ip_address = ip_address,\n dns_end = dns_end,\n url = url,\n req = req,\n handshake_start = handshake_start,\n stream = stream,\n handshake_end = handshake_end,\n data_start = data_start,\n data_length = data_length,\n data_end = data_end,\n dns_time = dns_time,\n handshake_time = handshake_time,\n data_time = data_time)\n elif request.method == 'GET':\n return render_template(\"speedtest.html\")\n else:\n return render_template(\"error.html\")\n\n@app.route(\"/echo\", methods=['POST'])\ndef echo():\n return render_template('echo.html', text=request.form['text'])\n\n\n\nif __name__ == \"__main__\":\n port = int(os.environ.get(\"PORT\", 33507))\n app.run(host='0.0.0.0', port=port, debug=True)\n\n# from flask import Flask\n# app = Flask(__name__)\n#\n#\n#\n# quarks = [{'name': 'up', 'charge': '+2/3'},\n# {'name': 'down', 'charge': '-1/3'},\n# {'name': 'charm', 'charge': '+2/3'},\n# {'name': 'strange', 'charge': '-1/3'}]\n#\n#\n#\n# @app.route('/', methods=['GET'])\n# def hello_world():\n# return jsonify({'message' : 'Hello, World!'})\n#\n# @app.route('/quarks', methods=['GET'])\n# def returnAll():\n# return jsonify({'quarks' : quarks})\n#\n# @app.route('/quarks/<string:name>', methods=['GET'])\n# def returnOne(name):\n# theOne = quarks[0]\n# for i,q in enumerate(quarks):\n# if q['name'] == name:\n# theOne = quarks[i]\n# return jsonify({'quarks' : theOne})\n#\n# @app.route('/quarks', methods=['POST'])\n# def addOne():\n# new_quark = request.get_json()\n# quarks.append(new_quark)\n# return jsonify({'quarks' : quarks})\n#\n# @app.route('/quarks/<string:name>', methods=['PUT'])\n# def editOne(name):\n# new_quark = request.get_json()\n# for i,q in enumerate(quarks):\n# if q['name'] == name:\n# quarks[i] = new_quark\n# qs = request.get_json()\n# return jsonify({'quarks' : quarks})\n#\n# @app.route('/quarks/<string:name>', methods=['DELETE'])\n# def deleteOne(name):\n# for i,q in enumerate(quarks):\n# if q['name'] == name:\n# del quarks[i]\n# return jsonify({'quarks' : quarks})\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":13255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"431424277","text":"global code\ncode = {65: 66, 66: 67, 67: 68, 68: 69, 69: 70, 70: 71, 71: 72, 72: 73, 73: 74, 74: 75, 75: 76, 76: 77, 77: 78, 78: 79, 79: 80, 80: 81, 81: 82, 82: 83, 83: 84, 84: 85, 85: 86, 86: 87, 87: 88, 88: 89, 89: 90, 90: 65}\n\n\ndef mvencode():\n global code\n test = {}\n for i in range(65,91):\n tmp = code[i]+n\n while tmp > 90:\n tmp-=26\n test[i] = tmp\n code = test\n print(code)\n\ndef encoding(txt):\n big = 1\n ordc = ord(txt)\n if ordc > 90 :\n big = 0\n ordc -=32\n result = code[ordc]\n if big == 0:\n result +=32\n\n mvencode()\n return chr(result)\n\ndef encode():\n with open('../testFile/testFile1.txt','r') as ft , open('entest.txt','w') as fs:\n while True:\n tmp = ft.read(1)\n if not tmp:\n break\n elif (ord(tmp)>=65 and ord(tmp)<=90) or (ord(tmp)>=97 and ord(tmp)<=122):\n tmp = encoding(tmp)\n fs.write(tmp)\n\n''' \ns = 'abcdef'\nprint(code)\nprint(s)\ns1 =''\nfor i in s:\n s1+=encoding(i)\nprint(s1)\n'''\nglobal n\nn=10\nencode()\n","sub_path":"Double-Encypt/AdvanceEncode.py","file_name":"AdvanceEncode.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"230643322","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 28 12:43:30 2018\n\n@author: yifan\n\"\"\"\n\n'''\nPredict CO adsorption energy for one plane\n'''\n\n\nimport sys\nimport os\nimport numpy as np\nimport pandas as pd\nimport pickle \n\nfrom ase.io import read, write\nfrom ase.visualize import view\nfrom ase import Atom\nfrom sympy import Plane, Point3D\nfrom itertools import combinations \n\n\nfrom sklearn.decomposition import PCA \nfrom sklearn.preprocessing import StandardScaler \n\nHomePath = os.path.expanduser('~')\nsys.path.append(os.path.join(HomePath,'Documents','GitHub', 'Pdn-Dynamics-Model','CO-adsorption', 'pool'))\n\nfrom Pdbulk import NN1,NN2\n\n#%% User define function block\n\ndef remove_CO(filename):\n '''\n Read the old CONTCAR file with a CO onto it\n remove the CO and save as a new CONTCAR\n ''' \n old_name = filename #'pd20-ceria-co-CONTCAR'\n atoms = read(old_name)\n view(atoms)\n \n # find number of Pd\n # find C atom index\n nPd = 0\n \n for i, atom in enumerate(atoms):\n if atom.symbol == 'Pd': \n nPd = nPd + 1\n if atom.symbol == 'C':\n C_in_CO = i\n \n C_O_Dist = []\n O_in_CO = [] \n \n for k, atom in enumerate(atoms):\n if atom.symbol == 'O':\n dist = atoms.get_distance(C_in_CO, k)\n C_O_Dist.append(dist)\n O_in_CO.append(k)\n \n O_in_CO = O_in_CO[C_O_Dist.index(min(C_O_Dist))]\n \n del atoms[[O_in_CO, C_in_CO]]\n view(atoms)\n write('pd'+str(nPd)+'-test-CONTCAR', atoms)\n \n #Example: remove_CO('pd20-ceria-co-CONTCAR')\n\ndef view_in_POV(atoms, filename = 'Pd20'):\n \n pov_args = {\n\t'transparent': True, #Makes background transparent. I don't think I've had luck with this option though\n 'canvas_width': 3600., #Size of the width. Height will automatically be calculated. This value greatly impacts POV-Ray processing times\n 'display': False, #Whether you want to see the image rendering while POV-Ray is running. I've found it annoying\n 'rotation': '0x,70y,90z', #Position of camera. If you want different angles, the format is 'ax, by, cz' where a, b, and c are angles in degrees\n 'celllinewidth': 0.02, #Thickness of cell lines\n 'show_unit_cell': 0 #Whether to show unit cell. 1 and 2 enable it (don't quite remember the difference)\n #You can also color atoms by using the color argument. It should be specified by an list of length N_atoms of tuples of length 3 (for R, B, G)\n #e.g. To color H atoms white and O atoms red in H2O, it'll be:\n #colors: [(0, 0, 0), (0, 0, 0), (1, 0, 0)]\n }\n\n #Write to POV-Ray file\n \n #write('Pd1CO.POV', atoms, **pov_args)\n\n write(filename + '.POV', atoms, **pov_args)\n\n \n \ndef sort_i_and_d(D,I):\n '''\n Sort indices based on the atomic bond length\n return the sorted bond length and indices in ascending order\n '''\n D = list(D)\n Dsort = np.sort(D)\n D_unqiue_sort = np.sort(np.unique(D))\n D_unqiue_sort = list(D_unqiue_sort)\n Isort = []\n for d in D_unqiue_sort:\n indices = [i for i, x in enumerate(D) if x == d]\n for i in indices: Isort.append(I[i])\n \n return Dsort,Isort\n\ndef find_all_Pd(atoms):\n '''\n Count number of atoms, return all Pd atom indices\n '''\n Pd_indices = []\n \n for i, atom in enumerate(atoms):\n if atom.symbol == 'Pd': Pd_indices.append(i) \n \n return Pd_indices\n\n\ndef find_bridge_pairs(Pd_pairs, atoms):\n \n bridge_pairs = []\n for pair in Pd_pairs:\n Pd_Pd = atoms.get_distances([pair[0]], [pair[1]])\n if np.logical_and(Pd_Pd>=NN1[0], Pd_Pd<=NN1[1]):\n bridge_pairs.append(list(pair))\n \n return bridge_pairs\n \ndef find_hollow_triples(Pd_triples , atoms):\n \n hollow_triples = []\n for triple in Pd_triples:\n Pd_Pd1 = atoms.get_distances(triple[0], [triple[1], triple[2]])\n Pd_Pd2 = atoms.get_distances([triple[1]], [triple[2]])\n flag1 = np.logical_and(Pd_Pd1>=NN1[0], Pd_Pd1<=NN1[1])\n flag2 = np.logical_and(Pd_Pd2>=NN1[0], Pd_Pd2<=NN1[1])\n \n if np.all(list(flag1)+list(flag2)):\n hollow_triples.append(list(triple))\n \n return hollow_triples\n \n\n\n# write a class for it\nclass PdCO():\n\n def __init__(self):\n \n '''\n Initializing descriptor variables\n '''\n \n self.Eads = [] # CO adsorption energy - y\n self.NPd = [] #No1\n self.Nsites = [] #No2 \n self.NN1_wavg = [] #No3\n self.NN2_wavg = [] #No4\n self.Dsupport = [] #No5\n \n self.sitetype = []\n self.descriptors = []\n self.site_PdC = site_PdC\n \n def get_descriptors(self, atoms, CO_sites):\n '''\n Takes in a structure dictionary with an atoms object and filename \n Input tolerance for Pd-C bond 0.3 A for detecting CO ads site\n '''\n self.atoms = atoms.copy()\n self.CO_sites = CO_sites \n\n '''\n Determine C position and site type\n '''\n Pd_pos = []\n for i in self.CO_sites: Pd_pos.append(self.atoms[i].position)\n self.C_pos = np.mean(Pd_pos, axis = 0) \n self.atoms.append(Atom('C', self.C_pos))\n self.Nsites = len(self.CO_sites)\n \n if self.Nsites== 3: self.sitetype = 'hollow' \n if self.Nsites == 2: self.sitetype = 'bridge'\n if self.Nsites == 1: self.sitetype = 'top'\n \n '''\n Count number of atoms\n '''\n # Atom index\n Pdi = []\n Cei = []\n Ci = []\n \n for i, atom in enumerate(self.atoms):\n if atom.symbol == 'Pd': Pdi.append(i)\n if atom.symbol == 'Ce': Cei.append(i)\n if atom.symbol == 'C': Ci.append(i)\n \n #No of Pd atoms in the cluster\n self.NPd = int(len(Pdi)) \n \n '''\n Get the bond length of C-Ce, Pd-C, Pd-Pd\n and NN table for each Pd\n '''\n\n Pd_C = self.atoms.get_distances(Ci[0], Pdi, mic = True) #all Pd-C bond length \n \n Pd_C, Pdi = sort_i_and_d(Pd_C, Pdi) #sorted Pd-C bond length\n \n PdC3 = self.site_PdC[self.sitetype]\n self.PdC1 = PdC3[0]\n self.PdC2 = PdC3[1]\n self.PdC3 = PdC3[2]\n \n C_Ce = self.atoms.get_distances(Ci[0], Cei, mic = True)#all Ce-C bond length\n C_Ce, Cei = sort_i_and_d(C_Ce, Cei) #sorted Ce-C bond length\n \n Pd_Pd = pd.DataFrame() #Pd to Pd bond length table \n PdNN = pd.DataFrame() #Pd NN table \n Pd1NN= dict() #Pd NN table \n \n \n for i in Pdi:\n PdD = self.atoms.get_distances(i, Pdi)\n PdD, Pdisort = sort_i_and_d(PdD,Pdi)\n \n Pd_Pd['Pd'+str(i)] = PdD\n Pd_Pd['i'+str(i)] = Pdisort\n PdNN['Pd'+str(i)] = [sum(np.logical_and(PdD>=NN1[0], PdD<=NN1[1])),\n sum(np.logical_and(PdD>=NN2[0], PdD<=NN2[1]))]\n Pd1NN['Pd'+str(i)] = np.array(Pdisort)[np.where(np.logical_and(PdD>=NN1[0],PdD<=NN1[1]))[0]]\n \n PdNN.index = ['NN1','NN2'] \n \n\n #take the distance of CO to Ce plane (determined by 3 Ce points)\n # as the distance to support\n Ce_plane = Plane(Point3D(self.atoms[Cei[0]].position), \n Point3D(self.atoms[Cei[1]].position), \n Point3D(self.atoms[Cei[2]].position))\n self.Dsupport = float(Ce_plane.distance(Point3D(self.atoms[Ci[0]].position)))\n \n '''\n Detect CO adsorption sites\n '''\n \n COsites_cols = []\n for s in range(len(self.CO_sites)):\n COsites_cols.append('Pd'+str(self.CO_sites[s]))\n \n PdNN_CO = PdNN.loc[:, COsites_cols] #NN dataframe \n #Pd_C_CO = np.array([:len(self.CO_sites)]) #CO distance to neighboring Pd atoms\n \n '''\n Average for NN1, NN2\n '''\n #norm_weights = (1/Pd_C_CO)/np.sum(1/Pd_C_CO) #weights based on 1 over CO-Pd distance\n \n self.CN1 = np.mean(PdNN_CO.loc['NN1'].values)\n self.CN2 = np.mean(PdNN_CO.loc['NN2'].values)\n \n \n '''\n Make a row in dataframe as an ID for each structure including filenames and properties etc\n '''\n self.structureID = [self.atoms, # atoms object\n self.Eads, #Eads\n self.NPd, #Npd\n self.sitetype, #sitetype from calculation\n self.CO_sites, #Pd index at the adsoprtion site\n self.C_pos, #CO position \n self.CN1, #CN1\n self.CN2, #CN2\n self.Dsupport, #Z\n self.Nsites, #number of sites\n self.PdC1, #1st Pd-C distance \n self.PdC2, #2nd Pd-C distance\n self.PdC3] #3rd Pd-C distance\n\n\n#%%\n'''\nBond length value calculation from the given dataset\n'''\n\ncsv_file = os.path.join(HomePath,'Documents','GitHub', 'Pdn-Dynamics-Model','CO-adsorption', 'pool', 'descriptor_data.csv')\nfdata = pd.read_csv(csv_file)\ndescriptors = ['NPd', 'CN1', 'CN2','GCN', 'Z', 'Charge', 'Nsites', 'Pd1C', 'Pd2C', 'Pd3C'] #10 in total\nsitetype_list = list(fdata.loc[:,'SiteType'])\nX = np.array(fdata.loc[:,descriptors], dtype = float)\n\nPdCs = ['Pd1C', 'Pd2C', 'Pd3C'] \nPdCi = []\n\nfor PdC in PdCs: PdCi.append(descriptors.index(PdC))\nXsite = [] \nfor cnt in PdCi:\n for site in ['top', 'bridge', 'hollow']:\n indices = np.where(np.array(sitetype_list) == site)[0]\n Xsite.append(X[:,cnt][indices])\n\ntop_PdC1 = np.mean(Xsite[0])\nbridge_PdC1 = np.mean(Xsite[1])\nhollow_PdC1 = np.mean(Xsite[2])\n\ntop_PdC2 = np.mean(Xsite[3][np.nonzero(Xsite[3])])\nbridge_PdC2 = bridge_PdC1 #np.mean(Xsite[4][np.nonzero(Xsite[4])])\nhollow_PdC2 = hollow_PdC1 #np.mean(Xsite[5][np.nonzero(Xsite[5])])\n\ntop_PdC3 = np.mean(Xsite[6][np.nonzero(Xsite[6])])\nbridge_PdC3 = np.mean(Xsite[7][np.nonzero(Xsite[7])])\nhollow_PdC3 = hollow_PdC1 #np.mean(Xsite[8][np.nonzero(Xsite[8])])\n\nsite_PdC = dict([('top', [top_PdC1, top_PdC2, top_PdC3]),\n ('bridge', [bridge_PdC1, bridge_PdC2, bridge_PdC3]),\n ('hollow', [hollow_PdC1, hollow_PdC2, hollow_PdC3])])\n#%%\n \n'''\nLoad the CONTCAR file with Pdn structure\n'''\n \nfilename = 'pd20-test-CONTCAR'\natoms = read(filename)\nview(atoms)\nview_in_POV(atoms)\n\n#Find all Pd atoms\nPd_indices = find_all_Pd(atoms)\n#Pd_no_interest = [97, 100, 102, 103]\nPd_interest = [107, 96, 98, 111, 106, 99, 110, 113, 112, 115]#[x for x in Pd_indices if x not in Pd_no_interest]\n\n#Find all CO adsorption sites\ntop_sites = []\nfor Pdi in Pd_interest: top_sites.append([Pdi])\n\nbridge_sites = [] \nPd_pairs = list(combinations(Pd_interest,2))\nbridge_sites = find_bridge_pairs(Pd_pairs, atoms)\n\n \nhollow_sites = [] \nPd_triples = list(combinations(Pd_interest,3))\nhollow_triples = find_hollow_triples(Pd_triples, atoms)\nhollow_sites = hollow_triples \n \nCO_sites = top_sites + bridge_sites + hollow_sites\n\n#\n#%% Analyse the structures and save into a csv file\nNtot = len(CO_sites) \nlabels = ['AtomsObject', 'Eads', 'NPd', 'SiteType', 'CO sites', 'CO Position',\n 'CN1', 'CN2', 'Z', 'Nsites', 'Pd1C', 'Pd2C', 'Pd3C']\n\nfdata = pd.DataFrame(columns = labels)\nfor i,site in enumerate(CO_sites):\n \n PdCO_ob = PdCO()\n PdCO_ob.get_descriptors(atoms, site)\n #if PdCO_ob.filename != 'pd5-ceria-co-CONTCAR':\n fdata.loc[i,:] = PdCO_ob.structureID\nfdata.to_csv('g_descriptor_data.csv', index=False, index_label=False)\n\n#%% Predict the energy \n\ndescriptors_g = ['CN1', 'Z', 'Nsites', 'Pd1C', 'Pd2C', 'Pd3C'] #6 geometric descriptors\ndem = np.array(fdata.loc[:,descriptors_g], dtype = float)\nsitetype_list = list(fdata.loc[:,'SiteType'])\n\nCO_pos = np.zeros((len(sitetype_list), 3))\nfor i in range(len(sitetype_list)):\n CO_pos[i,:] = fdata['CO Position'][i]\n\npca = PCA() \nX_g = dem.copy()\nX_std_g = StandardScaler().fit_transform(X_g)\nXpc_g = pca.fit_transform(X_std_g) \n\nestimator_file = os.path.join(HomePath,'Documents','GitHub', 'Pdn-Dynamics-Model','CO-adsorption', 'pool', 'g_estimator')\npcg_estimator = pickle.load(open(estimator_file,'rb'))\ny_pcg = pcg_estimator.predict(Xpc_g)\n\n\n#%% Plot the energy value for top, bridge, hollow sites\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"CO-adsorption/energy_prediction/bond_length_v3.py","file_name":"bond_length_v3.py","file_ext":"py","file_size_in_byte":12451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"583257630","text":"#!/usr/bin/env python\nimport email\nimport re\nimport csv\nimport os\n\nfile_names = []\n\ndef retrieve_sent_date():\n\temail_date = msg[\"Date\"]\n\tregex = re.compile(r\"\\d+\\s[A-Za-z]+\\s[0-9]+\")\n\tdate = regex.findall(email_date)\n\treturn date[0]\n\ndef retrieve_first_name():\n\temail_subject = msg[\"subject\"]\n\tregex = re.compile(r\"[A-Za-z]+\")\n\tfirst_name = regex.findall(email_subject)\n\treturn first_name[0]\n\ndef retrieve_last_name():\n\temail_subject = msg[\"subject\"]\n\tregex = re.compile(r\"[A-Za-z]+\")\n\tlast_name = regex.findall(email_subject)\n\treturn last_name[1]\n\ndef retrieve_service_wanted():\n\temail_body = msg.get_payload()\n\tstrip_email_body = email_body.replace(\"\"\"redacted\"\"\", \"\")\n\tfor services in services_offered:\n\t\tif strip_email_body.find(\"\"\"redacted\"\"\") != -1 or strip_email_body.find(\"\"\"redacted\"\"\") != -1:\n\t\t\treturn \"\"\"redacted\"\"\"\n\n\t\telif strip_email_body.find(\"\"\"redacted\"\"\") != -1 or strip_email_body.find(\"\"\"redacted\"\"\") != -1:\n\t\t\treturn \"\"\"redacted\"\"\"\n\n\t\telif strip_email_body.find(\"\"\"redacted\"\"\") != -1 or strip_email_body.find(\"\"\"redacted\"\"\") != -1:\n\t\t\treturn \"\"\"redacted\"\"\"\n\n\t\telse:\n\t\t\t\"An error occured\"\n\nfor file in os.listdir(\".\"):\n\tif file.endswith(\".eml\"):\n\t\tfile_names.append(file)\n\ncsv_output = open(\"output.csv\", \"wb+\")\n\nfor file in file_names:\n\tinput_files = open(file)\n\tmsg = email.message_from_file(input_files)\n\tcsv_rows = \"{0},{1},{2},{3}\\n\".format(retrieve_sent_date(), retrieve_first_name(), retrieve_last_name(), retrieve_service_wanted())\n\tcsv_output.write(csv_rows)\n\ncsv_output.close()","sub_path":"eml_to_csv.py","file_name":"eml_to_csv.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"350908740","text":"from pyvi import ViTokenizer, ViPosTagger \nfrom tqdm import tqdm\nimport numpy as np\nimport gensim\nimport os \nimport pickle\ndir_path = os.path.dirname(os.path.realpath(os.getcwd()))\ndir_path = os.path.join(dir_path, 'NLP')\n\ndef get_data(folder_path):\n X = []\n y = []\n dirs = os.listdir(folder_path)\n for path in tqdm(dirs):\n file_paths = os.listdir(os.path.join(folder_path, path))\n for file_path in tqdm(file_paths):\n with open(os.path.join(folder_path, path, file_path), 'r', encoding=\"utf-16\") as f:\n lines = f.readlines()\n lines = ' '.join(lines)\n lines = gensim.utils.simple_preprocess(lines)\n lines = ' '.join(lines)\n lines = ViTokenizer.tokenize(lines)\n\n X.append(lines)\n y.append(path)\n\n return X, y\n\ntrain_path = os.path.join(dir_path, 'Train_Full')\nX_data, y_data = get_data(train_path)\npickle.dump(X_data, open('X_data.pkl', 'wb'))\npickle.dump(y_data, open('y_data.pkl', 'wb'))\n\ntest_path = os.path.join(dir_path, 'Test_Full')\nX_test, y_test = get_data(test_path)\n\npickle.dump(X_test, open('X_test.pkl', 'wb'))\npickle.dump(y_test, open('y_test.pkl', 'wb'))","sub_path":"Desktop/Test_Classifcation/dump_data.py","file_name":"dump_data.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"207056176","text":"#!/usr/bin/env python3\n\nimport sys, os\nfrom bs4 import BeautifulSoup\nimport urllib.request\nimport gzip\n\n__version__ = '0.0.1'\n\nkickass_url = \"http://kickass.to/usearch/category%3Amovies%20seeds%3A5000/0/?field=time_add&sorder=desc\"\nn_pages = 3\n\ndef dl_torrent(url,filename):\n with urllib.request.urlopen(url) as response, open(filename, 'wb') as outf:\n outf.write(gzip.decompress(response.read()))\n outf.close()\n return True\n \npage=0\nfor page in range(0, n_pages):\n kickass_url = str(kickass_url).replace(\"/\" + str(page) + \"/?field=\", \"/\" + str(page + 1) + \"/?field=\")\n print(\"page #\" + str(page+1))\n data = urllib.request.urlopen(kickass_url).read()\n data = str(gzip.decompress(data),'utf-8')\n soup = BeautifulSoup(data)\n soup = soup.find(\"table\", {\"class\": \"data\"})\n \n for elem in soup.find_all(\"tr\"):\n try:\n #print(elem)\n link = elem.find_all(\"a\", {\"class\", \"idownload\"})[1].get('href')\n magnet = elem.find(\"a\", {\"class\", \"imagnet\"}).get('href')\n name = elem.find(\"a\", {\"class\", \"cellMainLink\"}).get_text()\n \n print(str(name) + \" >>> \" + str(link))\n dl_torrent(link, name + \".torrent\")\n except AttributeError as e:\n pass\n except Exception as e:\n print(e)\n","sub_path":"kickassfetch.py","file_name":"kickassfetch.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"12128253","text":"# Example taken from Gries et al. 2013. Practical Programming: An Introduction\n# to Computer Science Using Python 3\n\nimport unittest\nimport tools\n\nclass TestRunningSum(unittest.TestCase):\n '''Tests for running_sum.'''\n\n def test_running_sum_empty(self):\n '''Test an empty list.'''\n inputted = []\n tools.running_sum(inputted)\n output_expected = []\n self.assertEqual(output_expected, inputted, \"The list is empty.\")\n\n def test_running_sum_one(self):\n '''Test a one-item list.'''\n inputted = [2]\n tools.running_sum(inputted)\n output_expected = [2]\n self.assertEqual(output_expected, inputted, \"The list contains one item.\")\n\n def test_running_sum_two(self):\n '''Test a two-item list.'''\n inputted = [2, 5]\n tools.running_sum(inputted)\n output_expected = [2, 7]\n self.assertEqual(output_expected, inputted, \"The list contains two items.\")\n\n def test_running_sum_multi_neg(self):\n '''Test a list of negative values.'''\n inputted = [-1, -5, -3, -4]\n tools.running_sum(inputted)\n output_expected = [-1, -6, -9, -13]\n self.assertEqual(output_expected, inputted, \"The list contains only negative values.\")\n\n def test_running_sum_multi_zeros(self):\n '''Test a list of zeros.'''\n inputted = [0, 0, 0, 0]\n tools.running_sum(inputted)\n output_expected = [0, 0, 0, 0]\n self.assertEqual(output_expected, inputted, \"Not working with zeros.\")\n\n def test_running_sum_multi_pos(self):\n '''Test a list of positive values.'''\n inputted = [4, 2, 3, 6]\n tools.running_sum(inputted)\n output_expected = [4, 6, 9, 15]\n self.assertEqual(output_expected, inputted, \"Not working with positive values.\")\n\n def test_running_sum_multi_mix(self):\n '''Test a list of mixed values.'''\n inputted = [4, 0, 2, -5]\n tools.running_sum(inputted)\n output_expected = [4, 4, 6, 1]\n self.assertEqual(output_expected, inputted, \"Not working with mixed values.\")\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"wk7/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"16248109","text":"import tensorflow.keras\r\nfrom PIL import Image, ImageOps\r\nimport numpy as np\r\nimport argparse\r\nimport cv2 \r\nimport urllib\r\nimport paho.mqtt.client as paho \t\t #mqtt library\r\nimport os\r\nimport datetime\r\nimport json\r\nimport time\r\n\r\ndef pub():\r\n ACCESS_TOKEN='eWrIZt4BThzJrLTVvzu8' #Token of your device\r\n broker=\"demo.thingsboard.io\" \t\t\t #host name\r\n port=1883 \t\t\t\t\t #data listening port\r\n def on_publish(client,userdata,result): #create function for callback\r\n print(\"data published to thingsboard \\n\")\r\n pass\r\n client1= paho.Client(\"control1\") #create client object\r\n client1.on_publish = on_publish #assign function to callback\r\n client1.username_pw_set(ACCESS_TOKEN) #access token from thingsboard device\r\n client1.connect(broker,port,keepalive=60) #establish connection\r\n np.set_printoptions(suppress=True)\r\n if label_id==0:\r\n payload=\"{\"\r\n payload+=\"\\\"sign\\\":0\"; \r\n payload+=\"}\"\r\n ret= client1.publish(\"v1/devices/me/telemetry\",payload) #topic-v1/devices/me/telemetry\r\n print(payload);\r\n elif label_id==1:\r\n payload=\"{\"\r\n payload+=\"\\\"sign\\\":1\"; \r\n payload+=\"}\"\r\n ret= client1.publish(\"v1/devices/me/telemetry\",payload) #topic-v1/devices/me/telemetry\r\n print(payload);\r\n elif label_id==2:\r\n payload=\"{\"\r\n payload+=\"\\\"sign\\\":2\"; \r\n payload+=\"}\"\r\n ret= client1.publish(\"v1/devices/me/telemetry\",payload) #topic-v1/devices/me/telemetry\r\n print(payload);\r\n elif label_id==3:\r\n payload=\"{\"\r\n payload+=\"\\\"sign\\\":3\"; \r\n payload+=\"}\"\r\n ret= client1.publish(\"v1/devices/me/telemetry\",payload) #topic-v1/devices/me/telemetry\r\n print(payload);\r\n elif label_id==5:\r\n payload=\"{\"\r\n payload+=\"\\\"sign\\\":5\"; \r\n payload+=\"}\"\r\n ret= client1.publish(\"v1/devices/me/telemetry\",payload) #topic-v1/devices/me/telemetry\r\n print(payload);\r\n elif label_id==6:\r\n payload=\"{\"\r\n payload+=\"\\\"sign\\\":6\"; \r\n payload+=\"}\"\r\n ret= client1.publish(\"v1/devices/me/telemetry\",payload) #topic-v1/devices/me/telemetry\r\n print(payload);\r\n elif label_id==7:\r\n payload=\"{\"\r\n payload+=\"\\\"sign\\\":7\"; \r\n payload+=\"}\"\r\n ret= client1.publish(\"v1/devices/me/telemetry\",payload) #topic-v1/devices/me/telemetry\r\n print(payload);\r\n elif label_id==8:\r\n payload=\"{\"\r\n payload+=\"\\\"sign\\\":8\"; \r\n payload+=\"}\"\r\n ret= client1.publish(\"v1/devices/me/telemetry\",payload) #topic-v1/devices/me/telemetry\r\n print(payload);\r\n elif label_id==9:\r\n payload=\"{\"\r\n payload+=\"\\\"sign\\\":9\"; \r\n payload+=\"}\"\r\n ret= client1.publish(\"v1/devices/me/telemetry\",payload) #topic-v1/devices/me/telemetry\r\n print(payload);\r\n \r\n time.sleep(1)\r\n \r\ndef load_labels(path):\r\n with open(path, 'r') as f:\r\n return {i: line.strip() for i, line in enumerate(f.readlines())}\r\nparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\r\n# Load the model\r\nmodel = tensorflow.keras.models.load_model('keras_model.h5')\r\nparser.add_argument('--labels', help='File path of labels file.', required=True)\r\nargs = parser.parse_args()\r\nlabels = load_labels(args.labels)\r\nstart = datetime.datetime.now()\r\nwhile(1): \r\n \r\n # reads frames from a camera \r\n url=\"http://10.56.160.105:8080/shot.jpg\"\r\n \r\n data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)\r\n \r\n imgPath=urllib.request.urlopen(url)\r\n imgNp=np.array(bytearray(imgPath.read()),dtype=np.uint8)\r\n image=cv2.imdecode(imgNp,-1)\r\n \r\n size = (224, 224)\r\n image = cv2.resize(image,size)\r\n \r\n image_array = np.asarray(image)\r\n \r\n cv2.imshow('Edges',image) \r\n normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1\r\n data[0] = normalized_image_array\r\n\r\n# run the inference\r\n arr= model.predict(data)\r\n # Get the maximum element from a Numpy array\r\n a=arr[0,:]\r\n b=a.tolist()\r\n label_id=b.index(max(b))\r\n cv2.putText(image, labels[label_id]+str(max(b)), (10, 25),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2) \r\n cv2.imshow('Edges',image) \r\n stop=datetime.datetime.now()\r\n result = (stop - start).total_seconds()\r\n result=int(result)\r\n print(result)\r\n if result%2==0:\r\n pub()\r\n \r\n if cv2.waitKey(5) & 0xFF==ord('q'):\r\n break \r\ncv2.destroyAllWindows()\r\n","sub_path":"traffic1.py","file_name":"traffic1.py","file_ext":"py","file_size_in_byte":4564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"163551626","text":"import torchtext\nfrom torchtext.data import Example, Field, Dataset, get_tokenizer\n\nimport const\nimport nltk\nfrom app.utils import identity\nfrom app.dict.sentiwordnet import SentiWordNet\nfrom app.dict.sentiment import Sentiment\nfrom tqdm import tqdm\nfrom concurrent.futures import ProcessPoolExecutor\n\n\nclass InternalDataset:\n def __init__(self, text_field: Field, label_field: Field, score_field: Field, lexicon, dataset='sst-2'):\n fields = [('text', text_field), ('score', score_field), ('label', label_field)]\n\n # tokenize later\n text_tokenizer = identity\n text_tokenizer, text_field.tokenize = text_field.tokenize, text_tokenizer\n tokenizer = get_tokenizer(score_field.tokenize)\n\n if lexicon == 'wordnet':\n net = SentiWordNet(default=-1, exclude_stop_words=False)\n else:\n net = Sentiment(lexicon, default=-1)\n\n def build_score(text):\n texts = tokenizer(text)\n return [net[tok] for tok in texts]\n\n def build_tag_score(text):\n texts = tokenizer(text)\n tags = nltk.pos_tag(texts)\n return [net.get_score(tok, tag) for tok, tag in tags]\n\n score_field.tokenize = identity\n\n if 'sst' in dataset:\n phases = torchtext.datasets.SST.splits(text_field=text_field, label_field=label_field,\n fine_grained=True, root=const.data_path)\n if dataset == 'sst-2':\n mapping = {'very positive': 1, 'positive': 1, 'negative': 0, 'very negative': 0}\n else:\n mapping = {'very positive': 0, 'positive': 1, 'negative': 2, 'very negative': 3, 'neutral': 4}\n elif dataset == 'imdb':\n phases = torchtext.datasets.IMDB.splits(text_field=text_field, label_field=label_field,\n root=const.data_path)\n mapping = {\n 'pos': 1,\n 'neg': 0\n }\n else:\n raise LookupError\n\n self.n_class = len(set(mapping.values()))\n label_field.preprocessing = None\n text_field.tokenize = text_tokenizer\n score_field.tokenize = build_tag_score if lexicon == 'wordnet' else build_score\n\n def process(sample):\n return Example.fromlist([sample.text, sample.text, mapping[sample.label]], fields)\n\n pool = ProcessPoolExecutor()\n self.dataset = []\n for i, phase in enumerate(phases):\n examples = []\n rets = []\n for example in phase.examples:\n if example.label in mapping.keys():\n ret = process(example)\n examples.append(ret)\n # for ret in tqdm(rets):\n # ex = ret.result()\n # examples.append(ex)\n self.dataset.append(Dataset(examples, fields))\n\n def splits(self):\n return tuple(self.dataset)\n\n\nif __name__ == '__main__':\n TEXT = Field(batch_first=True, tokenize='spacy', fix_length=128, init_token='<cls>', eos_token='<eos>')\n LABEL = Field(sequential=False, use_vocab=False)\n SCORE = Field(tokenize='spacy', fix_length=128, init_token=-1, eos_token=-1, pad_token=-1, use_vocab=False,\n batch_first=True)\n\n imdb = InternalDataset(TEXT, LABEL, SCORE, 'wordnet', dataset='imdb')\n train, test = imdb.splits()\n","sub_path":"internal.py","file_name":"internal.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"14553614","text":"#!/usr/bin/env python\n\n\"\"\"\n==================\nScript Description\n==================\nThis script has been largely inspire by Adrian Rosebrock from pyimagesearch. He developed the loops used to convert urls, while I adapted the script to work through a directory of txt files rather than just one text file and append the images from all the files in a directory into one data folder. The script was also ammended to have command line functionality with a main function and argparse arguments, making it robust enough to work with any image directory of urls. \n\nWhat does this script do?\nThe script takes a directory of txt files containing urls and runs them through a process whereby the script requests the url link, saves the image attached to the url as a jpg file, and writes this into a variable named f. \n\nA new loop then goes through all the downloaded images files and looks to see whether this image can be used by openCV. It asks the file to open using cv2.imread and if nothing is returned, then this file is deleted from the output folder. \n\nThe output of the script is then a folder full of jpg images ready to be pre-processed\n\nCredit to Adrian Rosebrock(source: https://www.pyimagesearch.com/2017/12/04/how-to-create-a-deep-learning-dataset-using-google-images/?fbclid=IwAR3_R3XzW6LlnPtc-nHxx-9UMEXQOvJsQaHEtuSsrsx-WKSp3toZ25O6sug#download-the-code) \n\nNB: work from the base directory and use src/Google_image ... to pull the script\n\n\"\"\"\n\n\"\"\"\n============\nDependencies \n============\n\"\"\"\n# import the necessary packages\nfrom imutils import paths\nimport argparse\nimport requests\nimport cv2\nimport os\n\n\"\"\"\n==========================\nCommand line functionality\n==========================\n\"\"\"\n# construct the argument parse and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-d\", \"--directory\", \n required=False,\n default = \"data_collection/URL_txt_files/Other_URLs/\",\n help=\"path to directory containing txt files with the image URLs\")\nap.add_argument(\"-o\", \"--output\", \n required=False,\n default = \"data/Scraped_data/Other_Streetart\",\n help=\"path to output directory of images\")\nargs = vars(ap.parse_args())\n\n\n\"\"\"\n=============\nMain Function\n=============\n\n\"\"\"\ndef main():\n \n \"\"\"\n ------------------------------\n Extract files in the directory\n ------------------------------\n \"\"\"\n \n # Connect the directory to the argparse directory \n directory = args[\"directory\"]\n \n #Create an empty list for filenames \n files = []\n \n #for each file in the directory \n for filename in os.listdir(directory):\n # connect the filename to the variable f\n f = os.path.join(directory, filename)\n #if this filename is a file \n if os.path.isfile(f):\n #Then add it to the files list\n files.append(f)\n \n \n \"\"\"\n ------------------------------------------------------\n Get the urls from each file and save to a list of rows\n ------------------------------------------------------\n \"\"\"\n \n rows = []\n for file in files: \n urls = open(file).read().strip().split(\"\\n\")\n \n for url in urls:\n rows.append(url)\n \n total = 0\n\n \"\"\"\n -------------------------\n Make the urls into images\n -------------------------\n \"\"\"\n # loop over each url in the txt file \n for url in rows:\n try:\n # try to download the image\n r = requests.get(url, timeout=60)\n # save the image as a jpg file \n p = os.path.sep.join([args[\"output\"], \"{}.jpg\".format(\n str(total).zfill(8))])\n f = open(p, \"wb\")\n f.write(r.content)\n f.close()\n \n # update the counter\n print(\"[INFO] downloaded: {}\".format(p))\n total += 1\n \n # Informs the reader if the files are problematic by saying that it'll skip this url\n # Some errors are expected because it's a messy dataset we're working with \n except:\n print(\"[INFO] error downloading {}...skipping\".format(p))\n \n \n \"\"\"\n -------------------------\n Delete problematic images\n -------------------------\n \"\"\"\n # loop over the image paths we've just downloaded\n for imagePath in paths.list_images(args[\"output\"]):\n # initialize if the image should be deleted or not\n delete = False\n # try to load the image\n try:\n image = cv2.imread(imagePath)\n # if the image is `None` then we could not properly load it from disk, so delete it\n if image is None:\n delete = True\n # if OpenCV cannot load the image then the image is likely corrupt so we should delete it\n except:\n print(\"Except\")\n delete = True\n # check to see if the image should be deleted\n if delete:\n print(\"[INFO] deleting {}\".format(imagePath))\n os.remove(imagePath)\n\n \"\"\"\n --------------------\n Finish up the script\n --------------------\n \"\"\"\n output = args[\"output\"]\n print(f\"Your images have been converted and saved in {output}.\") \n \n# Close the main function \nif __name__==\"__main__\":\n main() \n","sub_path":"src/Google_Image_Converter.py","file_name":"Google_Image_Converter.py","file_ext":"py","file_size_in_byte":5355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"548393729","text":"import datetime\n\ndef solution(a, b):\n week =[\"SUN\", \"MON\", \"TUE\", \"WED\", \"THU\", \"FRI\", \"SAT\"]\n answer = week[(datetime.datetime(2016, a, b).weekday() +1) %7]\n\n return answer\n\na = 1\nb = 3\n\nprint(solution(a,b))\n#print((datetime.datetime(2016, 1, 3).weekday()+1)%7)","sub_path":"2016년.py","file_name":"2016년.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"371960188","text":"import math\nn = int(input())\nd = dict()\na = list(map(int, input().split()))\nmod = 10**9+7\ndaburi_l, daburi_r, hasikko_len = 0, 0, 0\nfor i, m in enumerate(a):\n if m in d:\n daburi_l, daburi_r = d[m], i\n hasikko_len = daburi_l + (n-daburi_r)\n break\n else:\n d[m] = i\n\n#total = math.factorial(n+1)%(10**9+7)\n\ndef pmod(x, y):\n n = 1\n while y>0:\n if y%2==1:\n n = n*x%mod\n y>>=1\n x = x*x%mod\n return n\n\nfac_table = [1,1]\nap = fac_table.append\ntotal = 1\nfor i in range(2, n+2):\n total = (total * i) % (10**9+7)\n ap(total)\n\ndp = [None]*(n+1)\nprint(n)\nfor i in range(2, n+2):\n r = fac_table[i]\n daburi = 0 if i > hasikko_len+1 else (fac_table[hasikko_len]*pmod(fac_table[i-1]*fac_table[hasikko_len-i+1], mod-2)) % mod\n m = min(i, n+1-i)\n if dp[m] is None:\n dp[m] = pmod(r*fac_table[n+1-i], mod-2)\n comb = (fac_table[n+1] * dp[m]) % mod\n #print(fac_table[n+1], r, fac_table[n+1-i], comb, daburi)\n print((comb-daburi)% mod)","sub_path":"work/atcoder/arc/arc077/D/answers/397092_tkb.py","file_name":"397092_tkb.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"406925806","text":"#logloss.py\n#Evaluation Function for testing different models\n#for the Biological Response kaggle project.\n\n#Last Updated: 3/30/15\n\nimport scipy as sp\ndef llfun(act,pred):\n\tepsilon = 1e-15\n\tpred = sp.maximum(epsilon, pred)\n\tpred = sp.minimum(1-epsilon, pred)\n\tll = sum(act*sp.log(pred) + sp.subtract(1,act)*sp.log(sp.subtract(1,pred)))\n\tll = ll* -1.0/len(act)\n\treturn ll","sub_path":"logloss.py","file_name":"logloss.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"38905138","text":"import subprocess\nfrom subprocess import PIPE\ndef cprogram(code):\n f=open(\"new.c\",'w')\n f.write(code)\n f.close()\n var1=\"gcc\"\n var2=\"new.c\"\n var3=\"-o\"\n var4=\"out\"\n subprocess.run([var1,var2,var3,var4])\n x=subprocess.run(\"./out\",stdout=PIPE)\n return x.stdout\n\ndef Cpp_program(code):\n f=open(\"try.cpp\",'w')\n f.write(code)\n f.close()\n var1=\"g++\"\n var2=\"try.cpp\"\n var3=\"-o\"\n var4=\"out\"\n subprocess.run([var1,var2,var3,var4])\n x=subprocess.run(\"./out\",stdout=PIPE)\n return x.stdout\n\n\ndef Java_program(code):\n f=open(\"Javacode.java\",'w')\n f.write(code)\n f.close()\n var1=\"javac\"\n var2=\"javacode.java\"\n var3=\"java\"\n var4= input(\"Main class name:-\")\n subprocess.run([var1,var2])\n subprocess.run([var3,var4])\n\ndef python_program(code):\n f=open(\"testpython.py\",'w')\n f.write(code)\n f.close()\n var1=\"python\"\n var2=\"testpython.py\"\n x=subprocess.run([var1,var2],stdout=PIPE)\n return x.stdout\n\n\n","sub_path":"DB/Cprogram.py","file_name":"Cprogram.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"223365233","text":"import sys\nimport random\n\n#GIATI NA TA KANEIS ME CLASS OTAN MPOREIS NA FTIAKSEI ENA CLASS MONO\n#STO OPOIO KATHE XRISTIS EINAI ENA OBJECT(INSTANCE). ME AUTO TON TROPO\n#GLITWNEIS XWRO KAI XRONO EKTELESIS STO PROGRAMMA KAI APOFEUGIS NA EXEIS\n#100000 FUNCTIONS ME SETTER KAI GETTER. APIRA PIO GRIGOROS TROPOS\n\n\n\n#TODO : ENWPOIIHSH OLWN TWN KATIGORIWN SE MIA KAI ENWSI OLWN AUTWN SE ENA MONO CLASS\n#TO OPOIO CLASS THA FTIAXNEI ENA OBJECT GIA KATHE XRISTI KAI OXI POLLA\n\n\n\n\n#TODO : 27/FEB/2016:\n#NA SPASW TA DICTIONARIES SE KSEXWRISTA FILES WSTE NA MPOROUME NA EPIREASOUME TO KATHENA KSEXWRISTA\n#KAI NA MHN TREXOUME GIA TO KATHENA MESA SE ENAN MONO KWDIKA.\n\n\nwatchable_sports = \t{\n\t'basketball_watch' : None,\n\t'football_watch' : None,\n\t'hockey_watch' : None,\n\t'baseball_watch' : None,\n\t'volley_watch' : None,\n\t'ragby_watch' : None,\n\t'tennis_watch' : None,\n\t'golf_watch': None,\n\t'motoracing_watch' : None,\n\t'autoracing_watch' : None,\n\t'ping_pong_watch' : None,\n\t'darts_watch' : None,\n\t'snooker_watch' : None\n\t\t\t\t\t}\n\n\nplayable_sports = \t{\n\t'gymnastics' : None,\n\t'basketball' : None,\n\t'football' : None,\n\t'ragby' : None,\n\t'air_sports' : None,\n\t'bow_arrow_guns' : None,\n\t'extreme' : None,\n\t'bicycle' : None,\n\t'baseball' : None,\n\t'water_sports' : None,\n\t'canoe_cayak' : None,\n\t'martial_arts' : None,\n\t'paintball' : None,\n\t'gymnastics_equipment' : None,\n\t'handball' : None,\n\t'hockey' : None,\n\t'kerling' : None,\n\t'bowling' : None,\n\t'snooker' : None,\n\t'snow_sports' : None,\n\t'freerun_parkour' : None,\n\t'skate' : None,\n\t'scubadive_freedive' : None,\n\t'auto_moto' : None,\n\t'board_games' : None\n\t\t\t\t\t}\n\n\n\nmovies = {\n\t'action' : None,\n\t'adventure' : None,\n\t'comedy' : None,\n\t'crime' : None,\n\t'fantasy' : None,\n\t'historical' : None,\n\t'historical_fiction' : None,\n\t'horror' : None,\n\t'magical_realism' : None,\n\t'mystery' : None,\n\t'paranoid' : None,\n\t'philosophical' : None,\n\t'political' : None,\n\t'romance' : None,\n\t'saga' : None,\n\t'satire' : None,\n\t'science_fiction' : None,\n\t'slice_of_Life' : None,\n\t'speculative' : None,\n\t'thriller' : None,\n\t'urban' : None,\n\t'western' : None\n\t\t\t}\n\n\nvideo_games =\t{\n\t'action' : None,\n\t'action-adventure' : None,\n\t'adventure' : None,\n\t'role_playing' : None,\n\t'simulation' : None,\n\t'strategy' : None,\n\t'sports' : None,\n\t'mmo' : None,\n\t'music_games' : None,\n\t'party_games' : None,\n\t'casual_games' : None,\n\t'programming_games' : None,\n\t'logic_games' : None,\n\t'trivia_games' : None,\n\t'idle_gaming' : None\n\t\t\t\t}\n\n\nindoor = \t{\n\t'watch_sport' : None,\n\t'gymnastics' : None,\n\t'watch_movies' : None,\n\t'video_games' : None,\n\t'do_homework' : None,\n\t'read_book' : None,\n\t'listen_music' : None,\n\t'internet'\t: None,\n\t'yoga_chill' : None,\n\t'take_nap' : None,\n\t'clean_house' : None,\n\t'mop_floor' : None,\n\t'clean_dishes' : None,\n\t'garbage_out' : None,\n\t'make_your_bed' : None,\n\t'cook' : None,\n\t'make_coctail' : None,\n\t'have_snack' : None,\n\t'reorganize_a_room' : None,\n\t'dance_off!!' : None,\n\t'think_deeply' : None,\n\t'schedule_your_day' : None,\n\t'phonecall_family' : None,\n\t'phonecall_friends' : None,\n\t'take_shower_hot' : None,\n\t'take_shower_cold' : None,\n\t'be_creative' : None,\n\t'draw' : None,\n\t'cook' : None,\n\t'daydream' : None,\n\t'invite_your_friends' : None,\n\t'play_some_instrument' : None,\n\t'get_ready_to_go_out' : None\n\t\t\t}\n\n\ngeneral =\t{\n\t'sports_and_fitness' : None,\n\t'movies' : None,\n\t'video_games' : None,\n\t'studies' : None,\n\t'books' : None,\n\t'music' : None,\n\t'internet' : None,\n\t'tv' : None,\n\t'computers' : None,\n\t'animals' : None,\n\t'arts' : None,\n\t'cars/moto' : None,\n\t'anime/comics' : None,\n\t'nature' : None,\n\t'nightlife' : None,\n\t'photography' : None,\n\t'travel' : None,\n\t'social_media' : None,\n\t'house_activities' : None,\n 'outdoors' : None,\n 'electronics' : None,\n 'alcohol' : None,\n 'history/museum' : None,\n 'cooking' : None,\n 'drawing' : None,\n 'instrument_lover' : None,\n 'pet' : None,\n \n\n\n\n\n\t\t\t}\n\ninterests = []\n\n\ngeneral['drawing'] = True\ngeneral['instrument_lover'] = True\ngeneral['pet'] = True\n\n\n\nfor i in general:\n\tif general[i] == True:\n\t\tinterests.append(i)\n\nrandom_range = len(interests)\n\ntest = []\nfor i in range(0,10000):\n\trandom_number = random.randrange(0,random_range)\n\tprint(interests[random_number])\n\n\n","sub_path":"basic_stats.py","file_name":"basic_stats.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"622446319","text":"import random\ndef aicb(n=11,p=9,k=27):\n c=[]\n for u in range(n):\n d=random.randint(p,k)\n c.append(d)\n return c\nx=aicb()\na=10\nb=20\ny=[]\nfor i in x:\n if i>a and i<b:\n y.append(i)\nprint(y)","sub_path":"basic/hamar284.py","file_name":"hamar284.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"279195993","text":"'''\n This file will be the entry point of the application.\n The input check will be performed and then if everything is\n ok the internal execution will be initiated.\n'''\n\nimport os, sys, getopt, glob, time\nfrom core.hashtagAppExecution import Hashtager\n\n# Check if the path exist\ndef verify_path(folder_path):\n\n if not os.path.exists(folder_path):\n raise Exception('The path: {} does not exist'.format(folder_path))\n \n if not glob.glob(os.path.join(folder_path, '*.txt')) :\n raise Exception('The given directory has no text files')\n \n return folder_path\n \n\n# Check the structure of the input\ndef input_check(argv):\n \n try:\n opts, _ = getopt.getopt(argv,\"d:\")\n except getopt.GetoptError:\n print(\"hashtagApp.py -d <folder_path>\")\n sys.exit(2)\n \n _, folder_path = opts[0]\n\n return folder_path\n\n# Application entry point\nif __name__ == \"__main__\":\n\n folder_path = input_check(sys.argv[1:])\n folder_path = verify_path(folder_path)\n\n hashtager = Hashtager()\n hashtager.find_hastags(folder_path)","sub_path":"hashtagApp.py","file_name":"hashtagApp.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"272351536","text":"# Copyright 2021 IBM Corporation\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. \nfrom re import sub\nimport requests\n\n\nclass GithubClient:\n\n DOMAIN = 'github.com'\n ENTERPRISE_DOMAIN = 'github.ibm.com'\n RAW_DOMAIN = 'raw.githubusercontent.com'\n RAW_ENTERPRISE_DOMAIN = 'raw.github.ibm.com'\n\n def __init__(self, api_token=None):\n self.headers = GithubClient.__create_headers(api_token)\n\n @staticmethod\n def __create_headers(api_token):\n if api_token:\n headers = {'Authorization': 'token %s' % api_token}\n else:\n headers = {}\n return headers\n\n @staticmethod\n def __parse_file_name(url):\n split_url = url.split('/')\n file_name = split_url[-1]\n return file_name\n\n def __write_response_to_disk(self, response, url):\n if response.status_code != 200:\n raise Exception('Status Code: %d' % response.status_code)\n\n file_name = self.__parse_file_name(url)\n with open(file_name, 'wb') as fd:\n fd.write(response.content)\n return file_name\n\n def __is_enterprise(self, url):\n no_protocol_url = sub(r'https?://', '', url)\n domain = no_protocol_url.split('/')[0]\n if domain == self.DOMAIN:\n return False\n return True\n\n # URLs must be formatted as https://{github.com|github.ibm.com}/path/to/file\n def __parse_github_url(self, url):\n no_blob_url = url.replace(r'/blob', '')\n if self.__is_enterprise(no_blob_url):\n download_url = no_blob_url.replace(self.ENTERPRISE_DOMAIN, self.RAW_ENTERPRISE_DOMAIN)\n else:\n download_url = no_blob_url.replace(self.DOMAIN, self.RAW_DOMAIN)\n return download_url\n\n def download_file(self, url):\n download_url = self.__parse_github_url(url)\n try:\n response = requests.get(download_url, headers=self.headers)\n file_name = self.__write_response_to_disk(response, download_url)\n return file_name\n except Exception as err:\n raise Exception(\"Unable to download %s:\\n%s\" % (url, err))\n","sub_path":"component-samples/jupyter/src/github_client.py","file_name":"github_client.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"467398540","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Django migration to provide initial schema data for the\nmytardis_hsm app.\"\"\"\n\nfrom django.conf import settings\nfrom django.db import migrations\nfrom mytardis_hsm.mytardis_hsm import (\n HSM_DATAFILE_NAMESPACE,\n HSM_DATASET_NAMESPACE,\n df_online\n)\nfrom tardis.tardis_portal.models import (Schema, ParameterName, Dataset,\n DataFile, DatafileParameter,\n DatasetParameterSet,\n DatafileParameterSet)\n\n\ndef forward_func(apps, schema_editor):\n \"\"\"Create HSM Schema and online ParameterName\"\"\"\n db_alias = schema_editor.connection.alias\n df_schema = Schema.objects\\\n .using(db_alias)\\\n .create(namespace=HSM_DATAFILE_NAMESPACE,\n name=\"Datafile HSM Schema\",\n hidden=True,\n type=3,\n immutable=True)\n\n ds_schema = Schema.objects\\\n .using(db_alias)\\\n .create(namespace=HSM_DATASET_NAMESPACE,\n name=\"Dataset HSM Schema\",\n hidden=True,\n type=2,\n immutable=True)\n\n param_name = ParameterName.objects\\\n .using(db_alias)\\\n .create(\n name=\"online\",\n full_name=\"Is Online\",\n schema=df_schema)\n\n min_file_size = getattr(settings, \"HSM_MIN_FILE_SIZE\", 500)\n for ds in Dataset.objects.using(db_alias).all():\n DatasetParameterSet.objects\\\n .using(db_alias)\\\n .create(schema=ds_schema, dataset=ds)\n\n for df in DataFile.objects.using(db_alias).all():\n if df.verified:\n dfps = DatafileParameterSet.objects\\\n .using(db_alias)\\\n .create(schema=df_schema, datafile=df)\n\n dp = DatafileParameter.objects\\\n .using(db_alias)\\\n .create(parameterset=dfps, name=param_name)\n dp.string_value = str(df_online(df, min_file_size))\n dp.save()\n\n\ndef reverse_func(apps, schema_editor):\n \"\"\"Remove HSM Schema and online ParameterName\"\"\"\n db_alias = schema_editor.connection.alias\n df_schema = Schema.objects.using(db_alias)\\\n .get(namespace=HSM_DATAFILE_NAMESPACE)\n\n ds_schema = Schema.objects.using(db_alias)\\\n .get(namespace=HSM_DATASET_NAMESPACE)\n\n param_names = ParameterName.objects.using(db_alias)\\\n .filter(schema=df_schema)\n\n for pn in param_names:\n DatafileParameter.objects\\\n .using(db_alias)\\\n .filter(name=pn).delete()\n pn.delete()\n\n DatafileParameterSet.objects\\\n .using(db_alias)\\\n .filter(schema=df_schema).delete()\n DatasetParameterSet.objects\\\n .using(db_alias)\\\n .filter(schema=ds_schema).delete()\n\n df_schema.delete()\n ds_schema.delete()\n\n\nclass Migration(migrations.Migration):\n \"\"\"HSM Schema and online ParameterName migrations\"\"\"\n dependencies = [\n (\"tardis_portal\", \"0001_initial\"),\n ]\n\n operations = [\n migrations.RunPython(forward_func, reverse_func),\n ]\n","sub_path":"mytardis_hsm/migrations/0001_initial_data.py","file_name":"0001_initial_data.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"572818935","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nimport os\nimport shutil\nfrom modules.global_info import (FILTER_PLUGIN,\n CONFIG_PATH,\n CONFIG_BAK_PATH,\n PLUGINS_DIR_LIST)\nfrom filter_config_generator import Generator\nfrom modules.input.tcp_udp_plugin_manage import TcpUdpPluginManage\nblack_list = ['/', ':', '?', '\\\"', '<', '>', '|',\n ':', '?', '’', '“', '”', '《', '》']\n\n\nclass FilterPluginInfo(object):\n \"\"\"\n \"\"\"\n def __init__(self, rule_name=None, config=None, file_name=None, file_path=None):\n \"\"\"\n \"\"\"\n self.rule_name = rule_name\n self.config = config\n self.file_name = file_name\n self.file_path = file_path\n\n def json_format(self):\n \"\"\"\n \"\"\"\n if self.rule_name:\n result = {}\n result['ruleName'] = self.rule_name\n result['config'] = self.config\n result['fileName'] = self.file_name\n return result\n\n\nclass FilterManage(object):\n \"\"\"\n \"\"\"\n def __init__(self):\n \"\"\"\n \"\"\"\n pass\n\n def parse_filter_file(self, f_name, p_dir):\n \"\"\"\n \"\"\"\n split_name = f_name.split(\"_\")\n if split_name[0] == str(FILTER_PLUGIN):\n plugin_info = FilterPluginInfo()\n plugin_info.rule_name = f_name[2:-5]\n plugin_info.file_name = f_name\n path = os.path.join(p_dir, f_name)\n plugin_info.file_path = path\n with open(path, 'r') as f:\n plugin_info.config = f.read()\n\n return plugin_info\n\n def get_plugin_info(self, rule_name):\n \"\"\"\n \"\"\"\n for p_dir in PLUGINS_DIR_LIST:\n for file_name in os.listdir(p_dir):\n plugin_info = self.parse_filter_file(file_name, p_dir)\n\n if plugin_info and plugin_info.rule_name == rule_name:\n return plugin_info\n\n def exists(self, rule_name):\n \"\"\"\n \"\"\"\n return True if self.get_plugin_info(rule_name) else False\n\n def add(self, json_args):\n \"\"\"\n \"\"\"\n if 'ruleName' not in json_args:\n raise Exception(\"规则名为空\")\n rule_name = json_args['ruleName']\n if not rule_name:\n raise Exception(\"规则名为空\")\n\n for invalid in black_list:\n if invalid.decode('utf8') in rule_name:\n raise Exception(\"不合法的规则名,请重新输入\")\n\n if self.exists(rule_name.encode('utf8')):\n raise Exception(\"存在同名过滤规则:%s\" % str(rule_name.encode('utf8')))\n\n # 每次新建先强制删除旧\n self.delete(rule_name)\n\n try:\n # 新建配置文件\n file_name = \"2_%s.conf\" % rule_name\n file_path = os.path.join(CONFIG_PATH, file_name)\n\n filte_config = Generator().generate_conf(json_args)\n with open(file_path, \"wb\") as f:\n f.write(filte_config.encode(\"utf-8\"))\n except Exception as ex:\n raise Exception(\"��建日志解析规则%s失败:%s\" % (rule_name.encode('utf8'), str(ex)))\n\n def update(self, rule_name, json_args):\n \"\"\"\n \"\"\"\n # 先强制删除旧\n self.delete(rule_name)\n\n # 再添加新的\n self.add(json_args)\n\n return json_args['ruleName']\n\n def list(self):\n \"\"\"\n \"\"\"\n results = []\n for p_dir in PLUGINS_DIR_LIST:\n for file_name in os.listdir(p_dir):\n plugin_info = self.parse_filter_file(file_name, p_dir)\n if plugin_info:\n res = plugin_info.json_format()\n ports = self.get_ports_by_rule(res['ruleName'])\n res['bindPorts'] = ports\n results.append(res)\n return results\n\n def get_ports_by_rule(self, rule_name):\n \"\"\"\n 根据规则名获取绑定的端口号\n \"\"\"\n ports = []\n all_input_infos = TcpUdpPluginManage().get_all()\n for info in all_input_infos:\n if 'ruleName' in info and info['ruleName'] == rule_name:\n ports.append(int(info['port']))\n return ports\n\n def get(self, rule_name):\n \"\"\"\n \"\"\"\n if not rule_name:\n raise Exception(\"规则名为空\")\n plugin_info = self.get_plugin_info(rule_name.encode('utf8'))\n if plugin_info:\n result = plugin_info.json_format()\n # 获取该规则绑定的端口\n ports = self.get_ports_by_rule(result['ruleName'])\n result['bindPorts'] = ports\n return result\n\n def delete(self, rule_name):\n \"\"\"\n \"\"\"\n if not self.exists(rule_name.encode('utf8')):\n return\n\n plugin_info = self.get_plugin_info(rule_name.encode('utf8'))\n os.remove(plugin_info.file_path)\n","sub_path":"docker/container_install_script/docker-container-installer/anyrobot/etl/etl_server/modules/filter/filter_manage.py","file_name":"filter_manage.py","file_ext":"py","file_size_in_byte":4981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"584371513","text":"import yaml\nimport logging\n\n\ndef parse_config(path=\"./config/config.yaml\"):\n \"\"\"\n parses yaml\n :param path: config path (default = ./config/config.yaml)\n :return: parsed config dict\n \"\"\"\n try:\n with open(path, 'r') as ymlfile:\n config = yaml.load(ymlfile)\n return config\n except Exception as e:\n logging.error(\"Error while parsing config.\\n{}\".format(e))","sub_path":"userauthentication-api/util/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"280483843","text":"# -*- coding: utf-8 -*-\n'''\nRSV:=(CLOSE-LLV(LOW,N))/(HHV(HIGH,N)-LLV(LOW,N))*100;\nBACKGROUNDSTYLE(1);\nK:SMA(RSV,M1,1);\nD:SMA(K,M2,1);\nJ:3*K-2*D;\n'''\n'''\n注:KDJ数据在LvyiWin中有KDJ_HLim和KDJ_LLim的限制,所以暂时不把true和cross的功能转移到模块中\n'''\nimport pandas as pd\n#import talib\nimport numpy as np\n\ndef taKDJ(data,N=9,M=3):\n hight = np.array(data[\"high\"])\n low = np.array(data[\"low\"])\n close = np.array(data[\"close\"])\n #matype: 0=SMA, 1=EMA, 2=WMA, 3=DEMA, 4=TEMA, 5=TRIMA, 6=KAMA, 7=MAMA, 8=T3 (Default=SMA)\n K, D = talib.STOCH(hight, low, close, fastk_period=N, slowk_matype=1, slowk_period=M, slowd_period=M,slowd_matype=1)\n J = 3 * K - 2 * D\n tadf=pd.DataFrame({'KDJ_K': K})\n tadf['KDJ_D']=D\n tadf['KDJ_J']=J\n return tadf\n\ndef taKDJ2(data,N=9,M=3):\n high = np.array(data[\"high\"])\n low = np.array(data[\"low\"])\n close = np.array(data[\"close\"])\n low_list = pd.rolling_min(low, N)\n #low_list.fillna(value=pd.expanding_min(low, inplace=True))\n high_list = pd.rolling_max(high, N)\n #high_list.fillna(value=pd.expanding_max(high), inplace=True)\n rsv = (close - low_list) / (high_list - low_list) * 100\n KDJ_K = pd.ewma(rsv, com=M-1)#a=1/(1+com),所以com=M-1\n KDJ_D = pd.ewma(KDJ_K, com=M-1)\n KDJ_J = 3 * KDJ_K - 2 * KDJ_D\n a=KDJ_K[-1]\n df1=pd.DataFrame({'KDJ_K':KDJ_K})\n df1['KDJ_D']=KDJ_D\n df1['KDJ_J']=KDJ_J\n return df1\n\n\n\ndef KDJ(data, N=9, M=3):\n #low_list = pd.rolling_min(data['low'], N)\n low_list = data['low'].rolling(N).min()\n #low_list.fillna(value=pd.expanding_min(data['low']), inplace=True)\n low_list.fillna(value=data['low'].rolling(N).min(), inplace=True)\n #high_list = pd.rolling_max(data['high'], N)\n high_list = data['high'].rolling(N).max()\n #high_list.fillna(value=pd.expanding_max(data['high']), inplace=True)\n high_list.fillna(value=data['high'].rolling(N).max(), inplace=True)\n rsv = (data['close'] - low_list) / (high_list - low_list) * 100\n #KDJ_K = pd.ewma(rsv, com=M-1)#a=1/(1+com),所以com=M-1\n KDJ_K = rsv.ewm(span=M, adjust=False).mean()\n #KDJ_D = pd.ewma(KDJ_K, com=M-1)\n KDJ_D = KDJ_K.ewm(span=M, adjust=False).mean()\n KDJ_J = 3 * KDJ_K - 2 * KDJ_D\n df1=pd.DataFrame({'KDJ_K':KDJ_K})\n df1['KDJ_D']=KDJ_D\n df1['KDJ_J']=KDJ_J\n #df1['rsv']=rsv\n #df1['Hn']=high_list\n #df1['Ln']=low_list\n return df1\n\ndef newKDJ(data,kdjdata,N=9,M=3):\n '''\n 计算单个KDJ的值\n 1: 获取股票T日收盘价X\n 2: 计算周期的未成熟随机值RSV(n)=(Ct-Ln)/(Hn-Ln)×100,\n 其中:C为当日收盘价,Ln为N日内最低价,Hn为N日内最高价,n为基期分别取5、9、19、36、45、60、73日。\n 3: 计算K值,当日K值=(1-a)×前一日K值+a×当日RSV\n 4: 计算D值,当日D值=(1-a)×前一日D值+a×当日K值。\n 若无前一日K值与D值,则可分别用50来代替,a为平滑因子,不过目前已经约定俗成,固定为1/3。\n 5: 计算J值,当日J值=3×当日K值-2×当日D值\n\n :return:\n '''\n closeT=data.iloc[-1].close\n Ln=float(min(data.iloc[-N:].low))\n Hn=float(max(data.iloc[-N:].high))\n if Hn==Ln:#防止出现Hn和Ln相等,导致分母为0的情况\n rsv=100\n else :\n rsv=((closeT-Ln)/(Hn-Ln))*1000\n lastK=kdjdata.iloc[-1].KDJ_K\n lastD=kdjdata.iloc[-1].KDJ_D\n a=1/float(M)\n '''\n if rsv==200:\n newK=lastK\n else:\n newK=(1-a)*lastK+a*rsv#不能用2/3和1/3来算,会变成int,结果变0\n '''\n newK = (1 - a) * lastK + a * rsv\n newD=(1-a)*lastD+a*newK\n newJ=3*newK-2*newD\n return [newK,newD,newJ]\n #kdjdata.loc[kdjrow] = [data.ix[datarow-1, 'start_time'], rsv,Ln, Hn, newK, newD, newJ]\n\nif __name__ == '__main__':\n N=9\n M=2\n KDJ_HLim=85\n KDJ_LLim=15\n df=pd.read_csv('test2.csv')\n #df_KDJ=KDJ(df,N,M)\n tadf=taKDJ2(df,N,M)\n '''\n df_KDJ=KDJ(df.iloc[0:20],N,M)\n df_KDJ['KDJ_True']=0\n df_KDJ.loc[(KDJ_HLim>df_KDJ['KDJ_K'])&(df_KDJ['KDJ_K']> df_KDJ['KDJ_D']), 'KDJ_True'] = 1\n df_KDJ.loc[(KDJ_LLim<df_KDJ['KDJ_K'])&(df_KDJ['KDJ_K']< df_KDJ['KDJ_D']), 'KDJ_True'] = -1\n import numpy\n for i in numpy.arange(21,344):\n kdj=newKDJ(df.iloc[0:i],df_KDJ,N,M)\n newk=kdj[0]\n newd=kdj[1]\n KDJ_True=0\n if KDJ_HLim>newk and newk>newd:KDJ_True=1\n elif KDJ_LLim<newk and newk<newd:KDJ_True=-1\n kdj.append(KDJ_True)\n df_KDJ.loc[i-1]=kdj\n '''\n #df_KDJ.to_csv('KDJ1.csv')\n tadf.to_csv('taKDJ2.csv')","sub_path":"KDJ.py","file_name":"KDJ.py","file_ext":"py","file_size_in_byte":4543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"1783619","text":"import os\nimport numpy as np\nimport tensorflow as tf\nimport input_data\nimport model\n\n\nN_CLASSES = 2\nIMG_W = 208\nIMG_H = 208\nBATCH_SIZE = 16\nCAPACITY = 2000 # 队列中元素个数\nMAX_STEP = 5000\nlearning_rate = 0.0001 # 小于0.001\n\n#获取批次batch\ntrain_dir = 'D:/PychamProjects/Cats_Dogs/data/train/' # 训练图片文件夹\nlogs_train_dir = 'D:/PychamProjects/Cats_Dogs/logs/train' # 保存训练结果文件夹\n\ntrain, train_label = input_data.get_files(train_dir)\n\ntrain_batch, train_label_batch = input_data.get_batch(train,\n train_label,\n IMG_W,\n IMG_H,\n BATCH_SIZE,\n CAPACITY)\n#操作定义\ntrain_logits = model.inference(train_batch, BATCH_SIZE, N_CLASSES)\ntrain_loss = model.losses(train_logits, train_label_batch)\ntrain_op = model.training(train_loss, learning_rate)\ntrain_acc = model.evalution(train_logits, train_label_batch)\n\nsummary_op = tf.summary.merge_all()\nsess = tf.Session()\n#writer:写Log文件\ntrain_writer = tf.summary.FileWriter(logs_train_dir, sess.graph)\n#产生一个saver来存储训练好的模型\nsaver = tf.train.Saver()\n\nsess.run(tf.global_variables_initializer())\n#队列监控\ncoord = tf.train.Coordinator()\nthreads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n\n\n# 开始训练\ntry:\n # 执行MAX_STEP步的训练,一步一个batch\n for step in np.arange(MAX_STEP):\n if coord.should_stop():\n break\n _, tra_loss, tra_acc = sess.run([train_op, train_loss, train_acc])\n\n if step % 50 == 0:\n print('Step %d, train loss = %.2f, train accuracy = %.2f%%' % (step, tra_loss, tra_acc))\n summary_str = sess.run(summary_op)\n train_writer.add_summary(summary_str, step)\n\n if step % 2000 == 0 or (step + 1) == MAX_STEP:\n checkpoint_path = os.path.join(logs_train_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step=step)\n\nexcept tf.errors.OutOfRangeError:\n print('Done training -- epoch limit reached')\nfinally:\n coord.request_stop()\n\ncoord.join(threads)\nsess.close()","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"332634650","text":"# image preprocessing\nRESIZE = (256, 256)\nCROP = 224\n\n# database\nDATA_FOLDER = \"C:/Users/chung/Documents/04-Insight/insight/data\"\nBATCH = 100\n\n# annoy index\nANNOY_PATH = 'NextPick/annoy_idx.annoy'\nANNOY_METRIC = 'angular'\nANNOY_TREE = 20\n\n# ResNet18 Feature Embeddings\nRESNET18_FEAT = 512\n\n# places365\nNUMCLASS = 365\n\n# upload image\nALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}\n\n# top_n images\nTOP_N = 40\n\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"56758874","text":"\"\"\"\nNur ein Programm um zu testen wie Springen mit Gravitation funktioniert.\nPython 3.2.5\nPygame 1.9.2\n\"\"\"\nimport sys\nimport pygame as pg\nfrom pygame.locals import *\n\npg.init()\n\nFPS = 60\nFPSCLOCK = pg.time.Clock()\n\nGRAVITY = 1\nMOV_SPEED = 5 * 60\nJUMP_SPEED = -22 * 60\nLEFT = \"left\"\nRIGHT = \"right\"\n\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nGREY = (125, 125, 125)\nBG_COLOR = WHITE\n\nWINDOW_WIDTH = 800\nWINDOW_HEIGHT = 600\nDISPLAYSURF = pg.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))\n\nPLAYER = pg.image.load(\"cat.png\")\nPLAYER_START_X_POS = 350\nPLAYER_START_Y_POS = 400\n\nPLATFORM = pg.Rect(100, 450, 600, 50)\n\n\ndef main():\n player_x_pos = PLAYER_START_X_POS\n player_y_pos = PLAYER_START_Y_POS\n ver_speed = JUMP_SPEED\n moving = False\n jumping = False\n direction = RIGHT\n \n while True: \n dt = FPSCLOCK.tick(FPS) / 1000\n DISPLAYSURF.fill(BG_COLOR)\n pg.draw.rect(DISPLAYSURF, GREY, PLATFORM)\n \n pressed = pg.key.get_pressed()\n for event in pg.event.get():\n if (event.type == QUIT or\n event.type == KEYUP and event.key == K_ESCAPE):\n pg.quit()\n sys.exit()\n\n if pressed[K_SPACE]:\n jumping = True\n if pressed[K_LEFT]:\n player_x_pos -= MOV_SPEED * dt\n if pressed[K_RIGHT]:\n player_x_pos += MOV_SPEED * dt\n\n if jumping == True:\n player_y_pos += ver_speed * dt\n ver_speed += GRAVITY\n\n if player_y_pos > PLAYER_START_Y_POS:\n player_y_pos = PLAYER_START_Y_POS\n jumping = False\n ver_speed = JUMP_SPEED\n\n DISPLAYSURF.blit(PLAYER, (player_x_pos, player_y_pos))\n \n pg.display.update() # vielleicht dirty update für flüssigere bewegung?\n \n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"spring_test.py","file_name":"spring_test.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"641319377","text":"import numpy as np\nimport scipy\nfrom matplotlib import pyplot as plt\nimport matplotlib.image as mpimage\nimport utilities as ut\nimport lab1\nfrom matplotlib.patches import Circle\nimport matplotlib.axes as axes\n\n\nim1 = lab1.load_lab_image(\"chessboard_1.png\")\nimShape = np.shape(im1)\n\nimages = np.zeros((imShape[0], imShape[1], 10))\nfor i in range(1,11):\n filename = \"chessboard_\" + str(i) + \".png\"\n images[:,:,i-1] = lab1.load_lab_image(filename)\n\nwindow_size = np.array([21,21])\nharrisWindow = np.array([3,3])\nmaxIterations = 100\nksize = 5\nsigma = 1\ndThresh = 0.05\nkappa = 0.05\nharrisThresh = 0.1\n\n\n(ch, x, y) = ut.harris(images[:,:,0], 5, ksize, sigma, harrisWindow, kappa, harrisThresh)\ndTot = np.zeros((2, np.size(x), 9))\npoints = np.zeros((2, np.size(x), 10))\npoints[:,:,0] = np.array([x,y])\n\nfor j in range(0,9):\n fig, ax = plt.subplots()\n ax.imshow(images[:,:,j])\n\n for i in range(0, np.size(x)):\n dTemp = ut.myKLTracker(images[:,:,j], images[:,:,j+1], points[:,i,j], window_size, maxIterations, ksize, sigma, dThresh)\n dTot[0,i,j] = dTemp[0]\n dTot[1,i,j] = dTemp[1]\n points[0,i,j+1] = points[0,i,j] + dTot[0,i,j]\n points[1,i,j+1] = points[1,i,j] + dTot[1,i,j]\n circ = Circle(points[:,i,j], 4, facecolor = 'None', linewidth = 1.0, edgecolor = 'r')\n ax.add_patch(circ)\n print(\"Image: \" + str(j+1))\n #print(\"Estimated d for image \" + str(j+1) + \" to \" + str(j+2))\n #print(dTot[:,:,j])\n #print(\"Estimated point in image \" + str(j+1))\n #print(np.round(points[:,1,j]))\n\nplt.show()\n","sub_path":"Lab 1/KLTtest.py","file_name":"KLTtest.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"231875152","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\ndef start(day):\r\n # title=[]\r\n namoz_name = ['Бомдод ', 'Пешин ', 'Аср ', 'Шом ', 'Хуфтан ']\r\n r=requests.get('http://shuroiulamo.tj/tj/namaz').text\r\n # #print(html_doc)\r\n html_doc=r\r\n soup = BeautifulSoup(html_doc, 'html.parser')\r\n table = soup.find('div', class_='mechety').find('tbody')\r\n # #print(table)\r\n today = (table.find('tr', class_='today').text).split('\\n')\r\n today = today[4:]\r\n # print(today)\r\n # i=2\r\n today = []\r\n table = table.find_all('tr')[day-1:day]\r\n\r\n # #print(table)\r\n # for tab in table:\r\n # #\r\n tds = (table[0].find_all('td'))\r\n #name=table[0]\r\n # #print(tds)\r\n for td in tds:\r\n today.append(td.text)\r\n str=''\r\n i=0\r\n today[1]\r\n\r\n for i in range (0,5):\r\n j=i+3\r\n if j>=6:\r\n j=j+1\r\n str=str+namoz_name[i]+today[j]+ '\\n'\r\n return ' '+today[1]+' '+'\\n'+str","sub_path":"namoz.py","file_name":"namoz.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"635850524","text":"import requests\n\nurl = 'http://address/path'\n\nheaders = {\n 'content-type': 'application/json',\n}\n\n\njson = {\n u'email': u'example@example.com',\n u'name': u'example',\n}\n\n\nresponse = requests.request(\n method='POST',\n url=url,\n headers=headers,\n json=json,\n)\n\nprint(response.text)\n","sub_path":"test/mitmproxy/data/test_flow_export/python_post_json.py","file_name":"python_post_json.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"136608243","text":"# -*- coding: utf-8 -*-\n\"\"\"\nМикросервис broker: брокер сообщений для app, worker, reporter\n\"\"\"\nimport logging\n\nimport redis\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\n__VERSION = 1.0\n__DEBUG = True\n__PORT = 5001\n\nconsole = logging.StreamHandler()\nlogger = logging.getLogger('__name__')\nlogger.addHandler(console)\nlogger.setLevel(logging.INFO)\n\nr = redis.Redis('localhost')\n\n\n@app.route('/get')\ndef get():\n url = request.args.get('url')\n logger.error('[INFO] /get with {}'.format(url))\n if not url:\n msg = 'No url parameter provided.'\n logger.error('[ERROR] {}'.format(msg))\n return jsonify({'error': msg}), 400\n\n status_b = r.get(url)\n if status_b:\n status = status_b.decode(\"utf-8\")\n else:\n return jsonify(), 404\n\n return jsonify({'status': status}), 200\n\n\n@app.route('/set')\ndef set():\n url = request.args.get('url')\n status = request.args.get('status')\n logger.error('[INFO] /set with {} and {}'.format(url, status))\n if not url or not status:\n msg = 'No url or status parameters provided.'\n logger.error('[ERROR] {}'.format(msg))\n return jsonify({'error': msg}), 400\n\n r.set(url, status)\n return jsonify(), 200\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=__PORT, debug=__DEBUG)\n","sub_path":"broker/broker.py","file_name":"broker.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"243854485","text":"\"\"\"\nrequest:\ncontent:1,12,11,13,5,2,7,9,10,15,3,14,6,8,4,0\ncontent:\n1,12,11,13,\n5,2,7,9,\n10,15,3,14,\n6,8,4,0\n\nzero signifies a blank space\nResponse\n14,13,9,10,6,2,1,5,6,10,9,5,6,7,11,10,6,7,11,10,6,2,3,7,11,15,14,10,6,7,11,10,6,2,3,7,6,5,9,13,12,8,9,13,14,10,6,5,9,13,14,15,11,10,6,7,11,15,14,10,11,15,14,10,6,7,11,15,14,13,9,10,14,13,12,8,9,10,14,13,12,8,9,10,14,13,9,10,11,15\n\neach number in the solution indicates the tile to be moved/clicked\n# testMap2 = [10, 9, 5, 7, 4, 2, 13, 1, 8, 12, 11, 14, 6, 3, 15, 0]\n\"\"\"\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\nimport random\nimport inspect\n\n\nclass puzzlesolver():\n\n \"\"\" int i\n int j\n int slidePiece\n int slideH\n int slideV\n int displace \"\"\"\n dragging = 0\n seed = 1\n counter = 0\n autoDisplace = [0, 5, 12, 21, 32, 32, 27, 20, 11, 0]\n subGoals = [1, 0, 2, 0, 3, 4, 0, 5, 0, 6, 0, 7, 8, 0, 9, 13, 0, 10, 14, 0, 11, 12, 15, 0, 16]\n delimiter = \"\\n|\"\n detour1 = [11, 10, 6, 7, 11, 10, 6, 7, 3, 2, 6, 7, 11, -1]\n detour2 = [15, 14, 10, 11, 15, 14, 10, 11, 7, 6, 10, 11, 15, -1]\n detour3 = [6, 2, 3, 7, -1]\n detour4 = [3, 7, -1]\n detour5 = [10, 6, 7, 11, -1]\n detour6 = [7, 11, -1]\n detour7 = [13, 12, 8, 9, -1]\n detour8 = [8, 9, -1]\n detour9 = [10, 14, 13, 9, 10, 14, 13, 9, 8, 12, 13, 9, 10, -1]\n detour10 = [14, 13, 9, 10, -1]\n detour11 = [9, 10, -1]\n detour12 = [11, 15, 14, 10, 11, 15, 14, 10, 9, 13, 14, 10, 11, -1]\n dragControl = True\n # holder = new int[20]\n # inputMap\n # moves = new int[400]\n moveCount = 0\n moveNum = 0\n roundabout = [11, 10, 14, 15, -1]\n roundDisp = [-4, -3, 1, 5, 4, 3, -1, -5, -4, -3, 1, 5, 4, 3, -1, -5, -4, -3, 1, 5, 4, 3, -1, -5, -4]\n rounddx = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0]\n # int current\n testMap2 = [10, 9, 5, 7, 4, 2, 13, 1, 8, 12, 11, 14, 6, 3, 15, 0]\n testMap3 = [1, 12, 11, 13, 5, 2, 7, 9, 10, 15, 3, 14, 6, 8, 4, 0]\n expected_solution_3 = [14, 13, 9, 10, 6, 2, 1, 5, 6, 10, 9, 5, 6, 7, 11, 10, 6, 7, 11, 10, 6, 2, 3, 7, 11, 15, 14, 10, 6, 7, 11, 10, 6, 2, 3, 7, 6, 5, 9, 13, 12, 8, 9, 13, 14, 10, 6, 5, 9, 13, 14, 15, 11, 10, 6, 7, 11, 15, 14, 10, 11, 15, 14, 10, 6, 7, 11, 15, 14, 13, 9, 10, 14, 13, 12, 8, 9, 10, 14, 13, 12, 8, 9, 10, 14, 13, 9, 10, 11, 15]\n wrong_solution_3 = [14, 13, 9, 11, 6, 2, 1, 5, 6, 10, 9, 5, 6, 7, 11, 10, 6, 7, 11, 10, 6, 2, 3, 7, 11, 15, 14, 10, 6, 7, 11, 10, 6, 2, 3, 7, 6, 5, 9, 13, 12, 8, 9, 13, 14, 10, 6, 5, 9, 13, 14, 15, 11, 10, 6, 7, 11, 15, 14, 10, 11, 15, 14, 10, 6, 7, 11, 15, 14, 13, 9, 10, 14, 13, 12, 8, 9, 10, 14, 13, 12, 8, 9, 10, 14, 13, 9, 10, 11, 15]\n\n map = [0] * 36 # new int[36]\n # ppath = new int[9]\n # boolean vertical\n automatic = False\n # boolean oldDragControl\n # solution\n border1 = \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\"\n # StringBuilder problemAndSolution\n\n def lineno(self):\n # Returns the current line number in our program.\n return inspect.currentframe().f_back.f_lineno\n\n def print_map(self):\n print('running print_map')\n sbMap = \"\"\n mapSum = 0\n i = 0\n while (i < 4):\n j = 0\n while (j < 4):\n mapVal = self.map[7 + i * 6 + j]\n # Formatter formatter = new Formatter(new StringBuilder(), Locale.US)\n # formatter = new Formatter(new StringBuilder(), Locale.US)\n formatted_mapval = '%2d'.format(mapVal)\n # formatter.format(\" %2d \", mapVal)\n sbMap = sbMap + formatted_mapval # formatter\n sbMap = sbMap + str(mapVal)\n mapSum += mapVal\n j = j + 1\n\n if (i == 0 or i == 1 or i == 2 or i == 3):\n pass # // empty if block\n\n ++i\n print(sbMap)\n return sbMap\n\n def makeRandInt(self):\n Lower_Bound = 1\n Upper_Bound = 3000\n # return (int)((double)Lower_Bound + Math.random() * (double)(Upper_Bound - Lower_Bound) + 0.5)\n return (Lower_Bound + random.random() * (Upper_Bound - Lower_Bound) + 0.5)\n\n\n\n def compare_lists(computed, actual):\n if not len(computed) == len(actual):\n print(self.lineno(), 'solution length error')\n exit(1)\n for index in range(len(computed)):\n if not computed[index] == actual[index]:\n print(\"error\", 'at index', index, computed[index], '!=', actual[index])\n exit(2)\n\n def init(self):\n i = 0\n while (i < 6):\n self.map[i] = 1\n self.map[i * 6] = 1\n i += 1\n\n i = 0\n while (i < 4):\n j = 0\n while (j < 4):\n self.map[7 + i * 6 + j] = i * 4 + j + 1 & 15\n j += 1\n\n i += 1\n\n print(self.lineno(), 'self.map = ', self.map)\n # self.print_map()\n # printHolder()\n # self.print_map()\n\n\n def solve_puzzle(self, inputMap):\n print('running solve_puzzle')\n # inputMap = inputMap\n # setProblemAndSolution(new StringBuilder() + Arrays.toString(inputMap)))\n # inputMap = testMap2\n # problemAndSolution = str(inputMap)\n self.init()\n seed = self.makeRandInt()\n map = self.fillMap(inputMap)\n self.print_map()\n self.solve()\n self.print_map()\n self.run()\n solution = int[moveCount]\n for i in range(moveCount):\n solution[i] = moves[i]\n problemAndSolution = problemAndSolution + \"|\" + int(solution.length) + \"|\" + str(solution)\n print('solution = ', solution)\n\n def formatInteger(inInt):\n # Formatter formatter = new Formatter(new StringBuilder(), Locale.US)\n # formatter.format(\" %6d \", inInt)\n # return formatter.toString()\n return str(inInt)\n\n def fillMap(self, mapCounter):\n print('running fillmap')\n mapCounter = 0\n i = 0\n while i < 4:\n j = 0\n while j < 4:\n self.map[7 + i * 6 + j] = mapCounter\n mapCounter += 1\n j += 1\n\n i += 1\n print(self.map)\n return self.map\n\n def inMap(h, v):\n myArray = []\n i = 0\n while i < myArray.length:\n myArray[i] = i\n i += 1\n\n return map[7 + h + 6 * v]\n\n def getNextMove():\n j = 0\n try:\n j = myd['moves'][myd['moveNum']]\n print(j)\n except Exception as e:\n print(\"error\", e)\n\n print_map()\n i = j / 4\n # set j equal to the last two bits of j with bitmap 3 (0011), i.e., 0 <= j <= 3\n j = j & 3\n # if (j &= 3) < 3 and inMap(j + 1, i) == 0:\n if j < 3 and inMap(j + 1, i) == 0:\n myd['dragging'] = 2\n myd['slideH'] = j\n myd['slideV'] = i\n elif (j > 0 and inMap(j - 1, i) == 0):\n myd['dragging'] = 2\n myd['slideH'] = j - 1\n myd['slideV'] = i\n elif (i < 3 and inMap(j, i + 1) == 0):\n myd['dragging'] = 1\n myd['slideH'] = j\n myd['slideV'] = i\n elif (i > 0 and inMap(j, i - 1) == 0):\n myd['dragging'] = 1\n myd['slideH'] = j\n myd['slideV'] = i - 1\n\n myd['vertical'] = 1\n myd['dragging'] = 1\n bl = 1\n if (myd['slideH'] == j and myd['slideV'] == i):\n displace = 0\n counter = 0\n else:\n displace = 32\n counter = 5\n\n slidePiece = inMap(j, i)\n map[7 + j + 6 * i] = 0\n automatic = True\n\n def scramble():\n print_map()\n if not automatic:\n j = 1\n i = 1\n # for (i = 0 i < 4 ++i):\n while i < 4:\n # for (j = 0 j < 4 ++j):\n while j < 4:\n map[7 + i * 6 + j] = i * 4 + j + 1 & 15\n\n # for (i = 0 i < 16 ++i):\n while i < 16:\n l = (randi() >> 5) % 15\n j = 7 + 6 * (l / 4) + (l & 3)\n l = (randi() >> 5) % 15\n k = 7 + 6 * (l / 4) + (l & 3)\n while (k == j):\n l = (randi() >> 5) % 15\n k = 7 + 6 * (l / 4) + (l & 3)\n\n l = map[k]\n map[k] = map[j]\n map[j] = l\n\n printHolderAlone()\n print_map()\n\n def solve(self):\n try:\n i = 0\n while (i < 4):\n j = 0\n while (j < 4):\n holder[i * 4 + j] = inMap(j, i)\n ++j\n\n ++i\n\n printHolder()\n goalsDone = 0\n i = 0\n j = 0\n while (holder[subGoals[i] - 1] == subGoals[i]):\n printHolderAlone()\n ++i\n if (subGoals[i] != 0):\n continue\n\n j = (i + 1)\n i += 1\n goalsDone += 1\n\n i = 0\n while (i < j):\n if (subGoals[i] > 0):\n holder[PuzzleSolver.subGoals[i] - 1] = -1\n\n ++i\n\n moveCount = 0\n if ((displace & 31) > 0):\n goalsDone = 9\n\n while (goalsDone < 9):\n printHolderAlone()\n detour = False\n # switch(goalsDone):\n if goalsDone == 0:\n # boolean detour\n # case 0:\n printHolder()\n moveTo(1, 0)\n break\n elif goalsDone == 1:\n printHolder()\n moveTo(2, 1)\n break\n\n # case 2:\n elif goalsDone == 2:\n printHolder()\n moveTo(3, 3)\n holder[3] = -1\n i = locate(0)\n detour = False\n if (i == 7):\n if (holder[2] == 4):\n makeDetour(detour3, 7)\n detour = True\n elif (i == 2):\n if (holder[6] == 4):\n makeDetour(detour4, 2)\n detour = True\n elif (holder[2] == 4):\n moveTo(4, 6)\n makeDetour(detour4, 2)\n detour = True\n\n if (detour):\n makeDetour(detour1, 7)\n else:\n moveTo(4, 7)\n\n holder[3] = 3\n holder[7] = -1\n moveTo(3, 2)\n holder[7] = 4\n moveTo(4, 3)\n break\n\n # case 3:\n elif goalsDone == 3:\n moveTo(5, 4)\n break\n\n # case 4:\n elif goalsDone == 4:\n moveTo(6, 5)\n break\n\n # case 5:\n elif goalsDone == 5:\n printHolder()\n moveTo(7, 7)\n holder[7] = -1\n i = locate(0)\n detour = False\n if (i == 11):\n if (holder[6] == 8):\n makeDetour(detour5, 11)\n detour = True\n\n elif (i == 6):\n if (holder[10] == 8):\n makeDetour(detour6, 6)\n detour = True\n\n elif (holder[6] == 8):\n moveTo(8, 10)\n makeDetour(detour6, 6)\n detour = True\n\n if (detour):\n makeDetour(detour2, 11)\n else:\n moveTo(8, 11)\n\n holder[7] = 7\n holder[11] = -1\n moveTo(7, 6)\n holder[11] = 8\n moveTo(8, 7)\n # break\n\n # case 6:\n elif goalsDone == 6:\n moveTo(13, 8)\n holder[8] = -1\n i = locate(0)\n detour = False\n if (i == 9):\n if (holder[12] == 9):\n makeDetour(detour7, 9)\n detour = True\n\n elif (i == 12):\n if (holder[13] == 9):\n makeDetour(detour8, 12)\n detour = True\n\n elif (holder[12] == 9):\n moveTo(9, 13)\n makeDetour(detour8, 12)\n detour = True\n\n if (detour):\n makeDetour(detour9, 9)\n else:\n moveTo(9, 9)\n\n holder[8] = 13\n holder[9] = -1\n moveTo(13, 12)\n holder[9] = 9\n moveTo(9, 8)\n printHolder()\n break\n\n # case 7:\n elif goalsDone == 7:\n printHolder()\n moveTo(14, 9)\n i = locate(0)\n detour = False\n if (i == 10):\n if (holder[13] == 10):\n makeDetour(detour10, 10)\n detour = True\n\n elif (holder[14] == 10):\n makeDetour(detour11, 13)\n detour = True\n\n if (detour):\n makeDetour(detour12, 10)\n else:\n moveTo(10, 10)\n\n holder[9] = 14\n holder[10] = -1\n moveTo(14, 13)\n holder[10] = 10\n moveTo(10, 9)\n printHolder()\n # break\n\n # case 8:\n elif goalsDone == 8:\n while (holder[15] != 0):\n if (holder[10] == 0):\n moves[moveCount] = 11\n moveCount += 1\n holder[10] = holder[11]\n holder[11] = 0\n\n if (holder[11] == 0):\n moves[moveCount] = 15\n moveCount += 1\n holder[11] = holder[15]\n holder[15] = 0\n\n if (holder[14] != 0):\n continue\n moves[moveCount] = 15\n moveCount += 1\n holder[14] = holder[15]\n holder[15] = 0\n\n while (holder[14] != 15):\n makeDetour(roundabout, 15)\n\n # else:\n # print('possible error?`')\n\n printHolder()\n break\n\n else:\n printHolder()\n\n ++goalsDone\n\n if (moveCount > 0):\n printHolderAlone()\n moveNum = 0\n getNextMove()\n oldDragControl = dragControl\n dragControl = False\n\n except: # catch (ArrayIndexOutOfBoundsException e):\n pass\n\n\nprint('running')\np = puzzlesolver()\nmyTestMap = p.testMap2\nprint('myTestMap = ', myTestMap)\n\nsolution = p.solve_puzzle(myTestMap)\nprint(\"solution = \", p.printArray(solution))\nprint(\"testMap3 = \", p.printArray(p.testMap3))\n# solution = p.solve_puzzle(p.testMap3)\n\n\n\"\"\"\ndef makeDetour(dList, hole):\n i = 0\n j = hole\n while (dList[i] >= 0):\n holder[j] = holder[dList[i]]\n holder[dList[i]] = 0\n j = dList[i]\n moves[moveCount] = dList[i]\n moveCount += 1\n i += 1\n\n\ndef moveTo(p, t):\n i\n whereNow = i = locate(p)\n j = 0\n while ((i & 3) != (t & 3)):\n # i = (i & 3) < (t & 3) ? ++i : --i\n if i == (i & 3) < (t & 3):\n i += 1\n else:\n i = i - 1\n ppath[j] = i\n j += 1\n while i > t:\n # ppath[j++] = i-=4\n ppath[j] = i\n i = 4\n j += 1\n\n holder[whereNow] = -1\n # for (i = 0 i < j ++i):\n i += 1\n while i < j:\n moveHole(ppath[i], whereNow)\n moves[moveCount] = whereNow\n moveCount += 1\n holder[whereNow] = 0\n holder[ppath[i]] = -1\n whereNow = ppath[i]\n printHolderAlone()\n\n\ndef moveHole(tg, ppos):\n k = 0\n posCount = 0\n negCount = 0\n i = locate(0)\n while Math.abs(i & 3) - (ppos & 3) > 1 or \\\n Math.abs(i / 4 - ppos / 4) > 1:\n k = (i & 3) < (tg & 3) and\n\n holder[i + 1] > 0 ? i + 1 : ((i & 3) > (tg & 3) and\n holder[i - 1] > 0 ? i - 1 : (i / 4 < tg / 4 and\n holder[i + 4] > 0 ? i + 4 : i - 4))\n\n # k = (i & 3) < (tg & 3) and holder[i + 1] > 0 ? i + 1 : ((i & 3) > (tg & 3) and holder[i - 1] > 0 ? i - 1 : (i / 4 < tg / 4 and holder[i + 4] > 0 ? i + 4 : i - 4))\n result_0 = (i + 3) < (tg + 3)\n\n def get_result_1():\n if holder[i + 1] > 0:\n i = i + 1\n return i\n else:\n return (i & 3) > (tg & 3)\n\n def get_result_2():\n if holder[i - 1] > 0:\n i = i - 1\n return i\n else:\n return i / 4 < tg / 4\n\n def get_result_3():\n if holder[i + 4] > 0:\n return i + 4\n else:\n return i - 4\n\n k = result_0 and get_result_1() and get_result_2() \\\n and get_result_3()\n\n moves[moveCount] = k\n moveCount += 1\n holder[i] = holder[k]\n holder[k] = 0\n i = k\n\n if (i != tg):\n j = 8\n # while (i != ppos + roundDisp[j]):\n while i != ppos + roundDisp[j]:\n j += 1\n\n k = j\n # while (ppos + roundDisp[k] != tg):\n while ppos + roundDisp[k] != tg:\n if (ppos + roundDisp[++k] >= 0 and ppos + roundDisp[k] < 16 and (ppos & 3) + rounddx[k] < 4 and (ppos & 3) + rounddx[k] >= 0 and holder[ppos + roundDisp[k]] > 0):\n ++posCount\n continue\n\n posCount += 50\n\n k = j\n while (ppos + roundDisp[k] != tg):\n if (ppos + roundDisp[--k] >= 0 and ppos + roundDisp[k] < 16 and (ppos & 3) + rounddx[k] < 4 and (ppos & 3) + rounddx[k] >= 0 and holder[ppos + roundDisp[k]] > 0):\n ++negCount\n continue\n\n negCount += 50\n\n # l = posCount <= negCount ? 1 : -1\n if posCount <= negCount:\n l = 1\n else:\n l = -1\n\n while (i != tg):\n j = j + 1\n k = ppos + roundDisp[j]\n\n moves[moveCount] = k\n moveCount += 1\n holder[i] = holder[k]\n holder[k] = 0\n i = k\n\n printHolderAlone()\n\n\ndef locate(num):\n li = 0\n while (holder[li] != num):\n i += 1\n\n return li\n\n\ndef run():\n automatic = True\n sb = \"\\nrunning run()>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\"\n sb += \" counter = \" + counter\n sb += \" dragging = \" + dragging\n sb += \" moveNum = \" + moveNum + \" moveCount = \" + moveCount\n print_map()\n while (counter <= 9 and automatic):\n if not automatic:\n continue\n ++counter\n displace = autoDisplace[counter]\n sb = sb + \"counter = \" + counter + \" \"\n sb + \"dragging = \" + dragging + \" \"\n if (dragging == 1):\n sb = sb + \"dragging == 1 \"\n elif (dragging == 2):\n sb = sb + \"dragging == 2 \"\n\n sb = sb + \" displace = \" + displace + \" \"\n sb = sb + \" displace&31 = \" + displace & 31\n if ((displace & 31) != 0):\n continue\n if (vertical):\n if (displace == 0):\n map[7 + slideH + 6 * slideV] = slidePiece\n else:\n map[7 + slideH + 6 * slideV + 6] = slidePiece\n\n elif (displace == 0):\n map[7 + slideH + 6 * slideV] = slidePiece\n else:\n map[7 + slideH + 6 * slideV + 1] = slidePiece\n\n ++moveNum\n print_map()\n dragging = 0\n sb = sb + \"moveNum = \" + moveNum + \" moveCount = \" + moveCount\n if (moveNum == moveCount):\n automatic = False\n dragControl = oldDragControl\n sb = sb + \"Done moving tiles\"\n print_map()\n printMoves()\n printHolder()\n continue\n\n getNextMove()\n\n sb = sb + \"ending run()\"\n\n\ndef randi():\n seed = seed * 171 % 30269\n return seed\n\n\ndef printHolder():\n # StringBuilder sb = new StringBuilder()\n sb = \"\"\n sb = sb + \"-holder[\" + holder.length + \"] = \"\n i = 0\n while (i < holder.length):\n sb + holder[i] + \", \"\n ++i\n\n sb = sb + \"\\n\"\n sb = sb + \"map[\" + map.length + \"] = \"\n i = 0\n while (i < map.length):\n sb + map[i] + \", \"\n ++i\n\n sb = sb + \"\\n\"\n sb = sb + \"moves[\" + moveCount + \"] = \"\n i = 0\n while (i < moveCount):\n sb = sb + moves[i] + \", \"\n ++i\n\n sb = sb + \"\\n\"\n\n\ndef printMoves():\n sb = \"\"\n sb = sb + \"moves[\" + moveCount + \"] = \"\n i = 0\n while (i < moveCount):\n sb = sb + moves[i] + \", \"\n ++i\n\n sb = sb + \"\\n\"\n\n\ndef printHolderAlone():\n sb = \"\"\n sb = sb + \"+holder[\" + holder.length + \"] = \"\n i = 0\n while (i < holder.length):\n sb = sb + holder[i] + \", \"\n i = i + 1\n\n\n\n\ndef printPPath():\n # sb = new StringBuilder()\n sp = ''\n sb = sb + \"ppath[\" + ppath.length + \"] = \"\n i = 1\n while i < ppath.length:\n sb = sb + ppath[i] + \", \"\n i += 1\n sb = sb + \"\\n\"\n\n\ndef printArray(inArray):\n # StringBuilder sb = new StringBuilder()\n sb = \"\"\n sb = sb + \"inArray[\" + inArray.length + \"] = \"\n sumInts = 0\n i = 1\n # for (int i = 0 i < inArray.length ++i):\n while i < inArray.length:\n sb = sb + inArray[i] + \", \"\n sumInts += inArray[i]\n i += 1\n\n return sb\n\n\ndef getProblemAndSolution():\n return problemAndSolution\n\n\ndef setProblemAndSolution(in_problemAndSolution):\n problemAndSolution = in_problemAndSolution\n\n\ndef appendToProblemAndSolution(inString):\n problemAndSolution += inString\n return problemAndSolution\n\n\n\"\"\"\n","sub_path":"solvepuzzle/solve_puzzle.py","file_name":"solve_puzzle.py","file_ext":"py","file_size_in_byte":22596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"427426172","text":"#!/usr/bin/env python3\n#\n# This file is part of LUNA.\n#\n\nfrom nmigen import Elaboratable, Module, Cat, Signal\n\nfrom luna import top_level_cli\nfrom luna.gateware.architecture.car import LunaECP5DomainGenerator\nfrom luna.gateware.usb.usb2.device import USBDevice\n\n\nclass USBDeviceExample(Elaboratable):\n \"\"\" Simple example of a USB device using the LUNA framework. \"\"\"\n\n\n def elaborate(self, platform):\n m = Module()\n\n # Generate our domain clocks/resets.\n m.submodules.car = LunaECP5DomainGenerator()\n\n # Create our USB device interface...\n ulpi = platform.request(\"target_phy\")\n m.submodules.usb = usb = USBDevice(bus=ulpi)\n\n # Connect our device by default.\n m.d.comb += usb.connect.eq(1)\n\n # ... and for now, attach our LEDs to our most recent control request.\n leds = Cat(platform.request(\"led\", i) for i in range(6))\n m.d.comb += leds.eq(usb.last_request)\n\n return m\n\n\nif __name__ == \"__main__\":\n top_level_cli(USBDeviceExample)\n","sub_path":"examples/usb/simple_device.py","file_name":"simple_device.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"640026390","text":"def IsPalindrome(n):\n nStr = str(n)\n return nStr == nStr[::-1]\n\ntotal = 0\n\nfor i in range(1000000):\n iBin = bin(i)\n if IsPalindrome(i) and IsPalindrome(iBin[2:]):\n total += i\n\n\n\ndef BaseConvert(n, base):\n numstr = ''\n while n > 0:\n digit = n % base\n n = n // base\n numstr = numstr + digit","sub_path":"036.py","file_name":"036.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"511886647","text":"from xml.etree.ElementTree import Element\n\nimport openmath.omparse as omparse\nimport openmath.omput as omput\n\n\nclass IncorrectNumberOfIntervalArgumentsError(Exception):\n def __init__(self):\n self.count = count\n\n def __repr__(self):\n return self.__class__.__name__ + '(%s)' % (self.count)\n\n\n@omparse.parse_openmath('interval1', 'integer_interval')\ndef interval(lst):\n if len(lst) == 2:\n return xrange(lst[0], lst[1] + 1) # Add one, since OpenMath intervals are inclusive.\n else:\n raise IncorrectNumberOfIntervalArgumentsError(len(lst))\n\n\n@omput.serialise_openmath(xrange)\ndef om_interval(x):\n omelt = Element(\"OMA\")\n oms = Element(\"OMS\")\n oms.attrib = {'cd': 'interval1', 'name': 'integer_interval'}\n omelt.append(oms)\n\n omelt.append(omput.om_int(x[0]))\n omelt.append(omput.om_int(x[-1]))\n\n return omelt\n","sub_path":"Code/openmath/content_dictionaries/interval1.py","file_name":"interval1.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"574433946","text":"class Solution:\n \"\"\"\n @param nums: A set of numbers.\n @return: A list of lists. All valid subsets.\n \"\"\"\n def subsetsWithDup(self, nums):\n self.results = []\n temp = []\n\n nums = sorted(nums)\n\n self.dfs(nums, 0, len(nums), temp)\n\n return self.results\n\n def dfs(self, nums, index, length, temp):\n if index > length:\n return\n\n self.results.append(temp[:])\n\n for i in range(index, length):\n if i > index and nums[i] == nums[i - 1]:\n continue\n temp.append(nums[i])\n self.dfs(nums, i + 1, length, temp)\n temp.pop()\n","sub_path":"US Giants/Search & Recursion/18. Subsets II.py","file_name":"18. Subsets II.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"147481072","text":"import apfel\nimport matplotlib.pyplot as plt\nimport sys\nfrom regex import split\n\n\ndef x_extractor(fInput):\n with open(fInput) as input:\n line = input.readlines()\n a = split(r\"\\s\", line[3])\n return a\n\nx= []\nfor item in x_extractor(sys.argv[1]):\n try:\n if float(item) > 0.0001:\n x.append(float(item))\n except:\n continue\nprint(x)\napfel.SetQLimits(1.3, 100000)\napfel.SetProcessDIS(\"NC\")\napfel.SetTargetDIS(\"neutron\")\napfel.InitializeAPFEL_DIS()\napfel.ComputeStructureFunctionsAPFEL(1.3, 20)\n\nf2N = []\nfor item in x:\n f2N.append(apfel.F2light(item))\n\napfel.SetQLimits(1.3, 100000)\napfel.SetProcessDIS(\"NC\")\napfel.SetTargetDIS(\"proton\")\napfel.InitializeAPFEL_DIS()\napfel.ComputeStructureFunctionsAPFEL(1.3, 20)\n\nf2P = []\nfor item in x:\n f2P.append(apfel.F2light(item))\n\nf2D = []\nfor i in range(0, len(f2P)):\n f2D.append((f2N[i] + f2P[i]) / 2)\n\nwith open('output.dat', 'w+') as fil:\n for i in range(0, len(f2D)):\n fil.writelines(str(x[i]) + \", \" + str(f2N[i]) + \", \" + str(f2P[i]) + \", \" + str(f2D[i]) + \"\\n\")\n\n\n\n\n\n\n\n\n\n\n","sub_path":"f2_draw.py","file_name":"f2_draw.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"131225631","text":"from django.contrib import admin\nfrom django.urls import path,include\nfrom . import views\n\nurlpatterns = [\n path('',views.home,name='home'),\n path('events/', views.events, name='events'),\n path('map3d/', views.map3d, name='map3d'),\n path('registration', views.registration, name='registration'),\n path('register', views.register, name='register'),\n path('sponsers', views.sponsers, name='sponsers'),\n path('team', views.team, name='team'),\n path('dashboard/', views.dashboard, name='dashboard'),\n path('login/', views.login_view, name=\"login\"),\n path('logout/', views.logout_view, name=\"logout\"),\n path('eventreg/', views.event_reg, name=\"eventsreg\"),\n path('eventdel', views.event_del, name=\"eventdel\"),\n path('change_registration_details/', views.change_details, name=\"change\"),\n path('forgotpwd/', views.forgotpwd, name=\"forgotpwd\"),\n path('otpgenerator/', views.otpgenerator, name=\"otpgenerator\"),\n path('otpcomparator',views.otpcomparator,name = 'otpcomparator'),\n path('changepwd', views.changepwd, name='changepwd'),\n path('change_registration_details/', views.change_details, name=\"change\"),\n path('payment_request/', views.payment_request, name=\"payment_request\"),\n path('payment_response/<slug:event>/', views.payment_response, name=\"payment_response\"),\n path('gallery', views.gallery, name=\"gallery\"),\n path('map3dHome', views.map3dHome, name=\"map3dHome\"),\n\n]","sub_path":"acusite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"483760902","text":"#!/usr/bin/python3\n\nimport re\nimport cgi\nimport json\nimport string\n\nimport requests\nimport pymongo\n\nimport get\nimport latex2png\n\nIMAGE_DIR = './image/'\n\n#########################################\n# process data #\n# [[.*]] -> $$.*$$ -> <img src=\"...\" /> #\n#########################################\n\ndef latex(func):\n \"\"\"处理latex公式的装饰器\n \n Args:\n func: 函数\n\n Returns:\n 返回一个内部函数\n\n Raises: 无\n \"\"\"\n def wrapper(data: str) -> str:\n \"\"\"处理latex公式\n\n 接受一个字符串,对于字符串中包含在[[]]中的LaTeX公式,下载图片,并将公式替换为特定图片格式,例如:\n [[c = a + b]] -> $$img.png$$\n\n Args:\n data: 待处理字符串\n\n Returns:\n 返回处理后的数据\n \n Raises: 无\n \"\"\"\n for x in re.findall(r'\\[\\[(.*?)\\]\\]', data):\n imgname, imgdata = latex2png.get_image(x)\n with open(IMAGE_DIR + imgname, 'wb') as f:\n for _ in imgdata.iter_content(1024):\n f.write(_)\n data = data.replace(f'[[{x}]]', f'$${imgname}$$')\n return func(data)\n return wrapper\n\ndef image(func):\n \"\"\"处理图片名的装饰器\n\n Args:\n func: 函数\n\n Returns:\n 返回一个内部函数\n\n Raises: 无\n \"\"\"\n def wrapper(data: str) -> str:\n \"\"\"处理图片名\n\n 接受一个字符串,对于字符串中包含在$$$$中的图片名,替换为img标签,例如:\n $$pic.png$$ -> <img src=\"http://yihaocup.cn/image/pic.png\" />\n\n Args:\n data: 待处理字符串\n \n Returns:\n 返回处理后的数据\n\n Raises: 无\n \"\"\"\n return func(re.sub(r'\\$\\$(.*?)\\$\\$', r'<img src=\"https://yihaocup.cn/image/\\1\" />', data))\n return wrapper\n\n@latex\n@image\ndef process(data: str) -> str:\n \"\"\"处理数据\n\n 接受一个字符串,经过latex和image两个装饰器处理后,得到结果字符串\n\n Args:\n data: 待处理数据\n\n Returns:\n 返回处理后的数据\n\n Raises: 无\n \"\"\"\n return data\n\n#########################################\n\n\ndef add(formdata: dict) -> None:\n \"\"\"添加题目\n\n 接受表单信息,将题目处理后加入数据库,并保存一同上传的图片\n\n Args:\n formdata: 包含管理平台添加题目时发送到服务器的所有数据的字典\n\n Returns: 无\n\n Raises: 无\n \"\"\"\n # print(formdata)\n data = {'description': None, 'options': {}, 'ans': None}\n data['description'] = formdata['description'].value\n data['ans'] = formdata['ans'].value\n\n for x in string.ascii_uppercase:\n try:\n item = formdata[x].value\n except:\n break\n else:\n data['options'][x] = item\n\n # process data\n data['description'] = process(data['description'])\n for k in data['options']:\n data['options'][k] = process(data['options'][k])\n\n # store to mongodb\n conn = pymongo.MongoClient('127.0.0.1', 27017)\n db = conn.weapp\n data_set = db.problems\n data_set.insert(data)\n\n # store image\n for x in string.digits[1:]:\n try:\n fd = formdata[f'PID{x}']\n except:\n break\n else:\n fn = fd.filename\n fd = fd.file.read()\n with open(IMAGE_DIR + fn, 'wb') as f:\n f.write(fd)\n\n\n\n\n","sub_path":"add.py","file_name":"add.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"620334174","text":"from typing import List, Tuple\n\nimport pytest\nfrom arango.database import StandardDatabase\n\nfrom core.db import workflowinstancedb\nfrom core.db.async_arangodb import AsyncArangoDB\nfrom core.db.workflowinstancedb import WorkflowInstanceData, WorkflowInstanceDb\nfrom core.event_bus import ActionDone\nfrom core.util import utc\nfrom core.workflow.model import Subscriber\n\nfrom core.workflow.workflows import WorkflowInstance\n\n# noinspection PyUnresolvedReferences\nfrom tests.core.workflow.workflows_test import workflow_instance, test_workflow\n\n# noinspection PyUnresolvedReferences\nfrom tests.core.db.graphdb_test import test_db\n\n# noinspection PyUnresolvedReferences\nfrom tests.core.event_bus_test import event_bus, all_events\n\n\n@pytest.fixture\nasync def workflow_instance_db(test_db: StandardDatabase) -> WorkflowInstanceDb:\n async_db = AsyncArangoDB(test_db)\n workflow_instance_db = workflowinstancedb.workflow_instance_db(async_db, \"workflow_instance\")\n await workflow_instance_db.create_update_schema()\n await workflow_instance_db.wipe()\n return workflow_instance_db\n\n\n@pytest.fixture\ndef instances() -> List[WorkflowInstanceData]:\n messages = [ActionDone(str(a), \"test\", \"bla\", \"sf\") for a in range(0, 10)]\n state_data = {\"test\": 1}\n return [\n WorkflowInstanceData(str(a), str(a), \"workflow_123\", messages, \"start\", state_data, utc()) for a in range(0, 10)\n ]\n\n\n@pytest.mark.asyncio\nasync def test_load(workflow_instance_db: WorkflowInstanceDb, instances: List[WorkflowInstanceData]) -> None:\n await workflow_instance_db.update_many(instances)\n loaded = [sub async for sub in workflow_instance_db.all()]\n assert instances.sort() == loaded.sort()\n\n\n@pytest.mark.asyncio\nasync def test_update(workflow_instance_db: WorkflowInstanceDb, instances: List[WorkflowInstanceData]) -> None:\n # multiple updates should work as expected\n await workflow_instance_db.update_many(instances)\n await workflow_instance_db.update_many(instances)\n await workflow_instance_db.update_many(instances)\n loaded = [sub async for sub in workflow_instance_db.all()]\n assert instances.sort() == loaded.sort()\n\n\n@pytest.mark.asyncio\nasync def test_delete(workflow_instance_db: WorkflowInstanceDb, instances: List[WorkflowInstanceData]) -> None:\n await workflow_instance_db.update_many(instances)\n remaining = list(instances)\n for _ in instances:\n sub = remaining.pop()\n await workflow_instance_db.delete(sub)\n loaded = [sub async for sub in workflow_instance_db.all()]\n assert remaining.sort() == loaded.sort()\n assert len([sub async for sub in workflow_instance_db.all()]) == 0\n\n\n@pytest.mark.asyncio\nasync def test_update_state(\n workflow_instance_db: WorkflowInstanceDb,\n workflow_instance: Tuple[WorkflowInstance, Subscriber, Subscriber, dict[str, List[Subscriber]]],\n) -> None:\n wi, _, _, _ = workflow_instance\n first = ActionDone(\"start_collect\", \"test\", \"bla\", \"sf\")\n second = ActionDone(\"collect\", \"test\", \"bla\", \"sf\")\n third = ActionDone(\"collect_done\", \"test\", \"bla\", \"sf\")\n\n async def assert_state(current: str, message_count: int) -> WorkflowInstanceData:\n state: WorkflowInstanceData = await workflow_instance_db.get(wi.id) # type: ignore\n assert state.current_state_name == current\n assert len(state.received_messages) == message_count\n return state\n\n await workflow_instance_db.insert(wi)\n await assert_state(wi.current_state.name, 6)\n\n wi.machine.set_state(\"start\")\n await workflow_instance_db.update_state(wi, first)\n await assert_state(\"start\", 7)\n\n wi.machine.set_state(\"collect\")\n await workflow_instance_db.update_state(wi, second)\n await assert_state(\"collect\", 8)\n\n wi.machine.set_state(\"done\")\n await workflow_instance_db.update_state(wi, third)\n last = await assert_state(\"done\", 9)\n\n assert last.received_messages[-3:] == [first, second, third]\n","sub_path":"keepercore/tests/core/db/workflowinstancedb_test.py","file_name":"workflowinstancedb_test.py","file_ext":"py","file_size_in_byte":3931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"427347704","text":"import torch.nn as nn\nimport torch\nimport torch.nn.functional as F\nfrom ltr.models.layers.blocks import LinearBlock\nfrom ltr.external.PreciseRoIPooling.pytorch.prroi_pool import PrRoIPool2D\n\n\ndef conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):\n return nn.Sequential(\n nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,\n padding=padding, dilation=dilation, bias=True),\n nn.BatchNorm2d(out_planes),\n nn.ReLU(inplace=True))\n\n\ndef valid_roi(roi: torch.Tensor, image_size: torch.Tensor):\n valid = all(0 <= roi[:, 1]) and all(0 <= roi[:, 2]) and all(roi[:, 3] <= image_size[0]-1) and \\\n all(roi[:, 4] <= image_size[1]-1)\n return valid\n\n\nclass ContextTexture(nn.Module):\n \"\"\"docstring for ContextTexture \"\"\"\n\n def __init__(self, **channels):\n super(ContextTexture, self).__init__()\n self.up_conv = nn.Conv2d(channels['up'], channels['main'], kernel_size=1)\n self.main_conv = nn.Conv2d(channels['main'], channels['main'], kernel_size=1)\n\n def forward(self, up, main):\n up = self.up_conv(up)\n main = self.main_conv(main)\n _, _, H, W = main.size()\n res = F.upsample(up, scale_factor=2, mode='bilinear')\n if res.size(2) != main.size(2) or res.size(3) != main.size(3):\n res = res[:, :, 0:H, 0:W]\n res = res * main\n return res\n\nclass AtomMulFPNIoUNet(nn.Module):\n \"\"\" Network module for IoU prediction. Refer to the paper for an illustration of the architecture.\"\"\"\n def __init__(self, input_dim=(128,256), pred_input_dim=(256,256),\n pred_inter_dim=(256,256),\n fpn_inter_dim=None,\n share_rt=False):\n super().__init__()\n # _r for reference, _t for test\n # =============== FPN ===============\n if fpn_inter_dim is None:\n fpn_inter_dim = input_dim\n add_conv5 = len(input_dim) == 3\n self.add_conv5 = add_conv5\n if add_conv5:\n self.conv5_lat_r = nn.Conv2d(input_dim[2], fpn_inter_dim[2], kernel_size=1)\n if share_rt:\n self.conv5_lat_t = self.conv5_lat_r\n else:\n self.conv5_lat_t = nn.Conv2d(input_dim[2], fpn_inter_dim[2], kernel_size=1)\n\n self.conv5_ct_r = ContextTexture(up=fpn_inter_dim[2], main=input_dim[1])\n if share_rt:\n self.conv5_ct_t = self.conv5_ct_r\n else:\n self.conv5_ct_t = ContextTexture(up=fpn_inter_dim[2], main=input_dim[1])\n\n self.conv4_lat_r = nn.Conv2d(input_dim[1], fpn_inter_dim[1], kernel_size=1)\n if share_rt:\n self.conv4_lat_t = self.conv4_lat_r\n else:\n self.conv4_lat_t = nn.Conv2d(input_dim[1], fpn_inter_dim[1], kernel_size=1)\n\n self.conv4_ct_r = ContextTexture(up=fpn_inter_dim[1], main=input_dim[0])\n if share_rt:\n self.conv4_ct_t = self.conv4_ct_r\n else:\n self.conv4_ct_t = ContextTexture(up=fpn_inter_dim[1], main=input_dim[0])\n # =============== FPN END ===========\n\n self.conv3_1r = conv(input_dim[0], 128, kernel_size=3, stride=1)\n self.conv3_1t = conv(input_dim[0], 256, kernel_size=3, stride=1)\n\n self.conv3_2t = conv(256, pred_input_dim[0], kernel_size=3, stride=1)\n\n self.prroi_pool3r = PrRoIPool2D(3, 3, 1/8)\n self.prroi_pool3t = PrRoIPool2D(5, 5, 1/8)\n\n self.fc3_1r = conv(128, 256, kernel_size=3, stride=1, padding=0)\n\n self.conv4_1r = conv(input_dim[1], 256, kernel_size=3, stride=1)\n self.conv4_1t = conv(input_dim[1], 256, kernel_size=3, stride=1)\n\n self.conv4_2t = conv(256, pred_input_dim[1], kernel_size=3, stride=1)\n\n self.prroi_pool4r = PrRoIPool2D(1, 1, 1 / 16)\n self.prroi_pool4t = PrRoIPool2D(3, 3, 1 / 16)\n\n self.fc34_3r = conv(256 + 256, pred_input_dim[0], kernel_size=1, stride=1, padding=0)\n self.fc34_4r = conv(256 + 256, pred_input_dim[1], kernel_size=1, stride=1, padding=0)\n\n self.fc3_rt = LinearBlock(pred_input_dim[0], pred_inter_dim[0], 5)\n self.fc4_rt = LinearBlock(pred_input_dim[1], pred_inter_dim[1], 3)\n\n self.iou_predictor = nn.Linear(pred_inter_dim[0]+pred_inter_dim[1], 1, bias=True)\n\n # Init weights\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d) or isinstance(m, nn.Linear):\n nn.init.kaiming_normal_(m.weight.data, mode='fan_in')\n if m.bias is not None:\n m.bias.data.zero_()\n\n def forward(self, feat1, feat2, bb1, proposals2):\n assert feat1[0].dim() == 5, 'Expect 5 dimensional feat1'\n\n num_test_images = feat2[0].shape[0]\n batch_size = feat2[0].shape[1]\n\n # Extract first train sample\n feat1 = [f[0,...] for f in feat1]\n bb1 = bb1[0,...]\n\n # Get modulation vector\n filter = self.get_filter(feat1, bb1)\n\n feat2 = [f.view(batch_size * num_test_images, f.shape[2], f.shape[3], f.shape[4]) for f in feat2]\n iou_feat = self.get_iou_feat(feat2)\n\n filter = [f.view(1, batch_size, -1).repeat(num_test_images, 1, 1).view(batch_size*num_test_images, -1) for f in filter]\n\n proposals2 = proposals2.view(batch_size*num_test_images, -1, 4)\n pred_iou = self.predict_iou(filter, iou_feat, proposals2)\n return pred_iou.view(num_test_images, batch_size, -1)\n\n def predict_iou(self, filter, feat2, proposals):\n fc34_3_r, fc34_4_r = filter\n c3_t, c4_t = feat2\n\n batch_size = c3_t.size()[0]\n\n # Modulation\n c3_t_att = c3_t * fc34_3_r.view(batch_size, -1, 1, 1)\n c4_t_att = c4_t * fc34_4_r.view(batch_size, -1, 1, 1)\n\n # Add batch_index to rois\n batch_index = torch.Tensor([x for x in range(batch_size)]).view(batch_size, 1).to(c3_t.device)\n\n # Push the different rois for the same image along the batch dimension\n num_proposals_per_batch = proposals.shape[1]\n\n # input proposals2 is in format xywh, convert it to x0y0x1y1 format\n proposals_xyxy = torch.cat((proposals[:, :, 0:2], proposals[:, :, 0:2] + proposals[:, :, 2:4]), dim=2)\n\n # Add batch index\n roi2 = torch.cat((batch_index.view(batch_size, -1, 1).expand(-1, num_proposals_per_batch, -1),\n proposals_xyxy), dim=2)\n roi2 = roi2.view(-1, 5).to(proposals_xyxy.device)\n\n roi3t = self.prroi_pool3t(c3_t_att, roi2)\n roi4t = self.prroi_pool4t(c4_t_att, roi2)\n\n fc3_rt = self.fc3_rt(roi3t)\n fc4_rt = self.fc4_rt(roi4t)\n\n fc34_rt_cat = torch.cat((fc3_rt, fc4_rt), dim=1)\n\n iou_pred = self.iou_predictor(fc34_rt_cat).view(batch_size, num_proposals_per_batch)\n\n return iou_pred\n\n def get_filter(self, feat1, bb1):\n if self.add_conv5:\n feat3_r, feat4_r, feat5_r = feat1\n else:\n feat3_r, feat4_r = feat1\n\n # FPN\n if self.add_conv5:\n feat4_r = self.conv5_ct_r(self.conv5_lat_r(feat5_r), feat4_r)\n feat3_r = self.conv4_ct_r(self.conv4_lat_r(feat4_r), feat3_r)\n\n c3_r = self.conv3_1r(feat3_r)\n\n # Add batch_index to rois\n batch_size = bb1.size()[0]\n batch_index = torch.Tensor([x for x in range(batch_size)]).view(batch_size, 1).to(bb1.device)\n\n # input bb is in format xywh, convert it to x0y0x1y1 format\n bb1 = bb1.clone()\n bb1[:, 2:4] = bb1[:, 0:2] + bb1[:, 2:4]\n roi1 = torch.cat((batch_index, bb1), dim=1)\n\n roi3r = self.prroi_pool3r(c3_r, roi1)\n\n c4_r = self.conv4_1r(feat4_r)\n roi4r = self.prroi_pool4r(c4_r, roi1)\n\n fc3_r = self.fc3_1r(roi3r)\n\n # Concatenate from block 3 and 4\n fc34_r = torch.cat((fc3_r, roi4r), dim=1)\n\n fc34_3_r = self.fc34_3r(fc34_r)\n fc34_4_r = self.fc34_4r(fc34_r)\n\n return fc34_3_r, fc34_4_r\n\n def get_iou_feat(self, feat2):\n if self.add_conv5:\n feat3_t, feat4_t, feat5_t = feat2\n else:\n feat3_t, feat4_t = feat2\n # FPN\n if self.add_conv5:\n feat4_t = self.conv5_ct_t(self.conv5_lat_t(feat5_t), feat4_t)\n feat3_t = self.conv4_ct_t(self.conv4_lat_t(feat4_t), feat3_t)\n #\n\n c3_t = self.conv3_2t(self.conv3_1t(feat3_t))\n c4_t = self.conv4_2t(self.conv4_1t(feat4_t))\n\n return c3_t, c4_t\n","sub_path":"ltr/models/bbreg/atom_mul_fpn_iou_net.py","file_name":"atom_mul_fpn_iou_net.py","file_ext":"py","file_size_in_byte":8448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"408270964","text":"#coding = 'utf-8'\nimport urllib,re\nfrom bs4 import BeautifulSoup #解析源码\nimport urllib.request\nimport html.parser\n\n#获取源码\ndef getContentOrComment(Url):\n header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0'}\n\n request = urllib.request.Request(url=Url, headers=header)\n try:\n response = urllib.request.urlopen(request) # 打开网址\n text = response.read().decode('UTF-8') # 获取所有的源码\n except Exception as e:\n text = None\n #print(text)\n return text\n#文章地址\narticleUrl = 'http://www.qiushibaike.com/textnew/page/%d'\n#评论地址\ncommentUrl = 'http://www.qiushibaike.com/article/%s'\npage = 0\nwhile True:\n raw = input('点击enter查看或者输入exit退出,请输入你的选择:')\n if raw == 'exit':\n break #跳出循环\n page += 1\n Url = articleUrl % page\n\n\n articlePage = getContentOrComment(Url)\n articleFloor = 1\n #print(articlePage)\n\n #print('kkkk')\n #获取段子内容\n soupArticle = BeautifulSoup(articlePage,'html.parser')#解析网页\n #print('gggg')\n #print(soupArticle)\n for string in soupArticle.find_all(attrs = \"article block untagged mb15\"):\n commentId = str(string.get('id')).strip()[11:]\n #print('ffff')\n #print(commentId)\n print(articleFloor,'.',string.find(attrs = \"content\").get_text().strip())\n articleFloor += 1\n\n #获取评论\n commentPage = getContentOrComment(commentUrl % commentId)\n if commentPage is None:\n continue\n soupComment = BeautifulSoup(commentPage,'hmtl.parser')#解析网页\n commentFloor = 1\n for comment in soupComment.find_all(attrs=\"body\"):\n #print('ffff')\n # print(commentId)\n print(' ',commentFloor, '楼回复',\n comment.get_text().strip())\n commentFloor += 1","sub_path":"project/Python爬虫/糗事百科/糗事百科.py","file_name":"糗事百科.py","file_ext":"py","file_size_in_byte":1926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"210555568","text":"#! /usr/bin/python3\n\nimport argparse\nfrom random import randint\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n '-c', type=int, default=3, help='number of coordinates')\nparser.add_argument(\n '-d', type=int, default=3, help='number of decimal places')\nparser.add_argument(\n '-b', type=int, default=10, help='coordinate bound')\nparser.add_argument(\n '-n', type=int, help='number of points')\nparser.add_argument(\n 'output_name', metavar='output', type=str,\n help='output file name')\nargs = parser.parse_args()\n\n\ndef create_point_string(cd, bd, bdp, dp):\n coords = [ float(randint(-bd * 10**dp, bd * 10**dp)) / float(10**dp)\n for _ in range(cd) ]\n return \" \".join( (\"{\" + \":+0{}.{}f\".format(1+bdp+1+dp,dp) + \"}\").format(c) for c in coords ) + \"\\n\"\n\n\nwith open(args.output_name, 'w') as output:\n output.writelines( create_point_string(args.c, args.b, len(str(args.b)), args.d)\n for _ in range(args.n) )\n","sub_path":"create_cell_file.py","file_name":"create_cell_file.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"135638750","text":"from django.core.management.base import BaseCommand\nimport json\nfrom constance import config\nimport logging\n\nlog = logging.getLogger(__name__)\n\nclass Command(BaseCommand):\n help = u'Upload settings from JSON to django-constance (usage ./manage.py apply_settings)'\n\n def add_arguments(self, parser):\n parser.add_argument('settings_file', type=str)\n\n def handle(self, *args, **options):\n settings_file = options['settings_file']\n log.debug('Settings file: %s' % settings_file)\n\n log.debug('Begin')\n with open(settings_file) as f:\n settings = json.loads(f.read())\n for k,v in settings.items():\n log.debug('%s = %s' % (k,v))\n setattr(config, k, v)\n\n\n log.debug('Done')\n","sub_path":"constance/management/commands/apply_settings.py","file_name":"apply_settings.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"366273907","text":"from unet_model import UNet2\nimport torch\nfrom torch import nn\nfrom torchvision import models, transforms, datasets\nfrom torch.utils.data import DataLoader, Dataset\nimport os\nimport cv2\nimport numpy as np\nfrom PIL import Image\nfrom tqdm import tqdm\nfrom torch.utils.tensorboard import SummaryWriter\nwriter = SummaryWriter('runs')\n\n\nclass DocSegDataset(Dataset):\n def __init__(self, root):\n self.root = root\n self.ids = os.listdir('{}/input'.format(root))\n self.transform_color = transforms.Compose([\n transforms.Resize((256, 256)),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[\n 0.229, 0.224, 0.225])\n ])\n self.transform_gray = transforms.Compose([\n transforms.Resize((256, 256)),\n transforms.ToTensor()\n ])\n\n def __len__(self):\n return len(self.ids)\n\n def __getitem__(self, idx):\n color = Image.open('{}/input/{}'.format(self.root, self.ids[idx]))\n color = self.transform_color(color)\n gray = Image.open('{}/unet/{}'.format(self.root,\n self.ids[idx])).convert('L')\n gray = self.transform_gray(gray)\n return color, gray, '{}/input/{}'.format(self.root, self.ids[idx])\n\n\ndevice = torch.device('cuda')\nmodel = UNet2(3, 1)\nmodel.to(device)\ncriterion = nn.BCELoss().to(device)\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)\ndataset = DocSegDataset('data')\ndata = DataLoader(dataset, batch_size=12, shuffle=True, num_workers=0)\nepoch = 1000\nstep = 0\nfor i in tqdm(range(epoch)):\n print('start epoch: ', i)\n for color, gray, path in data:\n step += 1\n color = color.to(device)\n gray = gray.to(device)\n output = model(color)\n o = (output > 0.5).float()[0]\n output = output.view(-1)\n gray = gray.view(-1)\n loss = criterion(output, gray)\n if step % 1 == 0:\n print('loss: ', loss)\n writer.add_scalar('loss', loss, step)\n c = cv2.imread(path[0])\n h, w = c.shape[:2]\n new_w = 400\n new_h = int(400 * h/w)\n c = cv2.resize(c, (new_w, new_h))\n c = cv2.cvtColor(c, cv2.COLOR_BGR2RGB)\n c = torch.tensor(c, dtype=torch.uint8).permute(2, 0, 1)\n g = cv2.imread(path[0].replace('input', 'unet'))\n g = cv2.resize(g, (new_w, new_h))\n g = cv2.cvtColor(g, cv2.COLOR_BGR2RGB)\n g = torch.tensor(g, dtype=torch.uint8).permute(2, 0, 1)\n _, h, w = o.shape\n refer = np.zeros((h, w, 3))\n for ii in range(h):\n for ij in range(w):\n if o[:, ii, ij] == 1:\n refer[ii, ij, :] = (255, 255, 255)\n refer = cv2.resize(refer, (new_w, new_h))\n # refer = np.resize(refer, (new_h, new_w, 3))\n refer = torch.tensor(refer, dtype=torch.uint8).permute(2, 0, 1)\n combine = torch.cat([c, g, refer], dim=2)\n writer.add_image('image', combine, step)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n torch.save(model.state_dict(), '1.pth')\n","sub_path":"unet.py","file_name":"unet.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"599683291","text":"#!/usr/bin/python2\nfrom __future__ import division\nimport numpy as np\nimport cv2\nimport sys\nimport time\n\nif len(sys.argv) < 2:\n print(\"Please specify a input file\")\n exit(1)\n\n# load the image, crop 10% at the borders, convert it to grayscale, and blur it slightly\nimage = cv2.imread(sys.argv[1])\n\nheight, width, channels = image.shape\nvertical_crop = int(height * 0.02)\nhorizontal_crop = int(width * 0.05)\ncropped = image[vertical_crop: height - vertical_crop, horizontal_crop: width - horizontal_crop]\n\ngray = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)\nblurred = cv2.GaussianBlur(gray, (7, 7), 0)\n\n# apply Canny edge detection using a wide threshold, tight\n# threshold, and automatically determined threshold\ncanny = cv2.Canny(blurred, 225, 250)\n\npixels = canny.size\nedges = (np.asarray(canny) > 0).sum()\nedge_percentage = edges / pixels * 100\n\nprint(edge_percentage)\n\n#cv2.imwrite(str(time.time()) + \"_edges.tif\", canny)\n\nif edge_percentage > 0.04:\n exit(0)\nelse:\n print(\"EMPTY PAGE!\")\n exit(404)\n","sub_path":"scan/is_empty.py","file_name":"is_empty.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"360671313","text":"import datetime\nimport hashlib\nimport json\nfrom flask import Flask, jsonify, request\nimport requests\nfrom urllib.parse import urlparse\nimport sys\n\nclass Blockchain:\n\n def __init__(self):\n self.chain = []\n self.mempool = []\n self.nodes = set()\n self.create_block(proof = 1, previous_hash = '0')\n \n def create_block(self, proof, previous_hash):\n block = {'index': len(self.chain) + 1,\n 'timestamp': str(datetime.datetime.now()),\n 'proof': proof,\n 'previous_hash': previous_hash,\n 'transactions': self.mempool}\n self.mempool = []\n self.chain.append(block)\n if self.replace_chain():\n raise Exception('Houston, we have a bigger chain') \n return block\n \n \n def create_transaction(self, sender, receiver, amount, timestamp):\n should_broadcast = False\n if not timestamp:\n timestamp = str(datetime.datetime.now())\n should_broadcast = True\n transaction = {'timestamp': timestamp,\n 'sender': sender,\n 'receiver': receiver,\n 'amount': amount}\n self.mempool.append(transaction)\n if should_broadcast:\n self.broadcast_transaction(transaction)\n return self.get_previous_block()['index'] + 1\n \n def create_node(self, address):\n parsed_url = urlparse(address)\n self.nodes.add(parsed_url.netloc)\n \n def get_previous_block(self):\n return self.chain[-1]\n \n def proof_of_work(self, previous_proof):\n new_proof = 1\n check_proof = False\n while check_proof is False:\n hash_operation = hashlib.sha256(str(new_proof**2 - previous_proof**2).encode()).hexdigest()\n if hash_operation[:4] == '0000':\n check_proof = True\n else:\n new_proof += 1\n return new_proof\n \n def hash(self, block):\n encoded_block = json.dumps(block, sort_keys = True).encode()\n return hashlib.sha256(encoded_block).hexdigest()\n \n def is_chain_valid(self, chain):\n previous_block = chain[0]\n block_index = 1\n while block_index < len(chain):\n block = chain[block_index]\n if block['previous_hash'] != self.hash(previous_block):\n return False\n previous_proof = previous_block['proof']\n proof = block['proof']\n hash_operation = hashlib.sha256(str(proof**2 - previous_proof**2).encode()).hexdigest()\n if hash_operation[:4] != '0000':\n return False\n previous_block = block\n block_index += 1\n return True\n \n def replace_chain(self):\n longest_chain = None\n max_length = len(self.chain)\n for node in self.nodes:\n response = requests.get(f'http://{node}/chain')\n if response.status_code == 200:\n length = response.json()['length']\n chain = response.json()['chain']\n if length > max_length and self.is_chain_valid(chain):\n max_length = length\n longest_chain = chain\n if longest_chain != None:\n self.chain = longest_chain\n return True\n return False\n \n def broadcast_transaction(self, transaction):\n result = True\n for node in self.nodes:\n response = requests.post(f'http://{node}/chain/transaction', json = transaction)\n if response.status_code != 201:\n result = False\n return result\n \napp = Flask(__name__)\n\nblockchain = Blockchain()\n\n@app.route('/chain/block', methods = ['PUT'])\ndef mine_block():\n previous_block = blockchain.get_previous_block()\n proof = blockchain.proof_of_work(previous_block['proof'])\n try:\n block = blockchain.create_block(proof, blockchain.hash(previous_block))\n except Exception as e:\n return str(e), 409\n response = {'block': block}\n return jsonify(response), 200\n \n@app.route('/chain', methods = ['GET'])\ndef get_chain():\n response = { 'chain': blockchain.chain,\n 'length': len(blockchain.chain)\n }\n return jsonify(response), 200\n \n@app.route('/chain/is_valid', methods = ['GET'])\ndef is_valid():\n return jsonify(blockchain.is_chain_valid(blockchain.chain)), 200\n\n@app.route('/chain/transaction', methods = ['POST'])\ndef post_transaction():\n transaction_keys = ['sender', 'receiver', 'amount']\n json = request.get_json()\n print(\"JSON: \" + str(json))\n if not all (key in json for key in transaction_keys):\n return 'Houston, we have a problem', 400\n sender = json['sender']\n receiver = json['receiver']\n amount = json['amount']\n timestamp = json['timestamp'] if 'timestamp' in json else ''\n return jsonify(blockchain.create_transaction(sender, receiver, amount, timestamp)), 201\n\n@app.route('/chain/nodes', methods = ['POST'])\ndef post_node():\n node_keys = ['nodes']\n json = request.get_json()\n if not all (key in json for key in node_keys):\n return 'Houston, we have a problem', 400\n nodes = json['nodes']\n for node in nodes:\n blockchain.create_node(node)\n return jsonify(len(blockchain.nodes)), 201\n \n@app.route('/chain', methods = ['PUT'])\ndef replace_chain():\n is_chain_replaced = blockchain.replace_chain()\n if is_chain_replaced:\n response = {'message': 'Chain replaced',\n 'chain': blockchain.chain\n } \n else: \n response = {'message': 'Chain was not replaced',\n 'chain': blockchain.chain\n }\n return jsonify(response), 200\n\napp.run(port=sys.argv[1])","sub_path":"blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":5759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"499942300","text":"#!/usr/bin/env python\nimport sys, time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom map import Map\nfrom vessel import Vessel\nfrom utils import Controller, PriorityQueue, eucledian_path_length\nfrom matplotlib2tikz import save as tikz_save\n\nimport dubins\n\nBIGVAL = 10000.\n\nclass HybridAStar(Controller):\n def __init__(self, x0, xg, the_map, replan=False):\n self.start = x0[0:3]\n self.goal = xg[0:3]\n\n self.world = None\n\n self.graph = SearchGrid(the_map, [1.0, 1.0, 25.0/360.0], N=3, parent=self)\n # :todo: Should be the_world?\n self.map = the_map\n self.eps = 5.0\n self.to_be_updated = True\n self.replan = replan\n self.path_found = False\n\n self.gridsize = the_map.get_gridsize()\n\n self.turning_radius = 20.0\n self.step_size = 1.5*the_map.get_gridsize()\n self.dubins_expansion_constant = 50\n\n def update(self, vobj, world, vessel_object):\n if self.to_be_updated:\n\n vessel_object.waypoints = self.search(vessel_object)\n\n self.to_be_updated = False\n #self.map.disable_safety_region()\n\n def draw(self, axes, n, fcolor, ecolor):\n pass\n\n def visualize(self, fig, axarr, t, n):\n pass\n\n def search(self, vobj):\n \"\"\"The Hybrid State A* search algorithm.\"\"\"\n\n tic = time.process_time()\n\n get_grid_id = self.graph.get_grid_id\n\n frontier = PriorityQueue()\n frontier.put(list(self.start), 0)\n came_from = {}\n cost_so_far = {}\n\n came_from[tuple(self.start)] = None\n cost_so_far[get_grid_id(self.start)] = 0\n\n dubins_path = False\n\n num_nodes = 0\n\n while not frontier.empty():\n current = frontier.get()\n\n if num_nodes % self.dubins_expansion_constant == 0:\n dpath,_ = dubins.path_sample(current, self.goal, self.turning_radius, self.step_size)\n if not self.map.is_occupied_discrete(dpath):\n # Success. Dubins expansion possible.\n self.path_found = True\n dubins_path = True\n break\n\n if np.linalg.norm(current[0:2] - self.goal[0:2]) < self.eps \\\n and np.abs(current[2]-self.goal[2]) < np.pi/8:\n self.path_found = True\n break\n\n for next in self.graph.neighbors(current, vobj.model.est_r_max):\n new_cost = cost_so_far[get_grid_id(current)] + \\\n self.graph.cost(current, next)\n\n if get_grid_id(next) not in cost_so_far or new_cost < cost_so_far[get_grid_id(next)]:\n cost_so_far[get_grid_id(next)] = new_cost\n priority = new_cost + heuristic(self.goal, next)\n frontier.put(list(next), priority)\n came_from[tuple(next)] = current\n\n num_nodes += 1\n # Reconstruct path\n path = [current]\n while tuple(current) != tuple(self.start):\n current = came_from[tuple(current)]\n path.append(current)\n\n if dubins_path:\n path = np.array(path[::-1] + dpath)\n else:\n path = np.array(path[::-2])\n\n print(\"Hybrid A-star CPU time: %.3f. Nodes expanded: %d\" % ( time.process_time() - tic, num_nodes))\n #print(self.start)\n\n return np.copy(path)\n\n\ndef heuristic(a, b):\n \"\"\"The search heuristics function.\"\"\"\n return np.linalg.norm(a-b)\n\nclass SearchGrid(object):\n \"\"\"General purpose N-dimentional search grid.\"\"\"\n def __init__(self, the_map, gridsize, N=2, parent=None):\n self.N = N\n self.grid = the_map.get_discrete_grid()\n self.map = the_map\n self.gridsize = gridsize\n self.gridsize[0] = the_map.get_gridsize()\n self.gridsize[1] = the_map.get_gridsize()\n dim = the_map.get_dimension()\n\n self.width = dim[0]\n self.height = dim[1]\n\n \"\"\"\n In the discrete map, an obstacle has the value '1'.\n We multiply the array by a big number such that the\n grid may be used as a costmap.\n \"\"\"\n self.grid *= BIGVAL\n\n\n def get_grid_id(self, state):\n \"\"\"Returns a tuple (x,y,psi) with grid positions.\"\"\"\n return (int(state[0]/self.gridsize[0]),\n int(state[1]/self.gridsize[1]),\n int(state[2]/self.gridsize[2]))\n\n def in_bounds(self, state):\n return 0 <= state[0] < self.width and 0 <= state[1] < self.height\n\n def cost(self, a, b):\n #if b[0] > self.width or b[1] > self.height:\n # return 0\n return np.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)#self.grid[int(b[0]/self.gridsize[0]), int(b[1]/self.gridsize[1])]\n\n def passable(self, state):\n # TODO Rename or change? Only returns true if object is _inside_ obstacle\n # Polygons add safety zone by default now.\n\n if state[0] > self.width or state[1] > self.height:\n return True\n\n return self.grid[int(state[0]/self.gridsize[0]),\n int(state[1]/self.gridsize[1])] < BIGVAL\n\n def neighbors(self, state, est_r_max):\n \"\"\"\n Applies rudder commands to find the neighbors of the given state.\n\n For the Viknes 830, the maximum rudder deflection is 15 deg.\n \"\"\"\n step_length = 2.5*self.gridsize[0]\n avg_u = 3.5\n Radius = 2.5*avg_u / est_r_max\n dTheta = step_length / Radius\n #print(Radius, dTheta*180/np.pi)\n\n trajectories = np.array([[step_length*np.cos(dTheta), step_length*np.sin(dTheta), dTheta],\n [step_length, 0., 0.],\n [step_length*np.cos(dTheta), -step_length*np.sin(dTheta), -dTheta]])\n\n #print(trajectories)\n results = []\n for traj in trajectories:\n newpoint = state + np.dot(Rz(state[2]), traj)\n if self.passable(newpoint):\n results.append(newpoint)\n\n #results = filter(self.in_bounds, results)\n\n return results\n\ndef Rz(theta):\n return np.array([[np.cos(theta), -np.sin(theta), 0],\n [np.sin(theta), np.cos(theta), 0],\n [0 , 0 , 1]])\n\nif __name__ == \"__main__\":\n mymap = Map(\"s1\", gridsize=1.0, safety_region_length=4.5)\n\n x0 = np.array([0, 0, np.pi/2, 3.0, 0.0, 0])\n xg = np.array([100, 100, np.pi/4])\n myvessel = Vessel(x0, xg, 0.05, 0.5, 1, [], True, 'viknes')\n\n myastar = HybridAStar(x0, xg, mymap)\n\n myastar.update(myvessel)\n\n fig = plt.figure()\n ax = fig.add_subplot(111,autoscale_on=False)\n ax.plot(myvessel.waypoints[:,0],\n myvessel.waypoints[:,1],\n '-')\n\n #ax.plot(x0[0], x0[1], 'bo')\n ax.plot(xg[0], xg[1], 'ro')\n myvessel.draw_patch(ax, myvessel.x, fcolor='b')\n\n #nonpass = np.array(nonpassable)\n #ax.plot(nonpass[:,0], nonpass[:,1], 'rx')\n\n ax.axis('equal')\n ax.axis('scaled')\n ax.axis([-10, 160, -10, 160])\n mymap.draw(ax, 'g', 'k')\n ax.grid()\n\n tikz_save('../../../latex/fig/testfig2.tikz',\n figureheight='8cm',\n figurewidth='8cm',\n textsize=11)\n\n plt.show()\n","sub_path":"ASV Simulator/ctrl_hybrid_astar.py","file_name":"ctrl_hybrid_astar.py","file_ext":"py","file_size_in_byte":7259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"98778575","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Acceso a los sensores de linea del S2.\"\"\"\n\nfrom .HS2LineSensors import HS2LineSensors\n\nclass S2LineSensors:\n \"\"\"Clase de acceso a los sensores de linea del S2.\"\"\"\n\n def __init__( self, s2 ):\n \"\"\"\n Corresponde al constructor de la clase.\n\n @type s2: L{Scribbler2}\n @param s2: referencia al S2 que lo contiene\n \"\"\"\n self.s2 = s2\n\n def getLeftLine( self ):\n \"\"\"\n Obtiene el valor del sensor de linea izquierdo.\n\n @rtype: integer\n @return: valor del sensor de linea izquierdo\n \"\"\"\n try:\n self.s2.lock()\n packet = self.s2.makeS2Packet( 74 )\n self.s2.sendS2Command( packet, 0 )\n return self.s2.getUInt8Response()\n except Exception as e:\n raise\n finally:\n self.s2.unlock()\n\n def getRightLine( self ):\n \"\"\"\n Obtiene el valor del sensor de linea derecho.\n\n @rtype: integer\n @return: valor del sensor de linea derecho\n \"\"\"\n try:\n self.s2.lock()\n packet = self.s2.makeS2Packet( 75 )\n self.s2.sendS2Command( packet, 0 )\n return self.s2.getUInt8Response()\n except Exception as e:\n raise\n finally:\n self.s2.unlock()\n\n def getAllLines( self ):\n \"\"\"\n Obtiene el valor de los sensores de linea del S2.\n\n @rtype: L{HS2LineSensors}\n @return: el valor de los sensores de linea del S2\n \"\"\"\n try:\n self.s2.lock()\n packet = self.s2.makeS2Packet( 76 )\n self.s2.sendS2Command( packet, 0 )\n return HS2LineSensors( self.s2.getUInt8Response(), self.s2.getUInt8Response() )\n except Exception as e:\n raise\n finally:\n self.s2.unlock()\n\n def getLineEx( self, side, thres):\n \"\"\"\n Obtiene el valor extendido de un sensor de linea.\n\n @type side: integer\n @param side: el sensor de linea (0 o 1)\n @type thres: byte\n @param thres: umbral para la lectura del valor del sensor\n @rtype: integer\n @return: valor extendido del sensor de linea\n \"\"\"\n try:\n self.s2.lock()\n packet = self.s2.makeS2Packet( 173 )\n packet[1] = side & 0x01\n packet[2] = 0\n packet[3] = thres & 0xFF\n self.s2.sendS2Command( packet, 0 )\n return self.s2.getUInt8Response()\n except Exception as e:\n raise\n finally:\n self.s2.unlock()\n","sub_path":"rcr/robots/scribbler2/S2LineSensors.py","file_name":"S2LineSensors.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"112958606","text":"import markovify\n\nwith open('vows.txt', 'r') as f:\n text = f.read()\n\nvow_model = markovify.Text(text)\n\ncount = 0\nfor i in range(5):\n sentence = vow_model.make_short_sentence(100)\n limit = len(sentence.split(' '))\n count += limit\n print(limit, sentence)\n\nprint(count)\n'''\nNicole,\n\nYou're the light in my life, my best friend, \n\nWe've already been together half of our lives, my love for you is endless,\nI can't wait to spend the rest of our lives together. I vow to always be by \nyour side with every adventure, \n\n\n'''\n\nimport pandas as pd\n\ndf = pd.read_csv('songdata.csv')\n\nqueen = df[df['artist'] == 'Styx']\n\n# for i in df.artist.unique():\n# print(i)\n# print(queen.text)\n\nprint('*'*40)\nqueen_vow = markovify.Text(df.text)\n\nfor i in range(5):\n sentence = queen_vow.make_short_sentence(100)\n print(len(sentence.split(' ')), sentence)\n\n","sub_path":"markov_vows/vows.py","file_name":"vows.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"137946321","text":"import pytest\nfrom faker import Faker\n\nfrom pages.basket_page import BasketPage\nfrom pages.login_page import LoginPage\nfrom pages.product_page import ProductPage\n\nlink_coders = \"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/\"\nlink_stars = \"http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/\"\nlink_registration = \"http://selenium1py.pythonanywhere.com/en-gb/accounts/login/\"\n\n\n@pytest.mark.need_review\ndef test_guest_can_add_product_to_basket(browser):\n page = ProductPage(browser, link_coders)\n page.open()\n page.add_to_cart()\n page.should_be_basket_total()\n page.check_basket_total()\n page.should_be_success_message()\n page.check_product_name_in_success_message()\n\n\n@pytest.mark.skip\ndef test_guest_cant_see_success_message_after_adding_product_to_basket(browser):\n page = ProductPage(browser, link_coders)\n page.open()\n page.add_to_cart()\n page.should_not_be_success_message()\n\n\ndef test_guest_cant_see_success_message(browser):\n page = ProductPage(browser, link_coders)\n page.open()\n page.should_not_be_success_message()\n\n\n@pytest.mark.skip\ndef test_message_disappeared_after_adding_product_to_basket(browser):\n page = ProductPage(browser, link_coders)\n page.open()\n page.add_to_cart()\n page.should_disappear_success_message()\n\n\n@pytest.mark.login\nclass TestLoginFromProductPage:\n def test_guest_should_see_login_link_on_product_page(self, browser):\n page = ProductPage(browser, link_stars)\n page.open()\n page.should_be_login_link()\n\n @pytest.mark.need_review\n def test_guest_can_go_to_login_page_from_product_page(self, browser):\n page = ProductPage(browser, link_stars)\n page.open()\n page.go_to_login_page()\n login_page = LoginPage(browser, browser.current_url)\n login_page.should_be_login_page()\n\n\n@pytest.mark.need_review\ndef test_guest_cant_see_product_in_basket_opened_from_product_page(browser):\n page = ProductPage(browser, link_stars)\n page.open()\n page.go_to_basket_page()\n basket_page = BasketPage(browser, browser.current_url)\n basket_page.should_be_basket_page()\n basket_page.should_be_empty()\n basket_page.should_be_message_that_basket_is_empty()\n\n\nclass TestUserAddToBasketFromProductPage:\n @pytest.fixture(scope=\"function\", autouse=True)\n def setup(self, browser):\n page = LoginPage(browser, link_registration)\n fake = Faker('en-US')\n femail = fake.ascii_free_email()\n fpassword = fake.password(length=10, special_chars=False, digits=True, upper_case=True, lower_case=True)\n page.open()\n page.register_new_user(femail, fpassword)\n page.should_be_authorized_user()\n\n @pytest.mark.need_review\n def test_users_can_add_product_to_basket(self, browser):\n page = ProductPage(browser, link_coders)\n page.open()\n page.add_to_cart()\n page.should_be_basket_total()\n page.should_be_success_message()\n expected_price = page.get_product_price()\n actual_price = page.get_basket_total()\n expected_product_name = page.get_product_name()\n actual_product_name = page.get_product_name_in_success_message()\n assert expected_product_name == actual_product_name, \\\n f'Expected name \"{expected_product_name}\", but got \"{actual_product_name}\"'\n assert expected_price == actual_price, \\\n f'Expected price \"{expected_price}\", but got \"{actual_price}\"'\n\n def test_users_cant_see_success_message(self, browser):\n page = ProductPage(browser, link_coders)\n page.open()\n page.should_not_be_success_message()\n","sub_path":"test_product_page.py","file_name":"test_product_page.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"398748853","text":"'''\n Listas Aninhadas\n Tarefa\n Dados os nomes e as notas de cada estudante em uma disciplina de física, numa\n classe com N estudantes, armazene-os em uma lista aninhada e imprima o nome do\n estudante com segundo menor nota.\n\n Note: Se houver múltiplos estudantes com a mesma nota, a order deve ser \n alfabética pelos nomes e imprima cada nome em uma linha.\n\n Formato de Entrada\n A primeira linha contém um inteiro representando o número de estudantes. \n As linhas subsequentes descrevem cada estudante de duas em duas linhas; \n A primeira linha é o nome, e a segunda é a nota.\n\n Restrições\n Sempre haverá um ou mais estudantes com a segunda nota mais baixa.\n\n Formato de Saída\n Imprima o nome do estudante que tirou a segunda menor nota em Física; se tiver\n mais de um estudante imprima os nomes em ordem alfabética pelos nomes onde cada \n linha terá um nome.\n\n Exemplo de Entrada 0\n 5\n Harry\n 37.21\n Berry\n 37.21\n Tina\n 37.2\n Akriti\n 41\n Harsh\n 39\n\n Exemplo de Saída 0\n Berry\n Harry\n\n Explicação \n Há 5 estudantes na classe cujo os nomes e notas são agregados para contruir a \n seguinte lista aninhada:\n\n students = \n [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], \n ['Harsh', 39]]\n\n A menor nota (37.2) pertence à Tina. A Segunda menor (37.21) nota pertence a \n Harry e Berry, assim nós temos de ordenar os nomes em ordem alfabética e \n imprimí-los linha a linha.\n'''\n\nN = int(input(\"Informe a quantidade de alunos: \"))\n\nstudents = []\nfor i in range(2*N):\n students.append(input(\"Informe o nome e a nota do aluno\").split())\n\ngrades = {}\nfor j in range(0, len(students), 2):\n grades[students[j][0]] = float(students[j + 1][0])\n\nresult = []\nnum_to_match = sorted(set(grades.values()))[1]\nfor pupil in grades.keys():\n if grades[pupil] == num_to_match:\n result.append(pupil)\n \nfor k in sorted(result):\n print (k)","sub_path":"Exercicios/Unidade II/lista-aninhada.py","file_name":"lista-aninhada.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"142308898","text":"# HSLU\n#\n# Created by Thomas Koller on 05.09.18\n#\nimport logging\nfrom jass.base.const import NORTH, next_player\nfrom jass.arena.play_game_strategy import PlayGameStrategy\n\n\nclass PlayNrRoundsStrategy(PlayGameStrategy):\n \"\"\"\n Play a specific number of rounds for one game. The first dealer is always NORTH, so to make the games fair,\n the number of rounds should be a multiple of 4.\n \"\"\"\n def __init__(self, nr_rounds: int):\n \"\"\"\n Initialise.\n Args:\n nr_rounds: The number of rounds to play.\n \"\"\"\n self._nr_rounds = nr_rounds\n self._logger = logging.getLogger(__name__)\n\n def play_game(self, arena) -> None:\n \"\"\"\n Play a game for a number of rounds and determine the winners and points.\n Args:\n arena: the arena for which to play the game.\n\n \"\"\"\n points_team_0 = 0\n points_team_1 = 0\n\n dealer = NORTH\n for nr_rounds in range(self._nr_rounds):\n arena.play_round(dealer)\n points_team_0 += arena.current_rnd.points_team_0\n points_team_1 += arena.current_rnd.points_team_1\n dealer = next_player[dealer]\n\n delta_points = (points_team_0 - points_team_1)\n\n self._logger.info('Game: Team 0: {}, Team 1: {}'.format(points_team_0, points_team_1))\n\n if points_team_0 > points_team_1:\n arena.add_win_team_0(delta_points)\n elif points_team_1 > points_team_0:\n arena.add_win_team_1(delta_points)\n else:\n arena.add_draw()\n","sub_path":"source/jass/arena/play_game_nr_rounds_strategy.py","file_name":"play_game_nr_rounds_strategy.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"62481937","text":"\"\"\"\nCreated by Koprvhdix on 17/05/05\n\"\"\"\nimport tensorflow as tf\nfrom tensorflow.contrib import rnn\n\n\nclass ModelLSTM(object):\n def __init__(self, n_input, n_step, n_classes):\n self.n_input = n_input\n self.n_step = n_step\n self.n_hidden = 1024\n self.n_classes = n_classes\n self.learning_rate = 0.001\n\n self.data = tf.placeholder(\"float\", [None, self.n_step, self.n_input])\n self.label = tf.placeholder(\"float\", [None, self.n_classes])\n weights = tf.Variable(tf.random_normal([self.n_hidden, self.n_classes]))\n biases = tf.Variable(tf.random_normal([self.n_classes]))\n\n data = tf.transpose(self.data, [1, 0, 2])\n data = tf.reshape(data, [-1, self.n_input])\n data = tf.split(data, self.n_step, 0)\n\n lstm_cell = rnn.LSTMCell(self.n_hidden, forget_bias=1.0, use_peepholes=True)\n outputs, states = rnn.static_rnn(lstm_cell, data, dtype=tf.float32)\n\n self.output = tf.matmul(outputs[-1], weights) + biases\n self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self.output, labels=self.label))\n self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate).minimize(self.cost)\n correct_pred = tf.equal(tf.argmax(self.output, 1), tf.argmax(self.label, 1))\n self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n","sub_path":"classification/model_lstm.py","file_name":"model_lstm.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"66727968","text":"import socket\nimport sys\nimport serveroperations\nfrom _thread import *\n\n\ndef server_listen(host,port):\n\tlistaddr = []\n\t'''Creating server with host and port and listening'''\n\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\twhile True:\n\t\ttry:\n\t\t\ts.bind((host,port))\n\t\texcept socket.error as e:\n\t\t\tprint(str(e))\n\n\n\ts.listen(10)\n\tprint('Waiting for connection')\n\n\tdef connected_client(conn,addr):\n\n\t\taddress = str(addr[0]) + str(addr[1])\n\t\tconn.send(str.encode('Welcome, to the cheapchat v0.1a'))\n\n\t\twhile True:\n\n\t\t\tdata = conn.recv(2048) #recieve data in bytecode\n\t\t\tif not data:\n\t\t\t\tbreak\n\t\t\tif check_login_status(address):\n\t\t\t\tconn.sendall(str.encode(get_user_name(address)+\": \"+data))\n\t\t\telse:\n\t\t\t\treply = serveroperations.server_get(data.decode('utf-8'),address)\n\t\t\t\tconn.sendall(str.encode(reply))\n\t\tserveroperations.delete_address_from_user(address)\n\t\tserveroperations.set_user_status(address,0)\n\t\tprint('User {} offline'.format(address))\n\t\tconn.close()\n\n\n\n\twhile 1:\n\t\t'''multithreading work with connections'''\n\t\tconn, addr = s.accept() #New connection WHY IT WORK JUST ONCE???\n\t\tprint('Connected to: ' + addr[0] + ':' + str(addr[1]))\n\t\taddress = str(addr[0]) + str(addr[1])\n\t\tstart_new_thread(connected_client(conn,addr))\n","sub_path":"socketchat/3 chatbasedonsockets/serversocket.py","file_name":"serversocket.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"530694266","text":"from flask_wtf import FlaskForm\nfrom wtforms import StringField, PasswordField, BooleanField, SubmitField,DecimalField,FileField\nimport wtforms\nfrom wtforms.validators import DataRequired\nfrom flask import Flask, render_template,url_for,redirect,abort,request\nimport json,random,sqlite3,hashlib,time,shutil,os\nfrom flask import Flask\nimport app.gen as g\nimport app.gc as GC\nfrom os import listdir\nfrom os.path import isfile, join\n\ngen = g.Gen()\n\nclass LoginForm(FlaskForm):\n login = StringField('Логин',validators=[DataRequired()])\n password = PasswordField('Пароль', validators=[DataRequired()])\n submit = SubmitField('Войти')\n\nclass RegisterForm(FlaskForm):\n name = StringField('Ваше имя',validators=[DataRequired()])\n login = StringField('Логин', validators=[DataRequired()])\n password = PasswordField('Пароль', validators=[DataRequired()])\n submit = SubmitField('Зарегистрироваться')\n\nclass UltimateForm(FlaskForm):\n pixelnoise = BooleanField('Режим 1: Шумно-пиксельный')\n trianglenoise = BooleanField('Режим 2: Шумно-треугольный')\n mirrored = BooleanField('Режим 3: Зеркально-пиксельный')\n mirroredgithub = BooleanField('Режим 4: Зеркально-гитхабный')\n captcha = BooleanField('Режим 5: Генератор капчи')\n pixilise = BooleanField('Режим 6: Пиксилятор фото')\n monopixilise = BooleanField('Режим 7: Черно-белый пиксилятор фото')\n voronoise = BooleanField('Режим 8: Эффект Вороного')\n photo_voronoise = BooleanField('Режим 9: Фото с эффектом Вороного')\n mono_voronoise = BooleanField('Режим 10: Моно эффект вороного')\n size = DecimalField('Шир��на:', validators=[DataRequired()])\n num = StringField('Количество блоков:')\n porog = StringField('Порог:')\n inp = StringField('Строка для рандомизации:')\n finp = FileField('Фотография для модицикаций:')\n submit = SubmitField('Сгенерировать')\n\ndef copy_file_function(list_of_files, directory1, directory2,rename=True):\n global usrs\n auth,name,id,temp = get_usrs(request.remote_addr)\n if id != 0:\n for i in list_of_files:\n address = directory1 + '/' + i\n shutil.copy(address, directory2)\n if rename:\n os.rename(directory2 + '/' + i, directory2 + '/' + str(id)+'_' + i)\n else:\n return\n\ndef get_usrs(ip):\n global usrs\n if ip not in usrs.keys():\n usrs[ip] = [False,'',0,list()]\n return False,'',0,list()\n else:\n return usrs[ip][0],usrs[ip][1],usrs[ip][2],usrs[ip][3]\n\ndef get_works(id):\n global gc\n onlyfiles = [f for f in listdir('../data/usr') if isfile(join('../data/usr', f))]\n temp = list()\n copy_file_function(onlyfiles,'../data/usr','../static',rename=False)\n #gc.add_files(list(map(lambda x:x.split('_')[1],onlyfiles)),'../static')\n gc.add_files(onlyfiles,'../static')\n for i in onlyfiles:\n if str(id) == i.split('_')[0]:\n temp.append('/static/'+i)\n return temp\n\ndef get_hash(passw):\n return hashlib.sha256(passw.encode('utf8')).hexdigest()\n\ndef get_logins(conn):\n return list(map(lambda x: x[0],conn.execute('SELECT login FROM users').fetchall()))\n\ndef get_data(login,conn):\n return list(conn.execute(f'SELECT * FROM users WHERE login=\"{login}\"').fetchall()[0])\n\ndef insert_user(name,login,pasw,conn):\n conn.execute(f'INSERT INTO USERS (name,login,password) VALUES (\\'{name}\\',\\'{login}\\',\\'{get_hash(pasw)}\\')')\n conn.commit()\n\n\napp = Flask(__name__,static_url_path='/static')\napp.debug =True\napp.jinja_env.auto_reload = True\n\napp.config['SECRET_KEY'] = 'yandexlyceum_secret_key'\napp.config['TEMPLATES_AUTO_RELOAD'] = True\ngc = GC.Gc(app.logger)\n\nusrs = dict() # [auth,name,id,temp]\n\n@app.errorhandler(404)\ndef not_found(error):\n return render_template('error.html')\n\n@app.errorhandler(405)\ndef not_found(error):\n return render_template('error.html')\n\n@app.route('/help')\ndef get_help():\n return render_template('help.html')\n\n@app.route('/',methods=['GET','POST'])\ndef main():\n global usrs,gc\n auth,name,id,temp = get_usrs(request.remote_addr)\n form = UltimateForm()\n if form.validate_on_submit():\n if form.num.data == '':\n num = 0\n else:\n try:\n num = int(form.num.data)\n except Exception:\n num = 5\n if form.porog.data == '':\n porog = 127\n else:\n try:\n porog = int(form.porog.data)\n except Exception:\n porog = 127\n fname = ''\n if request.method == 'POST':\n f = request.files['file']\n fname = hashlib.sha256((str(time.time())+str(f.content_length)).encode('utf8')).hexdigest() + '.png'\n f.save('../static/'+fname)\n app.logger.debug(fname)\n gc.add_files([fname],'../static')\n f.close()\n usrs[request.remote_addr][3] = [form.pixelnoise.data,form.trianglenoise.data,form.mirrored.data,form.mirroredgithub.data,form.captcha.data,int(form.size.data),num,form.inp.data,form.pixilise.data,form.monopixilise.data,porog,'../static/'+fname,form.voronoise.data,form.photo_voronoise.data,form.mono_voronoise.data]\n return redirect('/result')\n return render_template('index.html',form=form,name=name,auth=auth)\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n global app,gc\n form = LoginForm()\n if form.validate_on_submit():\n conn = sqlite3.connect('../data/users.db')\n if form.login.data in get_logins(conn):\n data = get_data(form.login.data,conn)\n if get_hash(form.password.data) == data[3]:\n global usrs\n auth, name, id, temp = get_usrs(request.remote_addr)\n auth = True\n id = data[0]\n name = data[1]\n usrs[request.remote_addr] = [auth,name,id,temp]\n conn.close()\n gc.check()\n return redirect('/')\n else:\n conn.close()\n gc.check()\n return render_template('login.html',\n message=\"Неправильный логин или пароль\",\n form=form)\n else:\n conn.close()\n gc.check()\n return render_template('login.html',\n message=\"Неправильный логин или пароль\",\n form=form)\n gc.check()\n return render_template('login.html', form=form)\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n form = RegisterForm()\n if form.validate_on_submit():\n conn = sqlite3.connect('../data/users.db')\n if form.login.data not in get_logins(conn):\n if len(form.password.data) >= 8:\n insert_user(form.name.data,form.login.data,form.password.data,conn)\n conn.close()\n return redirect('/')\n else:\n conn.close()\n return render_template('register.html',\n message=\"Пароль короткий\",\n form=form)\n else:\n conn.close()\n return render_template('register.html',\n message=\"Введенный логин уже кем-то используется\",\n form=form)\n return render_template('register.html', form=form)\n\n@app.route('/logout',methods=['GET','POST'])\ndef logout():\n global usrs\n usrs[request.remote_addr] = [False,'',0,list()]\n return redirect('/')\n\n@app.route('/view',methods=['GET','POST'])\ndef view():\n global temp,gc\n auth, name, id, temp = get_usrs(request.remote_addr)\n if id > 0:\n return render_template('view.html', temp=get_works(id))\n else:\n abort(404)\n\n@app.route('/download',methods=['GET','POST'])\ndef download():\n auth, name, id, temp = get_usrs(request.remote_addr)\n if os.path.isfile(temp):\n pass\n else:\n return render_template('error.html',message='Слишком поздно, генерируйте заного')\n\n@app.route('/result',methods=['GET','POST'])\ndef show():\n global gen,app,usrs,gc\n auth, name, id, temp = get_usrs(request.remote_addr)\n app.logger.debug(gc.stack)\n if temp:\n if type(temp[0]) is bool:\n try:\n if temp[0]:\n gen.gen_random_pixel_noise(temp[5], temp[6], temp[7])\n if temp[1]:\n gen.gen_random_triangle_noise(temp[5], temp[6], temp[7])\n if temp[2]:\n gen.gen_mirrored(temp[5], temp[6], temp[7])\n if temp[3]:\n gen.gen_mirrored_github(temp[5], temp[6], temp[7])\n if temp[4]:\n gen.gen_captcha(temp[5], temp[7])\n if temp[8]:\n gen.gen_pixilise(temp[5],temp[6],temp[11])\n if temp[9]:\n gen.gen_monopixilise(temp[5],temp[6],temp[11],temp[10])\n if temp[12]:\n gen.gen_voronoise(temp[5],temp[6],temp[7])\n if temp[13]:\n gen.gen_photo_voronoise(temp[5],temp[6],temp[11])\n if temp[14]:\n gen.gen_mono_voronoise(temp[5],temp[6],temp[7])\n\n except Exception as e:\n app.logger.debug(e.__class__.__name__)\n gc.check()\n return abort(404)\n usrs[request.remote_addr][3] = gen.names\n copy_file_function(gen.get_fnames(),'../static','../data/usr')\n gc.add_files(gen.get_fnames(),'../static')\n\n gen.names = list()\n gc.check()\n return redirect('/result')\n else:\n gc.check()\n return render_template('result.html',temp=usrs[request.remote_addr][3])\n #return render_template('view.html')\n else:\n abort(404)\n\n@app.route('/delete/<num>',methods=['GET','POST'])\ndef delete(num):\n try:\n os.remove('../data/usr/'+num)\n except Exception as e:\n app.logger.debug(e)\n abort(404)\n return redirect('/view')\n\n\nif __name__ == '__main__':\n gc.clean()\n app.run(port=8080,host='0.0.0.0')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"308066226","text":"\nfrom flask import current_app\nfrom datetime import datetime\nimport MySQLdb\n\nclass Config(object):\n\n def __init__(self):\n self.logger = current_app.logger\n self.configuration = current_app.config\n super(Config, self).__init__()\n\n# logging function\n def log(self, message, msgtype):\n t = datetime.now()\n str_time = t.strftime(\"%Y-%m-%d %H:%M:%S\")\n msg = str_time + \" | \" + message\n if msgtype == 'error':\n self.logger.error(msg)\n else:\n self.logger.info(msg)\n# db connection function\n\n def connect_db(self, db_name):\n\n db = MySQLdb.connect(host=self.configuration['db_server'], user=self.configuration['db_user'],\n passwd=self.configuration['db_password'], db=db_name)\n return db\n","sub_path":"reports-push_pull_api/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"308001410","text":"import IIR_pb2\nimport textwrap\nimport sys\nimport argparse \n\nclass deserializer:\n def __init__(self, metadata):\n self.indent_=0\n self.T_ = textwrap.TextWrapper(initial_indent=' '*self.indent_, width=120,subsequent_indent=' '*self.indent_)\n self.metadata_ = metadata\n \n def visitBuiltinType(self, builtin_type):\n if builtin_type.type_id == 0:\n raise ValueError('Builtin type not supported')\n elif builtin_type.type_id == 1:\n return \"auto\"\n elif builtin_type.type_id == 2:\n return \"bool\"\n elif builtin_type.type_id == 3:\n return \"int\"\n elif builtin_type.type_id == 4:\n return \"float\"\n raise ValueError('Builtin type not supported')\n\n def visitUnaryOperator(self, expr):\n return expr.op+\" \" +self.visitExpr(expr.operand)\n def visitBinaryOperator(self, expr):\n return self.visitExpr(expr.left) + \" \" + expr.op + \" \" + self.visitExpr(expr.right) \n def visitAssignmentExpr(self, expr):\n return self.visitExpr(expr.left) + \" \" + expr.op + \" \" + self.visitExpr(expr.right)\n def visitTernaryOperator(self, expr):\n return \"(\" + self.visitExpr(expr.cond) + \" ? \" + self.visitExpr(expr.left) + \" : \" + self.visitExpr(expr.right) + \")\"\n def visitVarAccessExpr(self, expr):\n return expr.name #+ self.visitExpr(expr.index)\n def visitFieldAccessExpr(self, expr):\n str_ = expr.name +\"[\"\n str_ += \",\".join(str(x) for x in expr.offset)\n str_ += \"]\"\n return str_ \n def visitLiteralAccessExpr(self, expr):\n return expr.value\n # call to external function, like math::sqrt\n def visitFunCallExpr(self, expr):\n return expr.callee + \"(\"+\",\".join(self.visitExpr(x) for x in expr.arguments)+\")\"\n def visitExpr(self,expr):\n if expr.WhichOneof(\"expr\") == \"unary_operator\":\n return self.visitUnaryOperator(expr.unary_operator)\n elif expr.WhichOneof(\"expr\") == \"binary_operator\":\n return self.visitBinaryOperator(expr.binary_operator)\n elif expr.WhichOneof(\"expr\") == \"assignment_expr\":\n return self.visitAssignmentExpr(expr.assignment_expr)\n elif expr.WhichOneof(\"expr\") == \"ternary_operator\":\n return self.visitTernaryOperator(expr.ternary_operator)\n elif expr.WhichOneof(\"expr\") == \"fun_call_expr\":\n return self.visitFunCallExpr(expr.fun_call_expr)\n elif expr.WhichOneof(\"expr\") == \"stencil_fun_call_expr\":\n raise ValueError(\"non supported expression\")\n elif expr.WhichOneof(\"expr\") == \"stencil_fun_arg_expr\":\n raise ValueError(\"non supported expression\")\n elif expr.WhichOneof(\"expr\") == \"var_access_expr\":\n return self.visitVarAccessExpr(expr.var_access_expr)\n elif expr.WhichOneof(\"expr\") == \"field_access_expr\":\n return self.visitFieldAccessExpr(expr.field_access_expr)\n elif expr.WhichOneof(\"expr\") == \"literal_access_expr\":\n return self.visitLiteralAccessExpr(expr.literal_access_expr)\n else:\n raise ValueError(\"Unknown expression\")\n\n def visitVarDeclStmt(self, var_decl):\n str_=\"\"\n if var_decl.type.WhichOneof(\"type\")==\"name\":\n str_+=var_decl.type.name\n elif var_decl.type.WhichOneof(\"type\")==\"builtin_type\":\n str_ += self.visitBuiltinType(var_decl.type.builtin_type)\n else:\n raise ValueError(\"Unknown type \", var_decl.type.WhichOneof(\"type\"))\n str_ += \" \" + var_decl.name\n\n if var_decl.dimension != 0:\n str_ += \"[\"+str(var_decl.dimension)+\"]\"\n\n str_ += var_decl.op\n \n for expr in var_decl.init_list:\n str_ += self.visitExpr(expr)\n\n print(self.T_.fill(str_))\n def visitExprStmt(self,stmt):\n print(self.T_.fill(self.visitExpr(stmt.expr)))\n def visitIfStmt(self, stmt):\n cond = stmt.cond_part\n if cond.WhichOneof(\"stmt\") != \"expr_stmt\":\n raise ValueError(\"Not expected stmt\")\n\n print(self.T_.fill(\"if(\"+self.visitExpr(cond.expr_stmt.expr)+\")\"))\n self.visitBodyStmt(stmt.then_part)\n self.visitBodyStmt(stmt.else_part)\n\n def visitBlockStmt(self, stmt):\n print(self.T_.fill(\"{\"))\n self.indent_+=2\n self.T_.initial_indent=' '*self.indent_\n\n for each in stmt.statements:\n self.visitBodyStmt(each)\n self.indent_-=2\n self.T_.initial_indent=' '*self.indent_\n\n print(self.T_.fill(\"}\"))\n\n def visitBodyStmt(self, stmt):\n if stmt.WhichOneof(\"stmt\") == \"var_decl_stmt\":\n self.visitVarDeclStmt(stmt.var_decl_stmt)\n elif stmt.WhichOneof(\"stmt\") == \"expr_stmt\":\n self.visitExprStmt(stmt.expr_stmt)\n elif stmt.WhichOneof(\"stmt\") == \"if_stmt\":\n self.visitIfStmt(stmt.if_stmt)\n elif stmt.WhichOneof(\"stmt\") == \"block_stmt\":\n self.visitBlockStmt(stmt.block_stmt)\n else:\n raise ValueError(\"Stmt not supported :\" + stmt.WhichOneof(\"stmt\"))\n def visitInterval(self, interval):\n str_=\"\"\n if (interval.WhichOneof(\"LowerLevel\") == 'special_lower_level'):\n if interval.special_lower_level == 0:\n str_ += \"kstart\"\n else:\n str_ += \"kend\"\n elif (interval.WhichOneof(\"LowerLevel\") == 'lower_level'):\n str_ += str(interval.lower_level)\n str_ += \",\"\n if (interval.WhichOneof(\"UpperLevel\") == 'special_upper_level'):\n if interval.special_upper_level == 0:\n str_ += \"kstart\"\n else:\n str_ += \"kend\"\n elif (interval.WhichOneof(\"UpperLevel\") == 'upper_level'):\n str_ += str(interval.upper_level)\n return str_\n\n def visitStatement(self, stmt):\n\n self.indent_+=2\n self.T_.initial_indent=' '*self.indent_\n\n self.visitBodyStmt(stmt.ASTStmt)\n\n self.indent_-=2\n self.T_.initial_indent=' '*self.indent_\n \n def visitAccess(self, accessid, extents, mode):\n extent_str = \"\"\n for extent in extents.extents:\n if not extent_str:\n extent_str=\"{\"\n else:\n extent_str +=\",\"\n extent_str += str(extent.minus)+\",\"+str(extent.plus)\n\n extent_str +=\"}\"\n print(self.T_.fill(mode+\": \" +self.metadata_.AccessIDToName[accessid])) + extent_str \n\n def visitAccesses(self, accesses):\n\n print(self.T_.fill(\"Accesses: \"))\n self.indent_+=2\n self.T_.initial_indent=' '*self.indent_\n\n for accessid,extents in accesses.writeAccess.iteritems():\n self.visitAccess(accessid, extents,\"w\")\n for access in accesses.readAccess.iteritems():\n self.visitAccess(accessid,extents,\"r\")\n\n self.indent_-=2\n self.T_.initial_indent=' '*self.indent_\n \n\n def visitDoMethod(self, domethod):\n domethodName = \"DoMethod_\"+str(domethod.DoMethodID)\n\n domethodName += \"(\"+self.visitInterval(domethod.interval)+\")\"\n\n print(self.T_.fill(domethodName))\n self.indent_+=2\n self.T_.initial_indent=' '*self.indent_\n\n for stmtaccess in domethod.stmtaccesspairs:\n# self.visitAccesses(stmtaccess.callerAccesses)\n self.visitStatement(stmtaccess.statement)\n\n self.indent_-=2\n self.T_.initial_indent=' '*self.indent_\n\n \n def visitStage(self, stage):\n stagename = \"stage_\"+str(stage.stageID) \n\n print(self.T_.fill(stagename))\n self.indent_+=2\n self.T_.initial_indent=' '*self.indent_\n\n for domethod in stage.domethods:\n self.visitDoMethod(domethod)\n\n self.indent_-=2\n self.T_.initial_indent=' '*self.indent_\n\n def visitMultiStage(self, ms):\n msname = \"multistage_\"+str(ms.MulitStageID)\n if ms.looporder == 0:\n msname += \"<forward>\"\n elif ms.looporder == 1:\n msname += \"<backward>\"\n elif ms.looporder == 3:\n msname += \"<parallel>\"\n print(self.T_.fill(msname))\n self.indent_+=2\n self.T_.initial_indent=' '*self.indent_\n\n for stage in ms.stages:\n self.visitStage(stage)\n\n self.indent_-=2\n self.T_.initial_indent=' '*self.indent_\n\n def visitStencil(self,stencil):\n print(self.T_.fill(self.metadata_.stencilName+\"_\"+str(stencil.stencilID)))\n self.indent_+=2\n self.T_.initial_indent=' '*self.indent_\n\n for ms in stencil.multistages:\n self.visitMultiStage(ms)\n \n self.indent_-=2\n self.T_.initial_indent=' '*self.indent_\n \n def visitFields(self,fields): \n str_=\"field \"\n for field in fields:\n str_ += field.name\n dims = [\"i\",\"j\",\"k\"]\n dims_=[]\n for i in range(1,3):\n if field.field_dimensions[i] != -1:\n dims_.append(dims[i])\n str_ += str(dims_)\n str_ += \",\"\n print(self.T_.fill(str_))\n\n\n\n\nparser=argparse.ArgumentParser(\n description='''Deserializes a google protobuf file encoding an HIR example and traverses the AST printing a DSL code with the user equations''',\n)\n#parser.add_argument('--hir', type=string, help='FOO!')\nparser.add_argument('hirfile',type=argparse.FileType('rb'), help='google protobuf HIR file')\nargs=parser.parse_args()\n\nstencilInstantiation = IIR_pb2.StencilInstantiation()\n\nstencilInstantiation.ParseFromString(args.hirfile.read())\nargs.hirfile.close()\n\n\nT = textwrap.TextWrapper(initial_indent=' '*1, width=120,subsequent_indent=' '*1)\ndes = deserializer(stencilInstantiation.metadata)\n\nfor stencil in stencilInstantiation.internalIR.stencils:\n des.visitStencil(stencil)\n\n","sub_path":"src/python/deserializeIIR.py","file_name":"deserializeIIR.py","file_ext":"py","file_size_in_byte":8863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"441972558","text":"'''\n\nTest DNN performances in the case of a full-variable run or in the case of only a couple of variables\n\n'''\n\nfrom __future__ import print_function, division, absolute_import\n\nimport numpy as np\nimport time\nimport pickle\nimport sys\nimport os\nimport random\nimport hashlib\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import roc_curve, roc_auc_score, precision_score, average_precision_score, precision_recall_curve, recall_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.preprocessing import StandardScaler\n\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, Callback, LearningRateScheduler, ReduceLROnPlateau\nfrom keras.constraints import maxnorm\nfrom keras.layers.advanced_activations import PReLU, ELU, LeakyReLU\n\ndef XY_split(fname):\n\tarr = np.load(fname)\n\tX = arr[:,0:-2]\t\t\t\t# Last two columns are timestamp and particle ID\n\tY = arr[:,-1]\n\treturn X,Y\n\ndef run(fullVar):\n\t\n\tt0 = time.time()\n\t\n\tbalanced = False\n\t\n\tif balanced:\t\n\t\tX_train, Y_train = XY_split('/home/drozd/analysis/fraction1/dataset_train.npy')\n\t\tX_val, Y_val = XY_split('/home/drozd/analysis/fraction1/dataset_validate_1.npy')\t\n\telse:\n\t\tX_train, Y_train = XY_split('/home/drozd/analysis/dataset_train.npy')\n\t\tX_val, Y_val = XY_split('/home/drozd/analysis/dataset_validate.npy')\t\t\n\t\n\tif not fullVar:\n\t\tvarsToRemove = [6,10,32,33,38,39,41,42,44,47,48,49,50,51,53,54,56,57]\n\t\tvarsToKeep = [i for i in range(X_train.shape[1]) if not i in varsToRemove]\n\t\t\n\t\tX_train = X_train[:,varsToKeep]\n\t\tX_val = X_val[:,varsToKeep]\n\t\t\n\t\n\tX_train = StandardScaler().fit_transform(X_train)\n\tX_val = StandardScaler().fit_transform(X_val)\n\t\n\tif fullVar:\n\t\tprint('----- All variables -----')\n\telse:\n\t\tprint('----- Selected variables -----')\n\t\n\tmodel = Sequential()\n\tmodel.add(Dense(40,\n\t\t\t\t\tinput_shape=(X_train.shape[1],),\n\t\t\t\t\tkernel_initializer='uniform',\n\t\t\t\t\tactivation='relu'))\n\tmodel.add(Dense(20,kernel_initializer='uniform',activation='relu'))\n\tmodel.add(Dense(10,kernel_initializer='uniform',activation='relu'))\n\tmodel.add(Dense(1,kernel_initializer='uniform',activation='sigmoid'))\n\tmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['binary_accuracy'])\n\n\tcallbacks = []\n\t\n\thistory = model.fit(X_train,Y_train,batch_size=100,epochs=50,verbose=0,callbacks=callbacks,validation_data=(X_val,Y_val))\n\t\n\tpredictions_binary = np.around(model.predict(X_val))\t\t# Array of 0 and 1\n\tpredictions_proba = model.predict_proba(X_val)\t\t\t\t# Array of numbers [0,1]\n\t\n\tpurity = precision_score(Y_val,predictions_binary)\t\t\t# Precision: true positive / (true + false positive). Purity (how many good events in my prediction?)\n\tcompleteness = recall_score(Y_val,predictions_binary)\t\t# Recall: true positive / (true positive + false negative). Completeness (how many good events did I find?)\n\tF1score = f1_score(Y_val,predictions_binary)\t\t\t\t# Average of precision and recall\n\t\n\tl_precision, l_recall, l_thresholds = precision_recall_curve(Y_val,predictions_proba)\n\t\n\n\t# Precision and Recall that maximise F1 score\n\tl_f1 = []\n\tfor i in range(len(l_precision)):\n\t\tl_f1.append( 2*(l_precision[i] * l_recall[i])/(l_precision[i] + l_recall[i]) )\n\tmf1 = max(l_f1)\n\tfor i in range(len(l_f1)):\n\t\tif l_f1[i] == mf1:\n\t\t\tprec_95 = l_precision[i]\n\t\t\trecall_95 = l_recall[i]\n\t\t\t\n\tAUC = average_precision_score(Y_val,predictions_proba)\n\t\n\tprint(\"-- On best F1:\")\t\t\t\t\n\tprint(\"Precision:\", prec_95)\n\tprint(\"Recall:\", recall_95)\n\tprint(\"Max F1:\", mf1)\n\tprint(\"AUC:\", AUC)\n\t\n\tprec_95 = 0\n\trc_95 = 0\n\tf1_95 = 0\n\t\n\tfor i in range(len(l_precision)):\n\t\tif l_precision[i] > 0.95:\n\t\t\ttemp_f1 = 2*(l_precision[i]*l_recall[i])/(l_precision[i]+l_recall[i])\n\t\t\tif temp_f1 > f1_95:\n\t\t\t\tprec_95 = l_precision[i]\n\t\t\t\trc_95 = l_recall[i]\n\t\t\t\tf1_95 = temp_f1\n\t\n\tprint('-- On 95%')\n\tprint('F1:',f1_95)\n\tprint('Precision',prec_95)\n\tprint('Recall',rc_95)\n\t\n\tdel X_train, X_val, Y_train, Y_val, history, predictions_binary, predictions_proba\n\t\n\t\t\n\t\t\n\t\nif __name__ == '__main__' :\n\t\n\trun(True)\n\trun(False)\n","sub_path":"DNN/old/varTest.py","file_name":"varTest.py","file_ext":"py","file_size_in_byte":4211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"310599258","text":"# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# Copyright (c) 2013, Vispy Development Team. All rights reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n# -----------------------------------------------------------------------------\n\"\"\"\nVertexShader and FragmentShader classes.\n\nThese classes are almost never created explicitly but are created implicitly\nfrom within a Program object.\n\nExample\n-------\n\n vert = \"some code\"\n frag = \"some code\"\n\n program = Program(vert,frag)\n\"\"\"\nfrom __future__ import print_function, division\n\nimport re\nimport os.path\nimport numpy as np\nimport OpenGL.GL as gl\n\nfrom vispy import gl\nfrom vispy.util import is_string\nfrom vispy.oogl.globject import GLObject\n\n\n\n# ------------------------------------------------------- class ShaderError ---\nclass ShaderError(RuntimeError):\n \"\"\" Shader error class \"\"\"\n pass\n\n\n\n\n\n# ------------------------------------------------------------ class Shader ---\nclass Shader(GLObject):\n \"\"\"\n Abstract shader class.\n \"\"\"\n\n # Conversion of known uniform and attribute types to GL constants\n _gtypes = {\n 'float': gl.GL_FLOAT,\n 'vec2': gl.GL_FLOAT_VEC2,\n 'vec3': gl.GL_FLOAT_VEC3,\n 'vec4': gl.GL_FLOAT_VEC4,\n 'int': gl.GL_INT,\n 'ivec2': gl.GL_INT_VEC2,\n 'ivec3': gl.GL_INT_VEC3,\n 'ivec4': gl.GL_INT_VEC4,\n 'bool': gl.GL_BOOL,\n 'bvec2': gl.GL_BOOL_VEC2,\n 'bvec3': gl.GL_BOOL_VEC3,\n 'bvec4': gl.GL_BOOL_VEC4,\n 'mat2': gl.GL_FLOAT_MAT2,\n 'mat3': gl.GL_FLOAT_MAT3,\n 'mat4': gl.GL_FLOAT_MAT4,\n 'sampler2D': gl.GL_SAMPLER_2D,\n 'sampler3D': gl.ext.GL_SAMPLER_3D,\n 'samplerCube': gl.GL_SAMPLER_CUBE }\n \n \n def __init__(self, target, code=None):\n \"\"\"\n Create the shader and store code.\n \"\"\"\n\n GLObject.__init__(self)\n \n # Check and store target\n if target not in [gl.GL_VERTEX_SHADER, gl.GL_FRAGMENT_SHADER]:\n raise ValueError('Target must be vertex or fragment shader.')\n self._target = target\n \n # Set code\n self._code = None\n self._source = None\n if code is not None:\n self.code = code\n \n \n @property\n def code(self):\n \"\"\"\n The actual code of the shader.\n \"\"\"\n\n return self._code\n \n @code.setter\n def code(self, code):\n \"\"\"\n Set the code of the shader.\n \"\"\"\n\n if not is_string(code):\n raise TypeError('code must be a string (%s)' % type(code))\n # Set code and source\n if os.path.exists(code):\n with open(code) as file:\n self._code = file.read()\n self._source = os.path.basename(code)\n else:\n self._code = code\n self._source = '<string>'\n\n # Set flags\n self._need_update = True\n\n \n @property\n def source(self):\n \"\"\"\n The source of the code for this shader (not the source code).\n \"\"\"\n\n return self._source\n \n \n def _get_attributes(self):\n \"\"\"\n Extract attributes (name and type) from code.\n \"\"\"\n\n attributes = []\n regex = re.compile(\"\"\"\\s*attribute\\s+(?P<type>\\w+)\\s+\"\"\"\n \"\"\"(?P<name>\\w+)\\s*(\\[(?P<size>\\d+)\\])?\\s*;\"\"\")\n for m in re.finditer(regex,self._code):\n size = -1\n gtype = Shader._gtypes[m.group('type')]\n if m.group('size'):\n size = int(m.group('size'))\n if size >= 1:\n for i in range(size):\n name = '%s[%d]' % (m.group('name'),i)\n attributess.append((name, gtype))\n else:\n attributes.append((m.group('name'), gtype))\n\n return attributes\n \n \n def _get_uniforms(self):\n \"\"\"\n Extract uniforms (name and type) from code.\n \"\"\"\n\n uniforms = []\n regex = re.compile(\"\"\"\\s*uniform\\s+(?P<type>\\w+)\\s+\"\"\"\n \"\"\"(?P<name>\\w+)\\s*(\\[(?P<size>\\d+)\\])?\\s*;\"\"\")\n for m in re.finditer(regex,self._code):\n size = -1\n gtype = Shader._gtypes[m.group('type')]\n if m.group('size'):\n size = int(m.group('size'))\n if size >= 1:\n for i in range(size):\n name = '%s[%d]' % (m.group('name'),i)\n uniforms.append((name, gtype))\n else:\n uniforms.append((m.group('name'), gtype))\n\n return uniforms\n \n \n def _create(self):\n \"\"\"\n Create the shader.\n \"\"\"\n self._handle = gl.glCreateShader(self._target)\n \n \n def _delete(self):\n \"\"\"\n Delete the shader.\n \"\"\"\n\n gl.glDeleteShader(self._handle)\n\n \n def _update(self):\n \"\"\"\n Compile the shader.\n \"\"\"\n\n # Check if we have source code\n if not self._code:\n raise ShaderError('No source code given for shader.')\n \n # Set source\n gl.glShaderSource(self._handle, self._code)\n \n # Compile the shader\n # todo: can this raise exception?\n gl.glCompileShader(self._handle)\n\n # Check the compile status\n status = gl.glGetShaderiv(self._handle, gl.GL_COMPILE_STATUS)\n if not status:\n print( \"Error compiling shader %r\" % self )\n errors = gl.glGetShaderInfoLog(self._handle)\n self._parse_shader_errors(errors, self._code)\n raise ShaderError(\"Shader compilation error\")\n\n\n def _parse_error(self, error):\n \"\"\"\n Parses a single GLSL error and extracts the line number and error\n description.\n\n Parameters\n ----------\n error : str\n An error string as returned byt the compilation process\n \"\"\"\n\n # Nvidia\n # 0(7): error C1008: undefined variable \"MV\"\n m = re.match(r'(\\d+)\\((\\d+)\\):\\s(.*)', error )\n if m: return int(m.group(2)), m.group(3)\n\n # ATI / Intel\n # ERROR: 0:131: '{' : syntax error parse error\n m = re.match(r'ERROR:\\s(\\d+):(\\d+):\\s(.*)', error )\n if m: return int(m.group(2)), m.group(3)\n\n # Nouveau\n # 0:28(16): error: syntax error, unexpected ')', expecting '('\n m = re.match( r'(\\d+):(\\d+)\\((\\d+)\\):\\s(.*)', error )\n if m: return int(m.group(2)), m.group(4)\n\n raise ValueError('Unknown GLSL error format')\n\n\n def _print_error(self, error, lineno):\n \"\"\"\n Print error and show the faulty line + some context\n\n Parameters\n ----------\n error : str\n An error string as returned byt the compilation process\n\n lineno: int\n Line where error occurs\n \"\"\"\n lines = self._code.split('\\n')\n start = max(0,lineno-2)\n end = min(len(lines),lineno+1)\n\n print('Error in %s' % (repr(self)))\n print(' -> %s' % error)\n print()\n if start > 0:\n print(' ...')\n for i, line in enumerate(lines[start:end]):\n if (i+start) == lineno:\n print(' %03d %s' % (i+start, line))\n else:\n if len(line):\n print(' %03d %s' % (i+start,line))\n if end < len(lines):\n print(' ...')\n print()\n\n\n\n\n# ------------------------------------------------------ class VertexShader ---\nclass VertexShader(Shader):\n \"\"\"\n Vertex shader class.\n \"\"\"\n\n def __init__(self, source=None):\n \"\"\"\n Create the shader.\n \"\"\"\n\n Shader.__init__(self, gl.GL_VERTEX_SHADER, source)\n\n\n def __repr__(self):\n \"\"\"\n x.__repr__() <==> repr(x)\n \"\"\"\n\n return \"Vertex Shader %d (%s)\" % (self._id, self._source)\n\n\n\n\n\n# ---------------------------------------------------- class FragmentShader ---\nclass FragmentShader(Shader):\n \"\"\"\n Fragment shader class\n \"\"\"\n\n def __init__(self, source=None):\n \"\"\"\n Create the shader.\n \"\"\"\n\n Shader.__init__(self, gl.GL_FRAGMENT_SHADER, source)\n\n\n def __repr__(self):\n \"\"\"\n x.__repr__() <==> repr(x)\n \"\"\"\n\n return \"Vertex Shader %d (%s)\" % (self._id, self._source)\n","sub_path":"vispy/oogl/shader.py","file_name":"shader.py","file_ext":"py","file_size_in_byte":8495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"558117503","text":"import maxofthree as m3\n\n\ndef get_three_values():\n v1 = input('Podaj 1 liczbę całkowitą: ')\n v2 = input('Podaj 2 liczbę całkowitą: ')\n v3 = input('Podaj 3 liczbę całkowitą: ')\n return v1, v2, v3\n\n\nif __name__ == \"__main__\":\n a, b, c = get_three_values()\n print(m3.maximum_of(a, b, c))\n","sub_path":"07_moduly/script3.py","file_name":"script3.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"21466814","text":"# coding: utf-8\n# pyfi2.1, open, for, readlines, strip, split, extend, Counter, print, close, %r, pprint\n# % load pyfi2.py\n\nfile = open('pyfi.csv', 'r')\nline_list = []\nfor line in file.readlines():\n line = line.strip('\\n')\n line = line.split(',')\n for iterm in line:\n little_iterm = iterm.split(',')\n line_list.extend(little_iterm)\n \nfrom collections import Counter\ncount = Counter(line_list)\nimport pprint\npprint.pprint(count, width=1)\n\nfile.close()\n","sub_path":"DU_card/python/pyfi2.1/pyfi2.1.py","file_name":"pyfi2.1.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"233815342","text":"#!/usr/bin/env python\n# _*_ coding: utf-8 _*_\n\nimport pygame\nimport os\nimport random\nfrom pygame.locals import *\nfrom sys import exit\n\nscreen_w, screen_h = 300, 570\nskin_unit = 20\n# 加载图片资源\ndef load_img(file_name):\n path_name = os.path.join('.', 'images', file_name)\n print(path_name)\n return pygame.image.load(path_name).convert()\n\n# 生成文字资源\ndef make_font_resources(str, size, font_type = None, font_color = (0,0,0)):\n font = pygame.font.Font(font_type, size)\n return font.render(str, True, font_color)\n# 人物移动函数\ndef actor_move(d, actor_pos):\n # actor_pos = actor_pos[0]-1, actor_pos[1] if d=='l'else actor_pos[0]+1, actor_pos[1]\n if d == 'l' and actor_pos[0]-skin_unit>=0 :\n actor_pos = actor_pos[0]-skin_unit, actor_pos[1]\n elif d == 'r' and actor_pos[0]+skin_unit <= screen_w - skin_unit:\n actor_pos = actor_pos[0]+skin_unit, actor_pos[1]\n return actor_pos\n\n\nclass Clock(object):\n def __init__(self, cyc=500):\n self.point = 0\n self.cyc = cyc\n\n def knock(self):\n current_point = pygame.time.get_ticks()/self.cyc\n if current_point > self.point:\n self.point = current_point\n return True\n else:\n return False\n\ndef main():\n pygame.init()\n display = pygame.display\n\n screen = display.set_mode((screen_w, screen_h))\n clock = pygame.time.Clock()\n grass = load_img('grass.png')\n skin = load_img('borgar.png')\n box = load_img('box.png')\n point = load_img('point.png')\n # skin_unit = skin.get_width()/4\n hp_unit = load_img('health-red.png')\n HP_left, HP_top, score_top, margin_right_score = 15, 20, 20, 15\n HP = 10\n # 游戏得分\n score = 0\n # 生成‘游戏失败’的文字图片资源\n font_game_over = make_font_resources('GAME OVER', 32, None, (255,0,0))\n left_game_over, top_game_over = (screen_w - font_game_over.get_width())/2, screen_h/2\n # 生成HP的文字图片资源\n font_hp_title = make_font_resources('HP',16)\n hp_title_left, hp_title_top = (HP_left+HP/2)-font_hp_title.get_width()/2, 4\n\n\n # 盒子雪碧图区域\n box_area = (2*skin_unit, 0, skin_unit, skin_unit)\n # 人物雪碧图区域\n actor_area = (skin_unit, 0, skin_unit, skin_unit)\n # 点雪碧图区域\n point_area = (0, skin_unit, skin_unit, skin_unit)\n # 怪物刷新高度\n monster_born_top = 40\n # 怪物速度\n monster_v = 1\n # 人物活动高度\n actor_h = screen_h - skin_unit\n # 人物初始位置\n actor_pos = ((screen_w/(2*skin_unit))*skin_unit, actor_h)\n # 飞行航道横坐标列表\n x_list_fly_path = [skin_unit*x for x in range(0, screen_w/skin_unit)]\n\n key_bool = False\n cyc_clock = Clock(200)\n monster_born_time = 0\n monster_cyc = 1000\n point_v = 1\n # 子弹列表\n point_list = []\n # 箱子列表\n monster_list = {}\n\n while 1:\n clock.tick(110)\n if HP <= 0:\n screen.fill(0)\n # 显示GAME OVER\n screen.blit(font_game_over, (left_game_over, top_game_over))\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n exit()\n else:\n # 清屏\n screen.fill(skin.get_at((0, 0)))\n # 分数文字的图片资源\n font_score = make_font_resources('SCORE : '+str(score), 16)\n score_left = screen_w - margin_right_score - font_score.get_width()\n screen.blit(font_score, (score_left, score_top))\n # 怪物生成器\n # for i in range(0, screen_w/skin_unit):\n if pygame.time.get_ticks() - monster_born_time > monster_cyc:\n monster_x = random.choice(x_list_fly_path)\n if monster_x not in monster_list.keys():\n monster_list[monster_x] = [monster_x, monster_born_top]\n monster_born_time = pygame.time.get_ticks()\n\n # 显示SCORE文字\n screen.blit(font_hp_title, (hp_title_left, hp_title_top))\n # 显示HP文字\n screen.blit(font_hp_title, (hp_title_left, hp_title_top))\n # 绘制血条\n for i in range(0, HP):\n screen.blit(hp_unit, (15+i, HP_top))\n # 绘制人物活动区域\n for i in range(0, screen_w/skin_unit):\n screen.blit(grass, (i*skin_unit, actor_h))\n\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n exit()\n # 键盘按下\n if event.type == KEYDOWN:\n if event.key == K_LEFT:\n key_bool = True\n d = 'l'\n elif event.key == K_RIGHT:\n key_bool = True\n d = 'r'\n elif event.key == K_SPACE:\n # 子弹初始发出\n point_list.append([actor_pos[0], screen_h - 2*skin_unit])\n # point_list[actor_pos[0]] = [actor_pos[0], screen_h - 2*skin_unit]\n\n # 键盘抬起\n if event.type == KEYUP:\n key_bool = False\n if event.key == K_LEFT:\n d = 'l'\n elif event.key == K_RIGHT:\n d = 'r'\n if key_bool and cyc_clock.knock() :\n actor_pos = actor_move(d, actor_pos)\n # 人物移动\n screen.blit(skin, actor_pos, actor_area)\n # 子弹和怪物的移动\n # 子弹部分\n for i, item in enumerate(point_list):\n item[1] -= point_v\n\n for x in x_list_fly_path:\n # 判断字典中存在目标对象\n if monster_list.has_key(x):\n monster_list[x][1] += monster_v\n monster_rect = pygame.Rect(box.get_rect())\n monster_rect.top = monster_list[x][1]\n monster_rect.left = monster_list[x][0]\n\n if monster_list[x][1] >= screen_h-skin_unit*2:\n del monster_list[x]\n HP -= 1\n # 处理碰撞\n # if monster_list[x] in point_list:\n # print point_list.index(monster_list[x])\n for i, item in enumerate(point_list):\n point_rect = pygame.Rect(point.get_rect())\n point_rect.top = item[1]\n point_rect.left = item[0]\n if monster_rect.colliderect(point_rect):\n del monster_list[x]\n point_list.pop(i)\n score += 1\n\n # 绘制子弹\n for item in point_list:\n screen.blit(skin, item, point_area)\n # 绘制怪物\n for i in monster_list:\n screen.blit(skin, monster_list[i], box_area)\n\n display.flip()\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"项目二/fall-shoot-game.py","file_name":"fall-shoot-game.py","file_ext":"py","file_size_in_byte":7170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"24454979","text":"from sys import stdout\n\nimport nni\nimport torch\nfrom sklearn.metrics import roc_auc_score\nfrom bilinear_model import LayeredBilinearModule\nfrom dataset.dataset_model import BilinearDataset\nfrom dataset.datset_sampler import ImbalancedDatasetSampler\nfrom params.parameters import BilinearActivatorParams, LayeredBilinearModuleParams\nfrom bokeh.plotting import figure, show\nfrom torch.utils.data import DataLoader, random_split, SubsetRandomSampler\nfrom collections import Counter\nimport numpy as np\nTRAIN_JOB = \"TRAIN\"\nDEV_JOB = \"DEV\"\nTEST_JOB = \"TEST\"\nVALIDATE_JOB = \"VALIDATE\"\nLOSS_PLOT = \"loss\"\nAUC_PLOT = \"AUC\"\nACCURACY_PLOT = \"accuracy\"\n\n\nclass BilinearActivator:\n def __init__(self, model: LayeredBilinearModule, params: BilinearActivatorParams, train_data: BilinearDataset,\n dev_data: BilinearDataset = None, test_data: BilinearDataset = None, nni=False):\n self._nni = nni\n self._dataset = params.DATASET\n self._gpu = torch.cuda.is_available()\n self._device = torch.device(\"cuda: 1\" if self._gpu else \"cpu\")\n self._model = model\n self._model.gpu_device(self._gpu)\n self._epochs = params.EPOCHS\n self._batch_size = params.BATCH_SIZE\n self._loss_func = params.LOSS\n self._load_data(train_data, dev_data, test_data, params.DEV_SPLIT, params.TEST_SPLIT, params.BATCH_SIZE)\n self._init_loss_and_acc_vec()\n self._init_print_att()\n\n # init loss and accuracy vectors (as function of epochs)\n def _init_loss_and_acc_vec(self):\n self._loss_vec_train = []\n self._loss_vec_dev = []\n self._loss_vec_test = []\n\n self._bar = 0.5\n self._accuracy_vec_train = []\n self._accuracy_vec_dev = []\n self._accuracy_vec_test = []\n\n self._auc_vec_train = []\n self._auc_vec_dev = []\n self._auc_vec_test = []\n\n # init variables that holds the last update for loss and accuracy\n def _init_print_att(self):\n self._print_train_accuracy = 0\n self._print_train_loss = 0\n self._print_train_auc = 0\n\n self._print_dev_accuracy = 0\n self._print_dev_loss = 0\n self._print_dev_auc = 0\n\n self._print_test_accuracy = 0\n self._print_test_loss = 0\n self._print_test_auc = 0\n\n # update loss after validating\n def _update_loss(self, loss, job=TRAIN_JOB):\n if job == TRAIN_JOB:\n self._loss_vec_train.append(loss)\n self._print_train_loss = loss\n elif job == DEV_JOB:\n self._loss_vec_dev.append(loss)\n self._print_dev_loss = loss\n elif job == TEST_JOB:\n self._loss_vec_test.append(loss)\n self._print_test_loss = loss\n\n # update accuracy after validating\n def _update_auc(self, pred, true, job=TRAIN_JOB):\n pred_ = [-1 if np.isnan(x) else x for x in pred]\n num_classes = len(Counter(true))\n if num_classes < 2:\n auc = 0.5\n # calculate acc\n else:\n auc = roc_auc_score(true, pred_)\n if job == TRAIN_JOB:\n self._print_train_auc = auc\n self._auc_vec_train.append(auc)\n return auc\n elif job == DEV_JOB:\n self._print_dev_auc = auc\n self._auc_vec_dev.append(auc)\n return auc\n elif job == TEST_JOB:\n self._print_test_auc = auc\n self._auc_vec_test.append(auc)\n return auc\n\n # update accuracy after validating\n def _update_accuracy(self, pred, true, job=TRAIN_JOB):\n # calculate acc\n if job == TRAIN_JOB:\n max_acc = 0\n best_bar = self._bar\n for bar in [i * 0.01 for i in range(100)]:\n acc = sum([1 if (0 if i < bar else 1) == int(j) else 0 for i, j in zip(pred, true)]) / len(pred)\n if acc > max_acc:\n best_bar = bar\n max_acc = acc\n self._bar = best_bar\n\n self._print_train_accuracy = max_acc\n self._accuracy_vec_train.append(max_acc)\n return max_acc\n\n acc = sum([1 if (0 if i < self._bar else 1) == int(j) else 0 for i, j in zip(pred, true)]) / len(pred)\n\n if job == DEV_JOB:\n self._print_dev_accuracy = acc\n self._accuracy_vec_dev.append(acc)\n return acc\n elif job == TEST_JOB:\n self._print_test_accuracy = acc\n self._accuracy_vec_test.append(acc)\n return acc\n\n # print progress of a single epoch as a percentage\n def _print_progress(self, batch_index, len_data, job=\"\"):\n prog = int(100 * (batch_index + 1) / len_data)\n stdout.write(\"\\r\\r\\r\\r\\r\\r\\r\\r\" + job + \" %d\" % prog + \"%\")\n print(\"\", end=\"\\n\" if prog == 100 else \"\")\n stdout.flush()\n\n # print last loss and accuracy\n def _print_info(self, jobs=()):\n if TRAIN_JOB in jobs:\n print(\"Acc_Train: \" + '{:{width}.{prec}f}'.format(self._print_train_accuracy, width=6, prec=4) +\n \" || AUC_Train: \" + '{:{width}.{prec}f}'.format(self._print_train_auc, width=6, prec=4) +\n \" || Loss_Train: \" + '{:{width}.{prec}f}'.format(self._print_train_loss, width=6, prec=4),\n end=\" || \")\n if DEV_JOB in jobs:\n print(\"Acc_Dev: \" + '{:{width}.{prec}f}'.format(self._print_dev_accuracy, width=6, prec=4) +\n \" || AUC_Dev: \" + '{:{width}.{prec}f}'.format(self._print_dev_auc, width=6, prec=4) +\n \" || Loss_Dev: \" + '{:{width}.{prec}f}'.format(self._print_dev_loss, width=6, prec=4),\n end=\" || \")\n if TEST_JOB in jobs:\n print(\"Acc_Test: \" + '{:{width}.{prec}f}'.format(self._print_test_accuracy, width=6, prec=4) +\n \" || AUC_Test: \" + '{:{width}.{prec}f}'.format(self._print_test_auc, width=6, prec=4) +\n \" || Loss_Test: \" + '{:{width}.{prec}f}'.format(self._print_test_loss, width=6, prec=4),\n end=\" || \")\n print(\"\")\n\n # plot loss / accuracy graph\n def plot_line(self, job=LOSS_PLOT):\n p = figure(plot_width=600, plot_height=250, title=self._dataset + \" - Dataset - \" + job,\n x_axis_label=\"epochs\", y_axis_label=job)\n color1, color2, color3 = (\"yellow\", \"orange\", \"red\") if job == LOSS_PLOT else (\"black\", \"green\", \"blue\")\n if job == LOSS_PLOT:\n y_axis_train = self._loss_vec_train\n y_axis_dev = self._loss_vec_dev\n y_axis_test = self._loss_vec_test\n elif job == AUC_PLOT:\n y_axis_train = self._auc_vec_train\n y_axis_dev = self._auc_vec_dev\n y_axis_test = self._auc_vec_test\n elif job == ACCURACY_PLOT:\n y_axis_train = self._accuracy_vec_train\n y_axis_dev = self._accuracy_vec_dev\n y_axis_test = self._accuracy_vec_test\n\n x_axis = list(range(len(y_axis_dev)))\n p.line(x_axis, y_axis_train, line_color=color1, legend=\"train\")\n p.line(x_axis, y_axis_dev, line_color=color2, legend=\"dev\")\n p.line(x_axis, y_axis_test, line_color=color3, legend=\"test\")\n show(p)\n\n def _plot_acc_dev(self):\n self.plot_line(LOSS_PLOT)\n self.plot_line(AUC_PLOT)\n self.plot_line(ACCURACY_PLOT)\n\n @property\n def model(self):\n return self._model\n\n @property\n def loss_train_vec(self):\n return self._loss_vec_train\n\n @property\n def accuracy_train_vec(self):\n return self._accuracy_vec_train\n\n @property\n def auc_train_vec(self):\n return self._auc_vec_train\n\n @property\n def loss_dev_vec(self):\n return self._loss_vec_dev\n\n @property\n def accuracy_dev_vec(self):\n return self._accuracy_vec_dev\n\n @property\n def auc_dev_vec(self):\n return self._auc_vec_dev\n\n @property\n def loss_test_vec(self):\n return self._loss_vec_test\n\n @property\n def accuracy_test_vec(self):\n return self._accuracy_vec_test\n\n @property\n def auc_test_vec(self):\n return self._auc_vec_test\n\n # load dataset\n def _load_data(self, train_dataset, dev_dataset, test_dataset, dev_split, test_split, batch_size):\n # calculate lengths off train and dev according to split ~ (0,1)\n len_dev = 0 if dev_dataset else int(len(train_dataset) * dev_split)\n len_test = 0 if test_dataset else int(len(train_dataset) * test_split)\n len_train = len(train_dataset) - len_test - len_dev\n\n # split dataset\n train, dev, test = random_split(train_dataset, (len_train, len_dev, len_test))\n\n # set train loader\n self._balanced_train_loader = DataLoader(\n train.dataset,\n batch_size=batch_size,\n collate_fn=train.dataset.collate_fn,\n sampler=ImbalancedDatasetSampler(train.dataset, indices=train.indices,\n num_samples=len(train.indices))\n # shuffle=True\n )\n # set train loader\n self._unbalanced_train_loader = DataLoader(\n train.dataset,\n batch_size=batch_size,\n collate_fn=train.dataset.collate_fn,\n sampler=SubsetRandomSampler(train.indices)\n # shuffle=True\n )\n\n # set validation loader\n self._dev_loader = DataLoader(\n dev_dataset,\n batch_size=batch_size,\n collate_fn=dev_dataset.collate_fn,\n\n ) if dev_dataset else DataLoader(\n dev,\n batch_size=batch_size,\n collate_fn=dev.dataset.collate_fn,\n # sampler=SubsetRandomSampler(dev.indices)\n # shuffle=True\n )\n\n # set test loader\n self._test_loader = DataLoader(\n test_dataset,\n batch_size=batch_size,\n collate_fn=test_dataset.collate_fn,\n ) if test_dataset else DataLoader(\n test,\n batch_size=batch_size,\n collate_fn=test.dataset.collate_fn,\n # sampler=SubsetRandomSampler(test.indices)\n # shuffle=True\n )\n\n # train a model, input is the enum of the model type\n def train(self, show_plot=True, early_stop=False):\n self._init_loss_and_acc_vec()\n # calc number of iteration in current epoch\n len_data = len(self._balanced_train_loader)\n for epoch_num in range(self._epochs):\n if not self._nni:\n print(\"epoch\" + str(epoch_num))\n # calc number of iteration in current epoch\n for batch_index, (A, x0, embed, l) in enumerate(self._balanced_train_loader):\n if self._gpu:\n A, x0, embed, l = A.cuda(), x0.cuda(), embed.cuda(), l.cuda()\n\n # print progress\n self._model.train()\n\n output = self._model(A, x0, embed) # calc output of current model on the current batch\n loss = self._loss_func(output.squeeze(dim=1).squeeze(dim=1), l.float()) # calculate loss\n loss.backward() # back propagation\n\n # if (batch_index + 1) % self._batch_size == 0 or (batch_index + 1) == len_data: # batching\n self._model.optimizer.step() # update weights\n self._model.zero_grad() # zero gradients\n\n if not self._nni:\n self._print_progress(batch_index, len_data, job=TRAIN_JOB)\n # validate and print progress\n self._validate(self._unbalanced_train_loader, job=TRAIN_JOB)\n self._validate(self._dev_loader, job=DEV_JOB)\n self._validate(self._test_loader, job=TEST_JOB)\n if not self._nni:\n self._print_info(jobs=[TRAIN_JOB, DEV_JOB, TEST_JOB])\n\n # /---------------------- FOR NNI -------------------------\n if epoch_num % 10 == 0 and self._nni:\n test_auc = self._print_test_accuracy\n nni.report_intermediate_result(test_auc)\n if early_stop and epoch_num > 30 and self._print_test_loss > np.max(self._loss_vec_train[-30:]):\n break\n\n if self._nni:\n test_auc = self.accuracy_test_vec[np.argmax(self._accuracy_vec_dev)]\n nni.report_final_result(test_auc)\n # ----------------------- FOR NNI -------------------------/\n\n if show_plot:\n self._plot_acc_dev()\n\n # validation function only the model and the data are important for input, the others are just for print\n def _validate(self, data_loader, job=\"\"):\n # for calculating total loss and accuracy\n loss_count = 0\n true_labels = []\n pred = []\n\n self._model.eval()\n # calc number of iteration in current epoch\n len_data = len(data_loader)\n for batch_index, (A, x0, embed, l) in enumerate(data_loader):\n if self._gpu:\n A, x0, embed, l = A.cuda(), x0.cuda(), embed.cuda(), l.cuda()\n # print progress\n if not self._nni:\n self._print_progress(batch_index, len_data, job=VALIDATE_JOB)\n output = self._model(A, x0, embed)\n # calculate total loss\n loss_count += self._loss_func(output.squeeze(dim=1).squeeze(dim=1), l.float())\n true_labels += l.tolist()\n pred += output.squeeze(dim=1).squeeze(dim=1).tolist()\n\n # update loss accuracy\n loss = float(loss_count / len(data_loader))\n # pred_labels = [0 if np.isnan(i) else i for i in pred_labels]\n self._update_loss(loss, job=job)\n self._update_accuracy(pred, true_labels, job=job)\n self._update_auc(pred, true_labels, job=job)\n return loss\n\n\nif __name__ == '__main__':\n from params.aids_params import AidsDatasetTrainParams, AidsDatasetDevParams, AidsDatasetTestParams\n aids_train_ds = BilinearDataset(AidsDatasetTrainParams())\n aids_dev_ds = BilinearDataset(AidsDatasetDevParams())\n aids_test_ds = BilinearDataset(AidsDatasetTestParams())\n activator = BilinearActivator(LayeredBilinearModule(LayeredBilinearModuleParams(ftr_len=aids_train_ds.len_features)),\n BilinearActivatorParams(), aids_train_ds, dev_data=aids_dev_ds, test_data=aids_test_ds)\n activator.train()\n","sub_path":"bilinear_activator.py","file_name":"bilinear_activator.py","file_ext":"py","file_size_in_byte":14347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"321766448","text":"from intake.source import base\nfrom . import __version__\n\n\nclass ParquetSource(base.DataSource):\n \"\"\"\n Source to load parquet datasets.\n\n Produces a dataframe.\n\n A parquet dataset may be a single file, a set of files in a single\n directory or a nested set of directories containing data-files.\n\n The implementation uses either fastparquet or pyarrow, select with the\n `engine=` kwarg.\n\n Keyword parameters accepted by this Source:\n\n - columns: list of str or None\n column names to load. If None, loads all\n\n - index: str or None\n column to make into the index of the dataframe. If None, may be\n inferred from the saved matadata in certain cases.\n\n - filters: list of tuples\n row-group level filtering; a tuple like ``('x', '>', 1)`` would mean\n that if a row-group has a maximum value less than 1 for the column\n ``x``, then it will be skipped. Row-level filtering is *not*\n performed.\n\n - engine: 'fastparquet' or 'pyarrow'\n Which backend to read with.\n\n\n - gather_statistics : bool or None (default).\n Gather the statistics for each dataset partition. By default,\n this will only be done if the _metadata file is available. Otherwise,\n statistics will only be gathered if True, because the footer of\n every file will be parsed (which is very slow on some systems).\n\n - see dd.read_parquet() for the other named parameters that can be passed through.\n \"\"\"\n container = 'dataframe'\n name = 'parquet'\n version = __version__\n partition_access = True\n\n def __init__(self, urlpath, metadata=None,\n storage_options=None, **parquet_kwargs):\n self._urlpath = urlpath\n self._storage_options = storage_options or {}\n self._kwargs = parquet_kwargs or {}\n self._df = None\n\n super(ParquetSource, self).__init__(metadata=metadata)\n\n def _get_schema(self):\n if self._df is None:\n self._df = self._to_dask()\n dtypes = {k: str(v) for k, v in self._df._meta.dtypes.items()}\n self._schema = base.Schema(datashape=None,\n dtype=dtypes,\n shape=(None, len(self._df.columns)),\n npartitions=self._df.npartitions,\n extra_metadata={})\n return self._schema\n\n def _get_partition(self, i):\n self._get_schema()\n return self._df.get_partition(i).compute()\n\n def read(self):\n \"\"\"\n Create single pandas dataframe from the whole data-set\n \"\"\"\n self._load_metadata()\n return self._df.compute()\n\n def to_spark(self):\n \"\"\"Produce Spark DataFrame equivalent\n\n This will ignore all arguments except the urlpath, which will be\n directly interpreted by Spark. If you need to configure the storage,\n that must be done on the spark side.\n\n This method requires intake-spark. See its documentation for how to\n set up a spark Session.\n \"\"\"\n from intake_spark.base import SparkHolder\n args = [\n ['read'],\n ['parquet', [self._urlpath]]\n ]\n sh = SparkHolder(True, args, {})\n return sh.setup()\n\n def to_dask(self):\n self._load_metadata()\n return self._df\n\n def _to_dask(self):\n \"\"\"\n Create a lazy dask-dataframe from the parquet data\n \"\"\"\n import dask.dataframe as dd\n urlpath = self._get_cache(self._urlpath)[0]\n self._df = dd.read_parquet(urlpath,\n storage_options=self._storage_options, **self._kwargs)\n self._load_metadata()\n return self._df\n\n def _close(self):\n self._df = None\n","sub_path":"intake_parquet/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":3791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"165792692","text":"\"\"\"Validation utils\n\"\"\"\nfrom typing import Any, Iterable\n\n\nclass ValidationError(Exception):\n pass\n\n\ndef validate_input(\n raw_value: Any,\n expected_type: type,\n var_name: str = None,\n message: str = None,\n min_value=None,\n max_value=None,\n choices: Iterable = None\n) -> Any:\n \"\"\"Validate input, raise ValidationError if invalid\n\n Args:\n raw_value: user input data\n expected_type: type to try convert into\n var_name: variable name for automatic message, ignore if have message\n message: custom error message\n min_value: minimum value, only for numeric type\n max_value: maximum value, only for numeric type\n choices: value must be in this list\n\n Returns:\n return expected converted value\n\n Raise ValidationError if invalid\n\n \"\"\"\n try:\n if isinstance(raw_value, expected_type):\n value = raw_value\n elif isinstance(raw_value, str):\n value = expected_type(raw_value.strip())\n else:\n value = expected_type(raw_value)\n except (TypeError, ValueError, AttributeError):\n if message:\n raise ValidationError(message)\n raise ValidationError(\n f'Invalid `{var_name}`, expected {expected_type.__name__}')\n\n errors = []\n\n if isinstance(value, (int, float, complex)):\n if min_value is not None and min_value > value:\n errors.append(f'must larger or equal {min_value}')\n if max_value is not None and max_value < value:\n errors.append(f'must smaller or equal {max_value}')\n\n if choices is not None and value not in choices:\n errors.append(f'only {choices} allowed')\n\n if errors:\n if message:\n raise ValidationError(message)\n message = ', '.join(errors)\n raise ValidationError(f'Invalid `{var_name}`, {message}')\n\n return value\n","sub_path":"backend/gasprice/utils/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"354342287","text":"import pytest\nimport webob\n\nfrom resourceful import (Library, Resource,\n get_needed, make_serf, compat)\nfrom resourceful import Resourceful, ConfigurationError\n\n\ndef test_inject():\n foo = Library('foo', '')\n x1 = Resource(foo, 'a.js')\n x2 = Resource(foo, 'b.css')\n y1 = Resource(foo, 'c.js', depends=[x1, x2])\n\n def app(environ, start_response):\n start_response('200 OK', [])\n needed = get_needed()\n needed.need(y1)\n return [b'<html><head></head><body</body></html>']\n\n wrapped_app = Resourceful(app, base_url='http://testapp')\n\n request = webob.Request.blank('/')\n request.environ['SCRIPT_NAME'] = '/root' # base_url is defined so SCRIPT_NAME\n # shouldn't be taken into account\n response = request.get_response(wrapped_app)\n assert response.body == b'''\\\n<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"http://testapp/resourceful/foo/b.css\" />\n<script type=\"text/javascript\" src=\"http://testapp/resourceful/foo/a.js\"></script>\n<script type=\"text/javascript\" src=\"http://testapp/resourceful/foo/c.js\"></script></head><body</body></html>'''\n\n\ndef test_inject_script_name():\n foo = Library('foo', '')\n x1 = Resource(foo, 'a.js')\n x2 = Resource(foo, 'b.css')\n y1 = Resource(foo, 'c.js', depends=[x1, x2])\n\n def app(environ, start_response):\n start_response('200 OK', [])\n needed = get_needed()\n needed.need(y1)\n return [b'<html><head></head><body</body></html>']\n\n wrapped_app = Resourceful(app)\n\n request = webob.Request.blank('/path')\n request.environ['SCRIPT_NAME'] = '/root'\n response = request.get_response(wrapped_app)\n assert response.body == b'''\\\n<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"/root/resourceful/foo/b.css\" />\n<script type=\"text/javascript\" src=\"/root/resourceful/foo/a.js\"></script>\n<script type=\"text/javascript\" src=\"/root/resourceful/foo/c.js\"></script></head><body</body></html>'''\n\n\ndef test_incorrect_configuration_options():\n app = None\n with pytest.raises(TypeError) as e:\n Resourceful(app, incorrect='configoption')\n assert (\n \"__init__() got an unexpected \"\n \"keyword argument 'incorrect'\") in str(e)\n\n\ndef test_inject_unicode_base_url():\n foo = Library('foo', '')\n x1 = Resource(foo, 'a.js')\n\n def app(environ, start_response):\n start_response('200 OK', [])\n x1.need()\n return [b'<html><head></head><body</body></html>']\n\n request = webob.Request.blank('/')\n wrapped = Resourceful(app, base_url=compat.u('http://localhost'))\n # Resourceful used to choke on unicode content.\n request.get_response(wrapped)\n\n\ndef test_serf():\n pytest.importorskip('mypackage')\n # also test serf config\n d = {\n 'resource': 'py:mypackage.style'\n }\n serf = make_serf({}, **d)\n serf = Resourceful(serf, versioning=False)\n request = webob.Request.blank('/')\n response = request.get_response(serf)\n assert response.body == b'''\\\n<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"/resourceful/foo/style.css\" /></head><body></body></html>'''\n\n\ndef test_serf_unknown_library():\n d = {\n 'resource': 'unknown_library:unknown_resource'\n }\n with pytest.raises(ConfigurationError):\n make_serf({}, **d)\n","sub_path":"tests/test_wsgi.py","file_name":"test_wsgi.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"321447538","text":"\"\"\"\nFlask Server\n\n - Takes HTTP requests (GET, POST, ...) and returns a response to the client\n\n\"\"\"\n\n# Imports\n\nfrom flask import Flask, redirect, url_for, render_template, request, session, flash\nfrom psycopg2 import connect, Error\nfrom datetime import timedelta\n\n# User-defined imports\nfrom modules.database import *\nfrom modules.profiles import *\nfrom modules.scheduling import *\nfrom modules.reporting import *\n\n#----------------------------------------------------------------------------#\n\n## Flask Server ##\n\napp = Flask(__name__)\napp.secret_key = \"key\" # necessary for session data\napp.permanent_session_lifetime = timedelta(days=2)\n\n#----------------------------------------------------------------------------#\n\n## Home Page ##\n\n@app.route(\"/\")\ndef home():\n\treturn render_template(\"index.html\")\n\n\n## Create Account Page ##\n\n@app.route(\"/create_account\", methods=[\"POST\", \"GET\"])\ndef create_account():\n\t# User sends account details\n\tif request.method == \"POST\":\t\t\n\t\t\n\t\temail = request.form[\"email\"]\n\t\tfirst_name = request.form[\"first_name\"]\t\t\t\t\t\n\t\tlast_name = request.form[\"last_name\"]\n\n\t\tsession[\"name\"] = first_name\n\t\tsession[\"email\"] = email\n\t\tsession[\"account_created\"] = True\n\n\t\t# Case 1: User already exists\n\t\tif user_already_exists(email):\t\t\t\t\t\t\t\n\t\t\treturn redirect(url_for(\"user\"))\t\n\n\t\t# Case 2: Add user to database\n\t\telse:\n\t\t\tadd_user_to_database(email, first_name, last_name) \n\t\t\treturn redirect(url_for(\"user\"))\n\n\treturn render_template(\"create_account.html\")\n\n\n## Login Page ##\n\n@app.route(\"/login\", methods=[\"POST\", \"GET\"])\ndef login():\n\n\t# User enter's credentials\n\tif request.method == 'POST':\n\t\temail = request.form[\"email\"]\n\n\t\tif user_already_exists(email):\n\t\t\treturn redirect(url_for(\"user\"))\n\t\telse:\n\t\t\tflash(\"This account does not exist\", \"error\")\n\t\t\treturn redirect(url_for(\"login\"))\n\n\treturn render_template(\"login.html\")\n\n\n## User Profile Page ##\n\n@app.route(\"/user\", methods=[\"POST\", \"GET\"])\ndef user():\n\tsession.permanent = True # Keeps the user logged in\n\n\tif request.method == \"POST\" and \"logout\" in request.form:\t# Case 1: User click's logout\n\n\t\tflash(\"You have been logged out!\", \"info\")\n\t\tsession.pop(\"name\", None)\n\t\tsession.pop(\"email\", None)\n\t\treturn redirect(url_for(\"login\"))\n\n\telse:\n\t\tif \"account_created\" in session:\n\t\t\tname = session[\"name\"]\n\t\t\tflash(\"You have successfully created an account {0}\".format(name), \"info\")\n\t\t\tsession.pop(\"account_created\", None)\n\n\t\treturn render_template(\"user.html\")\n\n\n#----------------------------------------------------------------------------#\n\n## Run the app ##\n\n# DEBUG MODE -> means you can edit here with the server running, \n# and you just need to 'refresh' your web browser to see changes\n\nif __name__ == \"__main__\":\n\tapp.run(debug = True) \n\t\n\n\t\n\n\n","sub_path":"supportsConnect/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"251433083","text":"\n\n#calss header\nclass _SLAVER():\n\tdef __init__(self,): \n\t\tself.name = \"SLAVER\"\n\t\tself.definitions = [u'(especially of an animal) to allow liquid to come out of the mouth, especially because of excitement or hunger: ', u'to show great interest or excitement in someone or something, in a way that is unpleasant to other people: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_slaver.py","file_name":"_slaver.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"81121951","text":"#!/usr/bin/python\n# -*- codding: utf-8 -*-\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nfrom common.execute_command import write_two_parameter\n\n# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appsync/delete-api-key.html\nif __name__ == '__main__':\n \"\"\"\n\tcreate-api-key : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appsync/create-api-key.html\n\tlist-api-keys : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appsync/list-api-keys.html\n\tupdate-api-key : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appsync/update-api-key.html\n \"\"\"\n\n parameter_display_string = \"\"\"\n # api-id : The API ID.\n # id : The ID for the API key.\n \"\"\"\n add_option_dict = {}\n add_option_dict[\"parameter_display_string\"] = parameter_display_string\n # ex: add_option_dict[\"no_value_parameter_list\"] = \"--single-parameter\"\n write_two_parameter(\"appsync\", \"delete-api-key\", \"api-id\", \"id\", add_option_dict)\n","sub_path":"appsync_write_2/api-key_delete.py","file_name":"api-key_delete.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"468925141","text":"import math\nimport re\nfrom tabulate import tabulate\n\ndef cls():\n print(\"\\x1B\\x5B2J\", end=\"\")\n print(\"\\x1B\\x5BH\", end=\"\")\n\ndef sind(angle):\n return math.sin(math.radians(angle))\ndef cosd(angle):\n return math.cos(math.radians(angle))\ndef tand(angle):\n return math.tan(math.radians(angle))\n\ndef vin(prompt, defvalue, **kwargs):\n\n units = kwargs.get('units', None)\n \n if (units == None):\n input_prompt = prompt + ' [' + str(defvalue) + '] ? '\n else:\n input_prompt = prompt + ' [' + str(defvalue) + '] ' + str(units) + ' ? '\n\n return (input(input_prompt) or defvalue)\n\nc=12/math.pi\n\ndfile = \"DIAMPY.DAT\"\nofile = \"DIAMPY.OUT\"\n\nfp = open(dfile, \"r\")\nfpw = open(ofile, \"w\")\n\nmaterials = []\nspeeds = []\nsfms = []\nsfmlow = []\nsfmhi = []\nnm = 0\ndiameters = []\n\ndef main():\n cls()\n print('MACHINING DIAMETER UTILITY\\n')\n\n rdata()\n print('number of data entries read = {0}'.format(len(materials)))\n\n for i in materials:\n print(i)\n \n def matnum():\n global nm\n nm = int(vin(\"Material Number\",1))-1\n if (not (-1<nm<=len(materials))):\n print('INVALID NUMBER')\n matnum()\n matnum()\n diamcalc()\n\ndef diamcalc():\n material = materials[nm]\n fpw.write('Material = {0}\\n'.format(material))\n\n header = [\"SPEED (rpm)\", \"MIN DIAMETER (in)\", \"MAX DIAMETER (in)\"]\n\n ns = len(sfms)\n for i in range(0,ns-1):\n dlow=round(c*float(sfmlow[nm])/float(speeds[i]),4)\n dhigh=round(c*float(sfmhi[nm])/float(speeds[i]),4)\n diameters.append([speeds[i],dlow,dhigh])\n\n fpw.write(tabulate(diameters, headers=header))\n\ndef rdata():\n temp = []\n nd=0 # number of data entries\n k=0\n f=0\n ns=0\n\n global materials\n global speeds\n global sfms\n global sfmlow\n global sfmhi\n\n for i in fp:\n x = re.search(r\"\\d{1,3} (\\w|\\s)* \\d{1,4} \\d{1,4}\",i)\n try:\n result = x.group()\n except AttributeError:\n result = None\n if result:\n material = re.search(r\"\\d{1,3} ([a-zA-Z]|\\s)*\",result)\n sfmsearch = re.search(r\"\\d{1,4} \\d{1,4}\",result)\n try:\n mat = material.group()\n sfm = sfmsearch.group()\n except AttributeError:\n mat = None\n sfm = None\n if mat:\n materials.append(mat.rstrip())\n if sfm:\n sfms.append(sfm)\n \n y = re.search(r\"^\\d{1,4}$\", i)\n try:\n result = y.group()\n except AttributeError:\n result = None\n if result:\n speeds.append(result)\n\n materials = list(dict.fromkeys(materials))\n sfms = list(dict.fromkeys(sfms))\n sfmsnew = []\n\n for i in range(0,len(sfms)):\n temp = (re.search(r\"\\d{1,4} \",sfms[i]).group())\n temp = temp.rstrip()\n sfmlow.append(temp)\n for i in range(0,len(sfms)):\n temp = (re.search(r\" \\d{1,4}\",sfms[i]).group())\n temp = temp.lstrip()\n sfmhi.append(temp)\n\nmain()","sub_path":"Converted Programs Jumble Lowercase/diam.py","file_name":"diam.py","file_ext":"py","file_size_in_byte":3045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"34466682","text":"# - Create a function called `factorio`\n# that returns it's input's factorial\n\na = int(input(\"Enter an integer: \"))\n\ndef factorio(n):\n if n < 0:\n print(\"Too small, must be 0 or greater!\")\n return\n elif n == 0:\n return 1\n else:\n f = 1\n for i in range(1, n + 1):\n f *= i\n return f\n\nprint(factorio(a))","sub_path":"week-02/day-02/factorio.py","file_name":"factorio.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"631587545","text":"from Nio import *\nx = open_file('CO_10deg_monthly_for_transportcalc_850-1850_032014.nc','r')\nlon = x.variables['lon'][:]\nlat = x.variables['lat'][:]\ntime = x.variables['time'][:]\nco = x.variables['mCO_flux_fire'][:]\nxo = open_file('CO_10deg_monthly_for_transportcalc_850-1850.hdf','c')\nxo.create_dimension('lon',lon.size)\nxo.create_dimension('lat',lat.size)\nxo.create_dimension('time',time.size)\nxo.create_variable('lon','d',('lon',))\nxo.create_variable('lat','d',('lat',))\nxo.create_variable('time','i',('time',))\nxo.create_variable('mCO_flux_fire','f',('time','lat','lon'))\nxo.variables['lon'][:] = lon\nxo.variables['lat'][:] = lat\nxo.variables['time'][:] = time\nxo.variables['mCO_flux_fire'][:] = co\nxo.variables['mCO_flux_fire'].description = \"CO released by biomass burned\"\nxo.variables['mCO_flux_fire'].units = 'gC/m2'\nx.close()\nxo.close()\n\n\n\n","sub_path":"DATA/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"164057502","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nfrom functools import partial\nimport math\n\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\n\nfrom src.scenario_lib.src.items.media import Media\nfrom src.gui_video_db.src.ui import VideoDatabase\n\nclass Temporalization():\n def __init__(self, ui, canvas, robotMediaPlayer, changeCallback):\n self.ui = ui\n self.canvas = canvas\n self.robotMediaPlayer = robotMediaPlayer\n self.changeCallback = changeCallback\n \n self.lastMediaDirectory = \"\"\n self.timelineValueIsSetByCode = False\n self.temporalizationSplitter = None\n self.fullDuration = 0.\n self.isPlaying = False\n \n self.ui.timeline_slider.valueChanged.connect(self.handleTimelineSliderValueChanged)\n self.ui.addMediaBefore_button.clicked.connect(self.handleAddMediaBeforeButtonClicked)\n self.ui.addMediaAfter_button.clicked.connect(self.handleAddMediaAfterButtonClicked)\n self.ui.deleteMedia_button.clicked.connect(self.handleDeleteMediaButtonClicked)\n self.ui.playPause_button.clicked.connect(self.handlePlayPauseMediaButtonClicked)\n \n self.playingTimer = QTimer()\n self.playingTimer.setInterval(1000. / 25)\n self.playingTimer.timeout.connect(self.handlePlaying)\n self.playingTimer.start()\n \n # disable focus on all widgets and add event for key press\n self.ui.keyPressEvent = self.handleKeyPressEvent\n for child in self.ui.findChildren(QWidget):\n if callable(getattr(child, \"setFocusPolicy\", None)):\n child.setFocusPolicy(Qt.NoFocus)\n \n \n def update(self):\n # delete previous one\n if self.temporalizationSplitter is not None:\n for child in self.temporalizationSplitter.children():\n child.hide()\n del child\n \n \n self.ui.temporalization_widget.layout().removeWidget(self.temporalizationSplitter)\n del self.temporalizationSplitter\n \n # init a new one\n self.temporalizationSplitter = QSplitter(Qt.Horizontal)\n self.temporalizationSplitter.setChildrenCollapsible(False)\n self.ui.temporalization_widget.layout().addWidget(self.temporalizationSplitter)\n \n # add buttons\n mediaSizes = []\n self.temporalizationSplitter.setHandleWidth(1)\n handleWidth = self.temporalizationSplitter.handleWidth()\n splitterWidth = self.temporalizationSplitter.width() - handleWidth * (len(self.canvas.currentRobot.medias) - 1)\n i = 0\n self.fullDuration = 0.\n for media in self.canvas.currentRobot.medias:\n self.fullDuration += media.duration\n \n for media in self.canvas.currentRobot.medias:\n mediaButton = QPushButton(media.niceName + \"\\n\" + str(float(int((media.duration) * 10) / 10)) + \" s\")\n mediaButton.setStyleSheet(\"background: \" + media.color.name() + \"; text-align: left;\")\n mediaButton.setMinimumWidth(1)\n mediaButton.setCheckable(True)\n mediaButton.setFocusPolicy(Qt.NoFocus)\n mediaButton.clicked.connect(partial(self.updateMedia, mediaButton))\n \n self.temporalizationSplitter.addWidget(mediaButton)\n \n # icon\n mediaButton.setIcon(media.thumbnailIcon)\n iconHeight = self.ui.temporalization_widget.height() * 1.55\n mediaButton.setIconSize(QSize(iconHeight / media.thumbnailRatio, iconHeight))\n \n # get size for the end\n mediaSize = (float(media.duration) / float(self.fullDuration)) * splitterWidth\n if len(self.canvas.currentRobot.medias) > 1:\n mediaSize -= handleWidth / (2 if (i == 0 or i == len(mediaSizes) - 1) else 1)\n \n mediaSizes.append(mediaSize)\n \n i += 1\n \n for i in range(self.temporalizationSplitter.count()):\n self.temporalizationSplitter.handle(i).setEnabled(False)\n \n # set good mediaSizes\n self.temporalizationSplitter.setSizes(mediaSizes)\n self.handleTimelineSliderValueChanged()\n \n self.changeCallback()\n \n\n def updateMedia(self, checkedMediaButton = None):\n previousMedia = self.robotMediaPlayer.currentVideoMediaSource\n \n mediaToPlay = None\n # check each timeline buttons\n for i in range(self.temporalizationSplitter.count()):\n mediaButton = self.temporalizationSplitter.widget(i)\n # uncheck others\n if mediaButton != checkedMediaButton and checkedMediaButton is not None:\n mediaButton.setChecked(False)\n # check if they have focus to display media\n if mediaButton.isChecked():\n # put the media on the player\n mediaToPlay = self.canvas.currentRobot.medias[i]\n \n if mediaToPlay is None or mediaToPlay.media != previousMedia:\n self.robotMediaPlayer.stop()\n self.robotMediaPlayer.setCurrentMedia(mediaToPlay)\n \n \n def setTimelineValueCurrentMedia(self, value):\n self.timelineValueIsSetByCode = True\n if self.robotMediaPlayer.currentMedia is not None:\n currentMediaStartTime = 0\n for media in self.canvas.currentRobot.medias:\n if media == self.robotMediaPlayer.currentMedia:\n break\n else:\n currentMediaStartTime += media.duration\n \n if self.fullDuration != 0:\n newTimelineValue = currentMediaStartTime / self.fullDuration + value * (self.robotMediaPlayer.currentMedia.duration / self.fullDuration)\n newTimelineValue *= self.ui.timeline_slider.maximum()\n self.ui.timeline_slider.setValue(int(newTimelineValue))\n \n self.timelineValueIsSetByCode = False\n \n \n def playNextMedia(self):\n #TODO: conditions depending on the type of media\n if self.robotMediaPlayer.currentMedia is not None:\n currentMediaIndex = self.canvas.currentRobot.medias.index(self.robotMediaPlayer.currentMedia)\n if currentMediaIndex < len(self.canvas.currentRobot.medias) - 1:\n mediaButton = self.temporalizationSplitter.widget(currentMediaIndex + 1)\n mediaButton.setChecked(True)\n self.updateMedia(mediaButton)\n self.robotMediaPlayer.seek(0)\n #self.play()\n else:\n mediaButton = self.temporalizationSplitter.widget(0)\n mediaButton.setChecked(True)\n self.updateMedia(mediaButton)\n self.robotMediaPlayer.stop()\n \n \n def setTimelineTime(self, timelineTime):\n if self.fullDuration > 0:\n self.handleTimelineSliderValueChanged(int(((float(timelineTime) / 1000) / self.fullDuration) * self.ui.timeline_slider.maximum()))\n \n \n def getTimelineTime(self):\n return ((float(self.ui.timeline_slider.value()) / self.ui.timeline_slider.maximum()) * self.fullDuration) * 1000\n \n \n def handleAddMediaBeforeButtonClicked(self, event):\n VideoDatabase(self.handleVideoSelected, True)\n \n \n def handleAddMediaAfterButtonClicked(self, event):\n VideoDatabase(self.handleVideoSelected, False)\n \n \n def handleVideoSelected(self, filePath, before = False):\n if filePath is not None:\n filePath = str(filePath.encode(\"utf-8\"))\n self.lastMediaDirectory = os.path.dirname(filePath)\n \n # create media\n if self.robotMediaPlayer.currentMedia is not None:\n currentMediaIndex = 0\n if len(self.canvas.currentRobot.medias) > 0:\n currentMediaIndex = 0\n for media in self.canvas.currentRobot.medias:\n if media == self.robotMediaPlayer.currentMedia:\n break\n currentMediaIndex += 1\n if not before:\n currentMediaIndex += 1\n self.canvas.currentRobot.medias.insert(currentMediaIndex, Media(filePath))\n else:\n self.canvas.currentRobot.medias.append(Media(filePath))\n \n \n self.update()\n \n self.temporalizationSplitter.refresh()\n \n \n def handleDeleteMediaButtonClicked(self, event):\n mediaToDelete = self.robotMediaPlayer.currentMedia\n # replace times to fill the gap \n if len(self.canvas.currentRobot.medias) > 1:\n mediaToDeleteIndex = self.canvas.currentRobot.medias.index(mediaToDelete)\n \n # remove it\n self.canvas.currentRobot.medias.remove(mediaToDelete)\n mediaToDelete.destroy()\n mediaToDelete = None\n \n self.update()\n \n \n def handleTimelineSliderValueChanged(self, value = -1):\n if value == -1:\n value = self.ui.timeline_slider.value()\n \n value = float(value) / (self.ui.timeline_slider.maximum() + 1)\n \n if not self.timelineValueIsSetByCode:\n timelineValue = value * self.fullDuration\n \n if len(self.canvas.currentRobot.medias) > 0:\n # set current media\n currentDuration = 0\n mediaIndex = 0\n for media in self.canvas.currentRobot.medias:\n currentDuration += media.duration\n \n if timelineValue <= currentDuration:\n mediaSeek = int((timelineValue - (currentDuration - media.duration)) * 1000)\n self.robotMediaPlayer.seek(mediaSeek)\n mediaButton = self.temporalizationSplitter.widget(mediaIndex)\n mediaButton.setChecked(True)\n self.updateMedia(mediaButton)\n break\n \n mediaIndex += 1\n else:\n self.updateMedia()\n \n # update canvas\n self.canvas.currentTimelinePosition = value\n self.ui.timeline_groupBox.setTitle(\"Timeline - \" + str((float(math.floor(self.canvas.currentTimelinePosition * self.fullDuration * 100)) / 100)) + \" s\")\n self.canvas.update()\n \n \n def handlePlaying(self):\n if self.isPlaying:\n toSeek = self.robotMediaPlayer.currentTime() + self.playingTimer.interval()\n if toSeek < self.robotMediaPlayer.totalTime():\n self.robotMediaPlayer.seek(int(toSeek))\n else:\n self.robotMediaPlayer.handleVideoPlayerFinished()\n \n \n def handlePlayPauseMediaButtonClicked(self):\n if self.isPlaying:\n self.pause()\n else:\n self.play()\n \n \n def play(self):\n if self.robotMediaPlayer.currentMedia is not None:\n self.ui.playPause_button.setText(\"||\")\n self.isPlaying = True\n \n \n def pause(self):\n self.ui.playPause_button.setText(\">\")\n self.isPlaying = False\n \n \n def handleKeyPressEvent(self, event):\n # play / pause\n if event.key() == Qt.Key_Space:\n self.handlePlayPauseMediaButtonClicked()\n \n # move forward / backward\n smallInterval = 2000. / 25\n bigInterval = smallInterval * 25\n currentTime = (self.canvas.currentTimelinePosition * 1000.) * self.fullDuration\n if event.key() == Qt.Key_Left:\n toSeek = int(currentTime - smallInterval)\n if toSeek > 0:\n self.robotMediaPlayer.seek(toSeek)\n if event.key() == Qt.Key_Right:\n toSeek = int(currentTime + smallInterval)\n if toSeek < self.fullDuration * 1000:\n self.robotMediaPlayer.seek(toSeek)\n if event.key() == Qt.Key_PageDown:\n toSeek = int(currentTime - bigInterval)\n if toSeek > 0:\n self.setTimelineTime(toSeek)\n if event.key() == Qt.Key_PageUp:\n toSeek = int(currentTime + bigInterval)\n if toSeek < self.fullDuration * 1000:\n self.setTimelineTime(toSeek)\n","sub_path":"src/gui_scenario_builder/src/ui/temporalization.py","file_name":"temporalization.py","file_ext":"py","file_size_in_byte":12380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"478655337","text":"\ndef main(j, args, params, tags, tasklet):\n params.merge(args)\n\n doc = params.doc\n tags = params.tags\n\n params.result = \"\"\n\n\n # spaces = sorted(j.core.portal.active.getSpaces())\n # spacestxt=\"\"\n # for item in spaces:\n # if item[0] != \"_\" and item.strip() != \"\" and item.find(\"space_system\")==-1 and item.find(\"test\")==-1 and item.find(\"gridlogs\")==-1:\n # spacestxt += \"%s:/%s\\n\" % (item, item.lower().strip(\"/\"))\n\n\n C = \"\"\"\n{{menudropdown: name:Doc\nEdit:/system/edit?space=$$space&page=$$page\n--------------\nLogout:/system/login?user_logoff_=1\nAccess:/system/OverviewAccess?space=$$space\nSystem:/system\n--------------\nDoc Core:/doc_jumpscale_core\nDoc Devel:/doc_jumpscale_devel\nDoc Grid:/doc_jumpscale_grid\nDoc Howto:/doc_jumpscale_howto\nDoc Portal:/doc_jumpscale_portal\n\"\"\"\n # C+=spacestxt\n C+='}}'\n\n#was inside\n#Reload:javascript:$.ajax({'url': '/system/ReloadSpace?name=$$space'}).done(function(){location.reload()});void(0);\n#ShowLogs:/system/ShowSpaceAccessLog?space=$$space\n#ResetLogs:/system/ResetAccessLog?space=$$space\n#Spaces:/system/Spaces\n#Pages:/system/Pages?space=$$space\n#ReloadAll:javascript:(function loadAll() {$.ajax({'url': '/system/ReloadApplication'});(function checkSpaceIsUp(trials) {if (trials <= 0) return;setTimeout(function() {$.ajax({'url': '/system/'}).done(function(){location.reload();console.log('Reloaded');}).error(function(){checkSpaceIsUp(trials - 1)});}, 1000);})(10);})();void(0);\n\n if j.core.portal.active.isAdminFromCTX(params.requestContext):\n params.result = C\n\n params.result = (params.result, doc)\n\n return params\n\n\ndef match(j, args, params, tags, tasklet):\n return True\n","sub_path":"lib/portal/portalloaders/templates/space/.macros/wiki/menuadmin_jdoc/1_menuadmin.py","file_name":"1_menuadmin.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"323840425","text":"import praw\nimport pprint\nimport requests\nimport re\n\n# function that checks the content type from the headers and determines if it is downloadable or not\ndef is_downloadable(url):\n h = requests.head(url, allow_redirects=True)\n header = h.headers\n content_type = header.get('content-type')\n if 'text' in content_type.lower() or 'html' in content_type.lower():\n return False\n return True\n\n# function that gets the filename from the url. The filename is the characters to the right of the last backslash\ndef get_filename_from_url(url):\n if url.find('/'):\n return url.rsplit('/', 1)[1]\n\n# Initialize the reddit praw instance with the credentials defined in the praw.ini files\nreddit = praw.Reddit('GoDeepFry', user_agent='windows:GoDeepFry:v0.1 (by /u/L-king)')\n\nsubreddit = reddit.subreddit('dankmemes')\nfolder = \"./memes/\"\nfor submission in subreddit.top(limit=100):\n # We only want the submissions that aren't v.redd.it videos, gifs or gifvs\n if submission.is_video == False and 'gifv' not in submission.url and 'gif' not in submission.url:\n if is_downloadable(submission.url):\n r = requests.get(submission.url, allow_redirects=True)\n filename = folder + get_filename_from_url(submission.url)\n open(filename, 'wb').write(r.content)","sub_path":"get-memes.py","file_name":"get-memes.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"437507569","text":"from scipy import interpolate\nimport numpy as np\nimport astropy.constants as const\n\nmars_cmf = 0.26\nearth_cmf = 0.33\ncmfs_of_interest = [earth_cmf]\nsource_location = \"/Users/sabrinaberger/RockyPlanets/DataFiles/\"\nfinal_location = \"/Users/sabrinaberger/RockyPlanets/MassRadiusDiagramData/\"\n\ndef grid_to_1Darray(grid):\n compressed = []\n for i in range(grid.shape[0]):\n for j in range(grid.shape[1]):\n compressed.append(grid[i][j])\n return compressed\n\ndef planet_interp(location, label, anchor_temps, cmf_of_interest):\n mass_plots = []\n radius_plots = []\n for temp in anchor_temps:\n properties = []\n p_c_list = grid_to_1Darray(np.load(source_location + \"p_c\" + label + str(temp) + \".pyc\" + \".npy\"))\n p_cmb_pc_list = grid_to_1Darray(np.load(source_location + \"p_cmb_percentage\" + label + str(temp) + \".pyc\" + \".npy\"))\n mass_list = grid_to_1Darray(np.load(source_location + \"mass_grid\" + label + str(temp) + \".pyc\" + \".npy\"))\n radius_list = grid_to_1Darray(np.load(source_location + \"radius_grid\" + label + str(temp) + \".pyc\" + \".npy\"))\n cmf_list = grid_to_1Darray(np.load(source_location + \"core_mass_grid\" + label + str(temp) + \".pyc\" + \".npy\"))\n cmr_list = grid_to_1Darray(np.load(source_location + \"core_rad_grid\" + label + str(temp) + \".pyc\" + \".npy\"))\n p_c_unique_dict = {}\n mass_values = [] # test plots\n radius_values = [] # test plots\n i = 0\n while i < p_c_list.__len__():\n p_c = p_c_list[i]\n if str(p_c) in p_c_unique_dict:\n p_c_unique_dict.get(str(p_c)).append(i)\n else:\n p_c_unique_dict[str(p_c)] = [i]\n i += 1\n for p_c in p_c_unique_dict.keys():\n desired_indices = p_c_unique_dict.get(str(p_c))\n desired_p_cmb_p_c_list = []\n desired_mass_list = []\n desired_radius_list = []\n desired_cmf_list = []\n desired_cmr_list = []\n for j in desired_indices:\n desired_p_cmb_p_c_list.append(p_cmb_pc_list[j])\n desired_mass_list.append(mass_list[j])\n desired_radius_list.append(radius_list[j])\n desired_cmf_list.append(cmf_list[j])\n desired_cmr_list.append(cmr_list[j])\n\n p_cmb_p_c = interpolate.interp1d(desired_cmf_list, desired_p_cmb_p_c_list, bounds_error=False, fill_value=\"extrapolate\")\n p_cmb_p_c_cmf0 = p_cmb_p_c(cmf_of_interest)\n mass = interpolate.interp1d(desired_p_cmb_p_c_list, desired_mass_list)\n radius = interpolate.interp1d(desired_p_cmb_p_c_list, desired_radius_list)\n cmr = interpolate.interp1d(desired_p_cmb_p_c_list, desired_cmr_list)\n\n mass_cmf0 = mass(p_cmb_p_c_cmf0)\n radius_cmf0 = radius(p_cmb_p_c_cmf0)\n cmr_cmf0 = cmr(p_cmb_p_c_cmf0)\n # properties = [temp, cmf_of_interest, p_cmb_p_c_cmf0, cmr, mass_cmf0, radius_cmf0, cmr_cmf0]\n # np.save(final_location + str(temp) + \"_\" + str(cmf_of_interest) + \".pyc\", properties)\n mass_values.append(mass_cmf0)\n radius_values.append(radius_cmf0)\n mass_values = np.array(mass_values)/const.M_earth\n radius_values = np.array(radius_values)/const.R_earth\n print(\"done\")\n return np.sort(mass_values), np.sort(radius_values)\n\n #save interpolated values\n\n\n\n","sub_path":"adiabat_constant_interpolation.py","file_name":"adiabat_constant_interpolation.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"624237284","text":"\n\nfrom xai.brain.wordbase.nouns._instigator import _INSTIGATOR\n\n#calss header\nclass _INSTIGATORS(_INSTIGATOR, ):\n\tdef __init__(self,): \n\t\t_INSTIGATOR.__init__(self)\n\t\tself.name = \"INSTIGATORS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"instigator\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_instigators.py","file_name":"_instigators.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"65020863","text":"\"\"\" time O(n^2), space O(1)\n$ python3 quick_sort_pivot_end.py 2 5 3 1 4 6\n['2', '5', '3', '1', '4', '6']\n['1', '3', '2', '4', '5', '6']\n$ python3 quick_sort_pivot_end.py 2 5 3 1 4 6 0 0 0 7\n['2', '5', '3', '1', '4', '6', '0', '0', '0', '7']\n['0', '0', '0', '1', '2', '3', '4', '5', '6', '7']\n\n\"\"\"\n\nimport sys\n\n\ndef partition(a: list, low: int, high: int) -> int:\n p = a[high]\n j = low - 1\n for i in range(low, high):\n if a[i] >= p:\n continue\n j += 1\n a[j], a[i] = a[i], a[j]\n j += 1\n a[j], a[high] = a[high], a[j]\n return j\n\ndef quick_sort(a: list, low, high) -> None:\n if high - low <= 1:\n return\n j = partition(a, low, high)\n quick_sort(a, low, j - 1)\n quick_sort(a, j+1, high)\n\n\nif __name__ == \"__main__\":\n a = sys.argv[1:]\n print(a)\n quick_sort(a, 0, len(a) - 1)\n print(a)\n\n","sub_path":"algo-ds/sorts/quick_sort_pivot_end.py","file_name":"quick_sort_pivot_end.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"512630682","text":"import json\n\nimport image_fetch_utils as ifu\nimport image_fetch_dataset as ifd\nfrom config import get_config_path\n\nwith open(get_config_path()) as cfg_file:\n cfg_data = json.load(cfg_file)\n out_path = cfg_data['file_paths']['output_path']\n test_img_path = cfg_data['file_paths']['test_image_path']\n train_img_path = cfg_data['file_paths']['train_image_path']\n mat_path = cfg_data['file_paths']['mat_path']\n csv_path = cfg_data['file_paths']['csv_path']\n\nvgd, potentials = None, None\nplatt_mod, bin_mod, queries = None, None, None\nifdata, hf = None, None\ndata_loaded = None\n\n\ndef _load(dataset='stanford', split='test', use_csv=False):\n \"\"\"Helper function which loads data and caches it for later use.\"\"\"\n global data_loaded, vgd, potentials, platt_mod, bin_mod, queries, ifdata\n if (dataset, split) != data_loaded:\n data = ifu.get_mat_data(mat_path, get_potentials=not use_csv,\n get_bin_mod=not use_csv,\n get_platt_mod=not use_csv)\n vgd, potentials, platt_mod, bin_mod, queries = data\n img_path = test_img_path if split == 'test' else train_img_path\n if use_csv:\n ifdata = ifd.CSVImageFetchDataset(\n dataset, split, vgd, img_path, csv_path)\n else:\n if dataset != 'stanford':\n raise ValueError('Dataset {} invalid for loading without CSV'\n .format(dataset))\n\n # Note that for non-CSV, changing splits only changes vg_data\n if split == 'test':\n vg_dataset = vgd['vg_data_test']\n elif split == 'train':\n vg_dataset = vgd['vg_data_train']\n else:\n raise ValueError('Split {} invalid for stanford dataset'\n .format(split))\n ifdata = ifd.ImageFetchDataset(vg_dataset, potentials, platt_mod,\n bin_mod, img_path)\n data_loaded = (dataset, split)\n\n\ndef get_all_data(*args, **kwargs):\n \"\"\"Retrieves an ImageFetchDataset object with all data inside, and\n all other auxillary data.\"\"\"\n global data_loaded, vgd, potentials, platt_mod, bin_mod, queries, ifdata\n _load(*args, **kwargs)\n return vgd, potentials, platt_mod, bin_mod, queries, ifdata\n\n\ndef get_ifdata(*args, **kwargs):\n \"\"\"Retrieves an ImageFetchDataset object with all data inside.\"\"\"\n global data_loaded, vgd, potentials, platt_mod, bin_mod, queries, ifdata\n _load(*args, **kwargs)\n return ifdata\n\n\ndef get_supplemental_data(*args, **kwargs):\n \"\"\"Retrieves all data which is not the ImageFetchDataset object.\"\"\"\n global data_loaded, vgd, potentials, platt_mod, bin_mod, queries, ifdata\n _load(*args, **kwargs)\n return vgd, potentials, platt_mod, bin_mod, queries\n","sub_path":"code/irsg_core/data_pull.py","file_name":"data_pull.py","file_ext":"py","file_size_in_byte":2836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"242953052","text":"from django.urls import path\nfrom product.views import *\n\napp_name = 'product'\n\nurlpatterns = [\n path('', ProductLV.as_view(), name='list'),\n path('<int:pk>/', ProductDV.as_view(), name='detail'),\n path('search/', SearchLView.as_view(), name='search'),\n # Example: /product/tag/\n path('tag/', TagCloudTV.as_view(), name='tag_cloud'),\n # Example: /product/tag/tagname/\n path('tag/<str:tag>/', TaggedObjectLV.as_view(), name='tagged_object_list'),\n]\n","sub_path":"product/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"215662778","text":"from icecube.shovelart import *\nfrom icecube import paraboloid\n\nimport math\n\nfrom .AnimatedParticle import PosAtTime\n\ndef axis2vertex(particle, time):\n return vec3d(-particle.dir*particle.speed*(time-particle.time))\n\ndef dist(particle, time):\n return math.sqrt((particle.dir*particle.speed*(time-particle.time)).mag2)\n\ndef bottom(particle, time, angle):\n return dist(particle, time) * math.tan(angle)\n\nclass ParticleUncertainty( PyArtist ):\n\n requiredTypes = [ paraboloid.I3ParaboloidFitParams ]\n\n def __init__( self ):\n PyArtist.__init__(self)\n\n self.defineSettings(dict(color=PyQColor.fromRgbF(0, 0, 1)))\n\n def create( self, frame, output ):\n params = frame[self.keys()[0]]\n particle = frame[self.keys()[0][:-len(\"FitParams\")]]\n color = self.setting(\"color\")\n\n # opening angle\n psi = math.sqrt((params.pbfErr1**2 + params.pbfErr2**2)/2.)\n\n nulltime = particle.time\n\n ### backward cylinder\n bcyl = output.addCylinder(PosAtTime(particle, 0.),\n 0. * vec3d(particle.dir),\n bottom(particle, 0., psi))\n\n # increasing height\n baxisFunc = LinterpFunctionVec3d(0. * vec3d(particle.dir), 0)\n baxisFunc.add(axis2vertex(particle, 0.), nulltime)\n baxisFunc.add(axis2vertex(particle, 0.), 40000)\n\n # decreasing radius\n btopFunc = LinterpFunctionFloat(bottom(particle, 0, psi), 0)\n btopFunc.add(0., nulltime)\n btopFunc.add(0., 40000)\n\n bcyl.setColor(color)\n bcyl.setAxis(baxisFunc)\n bcyl.setTopRadius(btopFunc)\n\n ### forward Cylinder\n fcyl = output.addCylinder(PosAtTime(particle, 0.),\n 0. * vec3d(particle.dir),\n bottom(particle, 0., psi))\n\n # moving vertex\n fvertexFunc = LinterpFunctionVec3d(vec3d(particle.pos), 0)\n fvertexFunc.add(vec3d(particle.pos), nulltime)\n fvertexFunc.add(PosAtTime(particle, 40000.), 40000)\n\n # increasing height\n faxisFunc = LinterpFunctionVec3d(0. * vec3d(particle.dir), 0)\n faxisFunc.add(0. * vec3d(particle.dir), nulltime)\n faxisFunc.add(axis2vertex(particle, 40000.), 40000)\n\n # increasing radius\n fbottomFunc = LinterpFunctionFloat(0., 0)\n fbottomFunc.add(0., nulltime)\n fbottomFunc.add(bottom(particle, 40000., psi), 40000)\n\n fcyl.setColor(color)\n fcyl.setLocation(fvertexFunc)\n fcyl.setAxis(faxisFunc)\n fcyl.setBaseRadius(fbottomFunc)\n\n\n","sub_path":"src/steamshovel/python/artists/ParticleUncertainty.py","file_name":"ParticleUncertainty.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"206739931","text":"import pandas\r\nimport os\r\nimport WolverineFunctions\r\n\r\ndef CreateCSVs(shapefile, runnumber, conn, filepath):\r\n views = ['activeair_clipped', 'air_rh_clipped', 'csimu_block_clipped',\r\n 'csirt1_clipped', 'csirt2_clipped', 'csirt3_clipped', 'csirt4_clipped',\r\n 'cslocation_clipped', 'cslogger_clipped',\r\n 'cspep1_clipped', 'cspep2_clipped', 'cspep3_clipped', 'cspep4_clipped',\r\n 'gsalldata_clipped', 'rad1_clipped', 'rad2_clipped']\r\n\r\n\r\n for view in views:\r\n table_df = pandas.read_sql_query(f\"SELECT * FROM {shapefile}.{view} WHERE fk_sensorrun = {runnumber}\", con=conn)\r\n\r\n table_df.to_csv(filepath + '\\clipped/' + f'{view}' + '.csv', encoding='utf-8')\r\n\r\n\r\ndef create_clipped_plots(shapefile, fk_sensorrun, conn, filepath):\r\n \"\"\"Creates individual plot csv's for each plot in a given schema\"\"\"\r\n uniqueplots = pandas.read_sql_query(f\"select distinct id from {shapefile}\", con=conn)\r\n\r\n views = ['activeair_clipped', 'air_rh_clipped', 'csimu_block_clipped',\r\n 'csirt1_clipped', 'csirt2_clipped', 'csirt3_clipped', 'csirt4_clipped',\r\n 'cslocation_clipped', 'cslogger_clipped',\r\n 'cspep1_clipped', 'cspep2_clipped', 'cspep3_clipped', 'cspep4_clipped',\r\n 'gsalldata_clipped', 'rad1_clipped', 'rad2_clipped']\r\n\r\n for view in views:\r\n path = filepath + f'\\clipped\\{view}_plots'\r\n\r\n if os.path.isdir(path):\r\n pass\r\n else:\r\n os.makedirs(path)\r\n\r\n print(f\"Creating plot tables for: {view}\\n\")\r\n for index, row in uniqueplots.iterrows():\r\n plotnumber = row['id']\r\n\r\n plottable = pandas.read_sql_query(f\"\"\"select * from {shapefile}.{view} \r\n where fk_sensorrun = {fk_sensorrun} \r\n and id = {plotnumber}\"\"\",\r\n con=conn)\r\n\r\n if plottable.empty == False:\r\n print(rf'/{view}_plot_{plotnumber}.csv created')\r\n plottable.to_csv(path + rf'/{view}_plot_{plotnumber}.csv', encoding='utf-8')\r\n\r\ndef main():\r\n create_clipped_plots(\"f119_rbtn\",1, WolverineFunctions.EstablishConnection(), WolverineFunctions.AskForFilepath())\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"FieldFunctions.py","file_name":"FieldFunctions.py","file_ext":"py","file_size_in_byte":2330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"423306410","text":"\"\"\"Посчитать количество строчных (маленьких) и прописных (больших) букв в\n введенной строке. Учитывать только английские буквы.\n\"\"\"\n\n\ndef count_letters(str_):\n \"\"\"Подсчет символов.\n\n :param str_: входная строка\n :return: кортеж. (low_number, up_number). low_number - количество строчных,\n up_number - количество пописных.\n \"\"\"\n # write your code here\n low_number = 0\n up_number = 0\n alef = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'\n for letters in str_:\n if letters in alef:\n if letters.islower():\n low_number+=1\n continue\n if letters.upper():\n up_number+=1\n\n print(low_number,up_number)\n\n #return (low_number, up_number) # write return value here\n\n\nif __name__ == '__main__':\n # здесь можно сделать ввод из консоли и проверить работу функции\n str_ = 'fvdfdgASDDWWWSDdedf!!!ваавыапкыеы'\n #print(count_letters(str_))\n count_letters(str_)\n","sub_path":"src/homework2/task4.py","file_name":"task4.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"77850624","text":"import os\nimport subprocess\nimport inspect\n\n__all__ = ['harness', 'compile']\n\ndef testsource(tests):\n source = '''\n unsigned int tests[{}][{}] = {{\n'''.format(len(tests), len(tests[0]))\n\n for test in tests:\n testvector = ', '.join([str(t) for t in test])\n source += '''\\\n {{ {} }}, \n'''.format(testvector)\n\n source += '''\\\n };\n'''\n return source\n\ndef bodysource(tests):\n return '''\n for(int i = 0; i < {ntests}; i++) {{\n unsigned int* test = tests[i];\n top->op_a = test[0];\n top->op_b = test[1];\n top->eval();\n std::cout << \"test_iter=\" << i << \", op_a=\" << test[0] << \", op_b=\" << test[1] << \", expected_res=\" << test[2] << \", actual_res=\" << top->res << \"\\\\n\";\n assert(top->res == test[2]);\n }}\n'''.format(ntests=len(tests))\n\ndef harness(top_name, opcode, tests):\n\n test = testsource(tests)\n body = bodysource(tests)\n return '''\\\n#include \"V{top_name}.h\"\n#include \"verilated.h\"\n#include <cassert>\n#include <iostream>\n\nint main(int argc, char **argv, char **env) {{\n Verilated::commandArgs(argc, argv);\n V{top_name}* top = new V{top_name};\n\n {test}\n\n top->op_code = {op};\n top->op_d_p = 0;\n\n {body}\n\n delete top;\n std::cout << \"Success\" << std::endl;\n exit(0);\n}}'''.format(test=test,body=body,top_name=top_name,op=opcode&0x1ff)\n\n\ndef compile(name, top_name, opcode, tests):\n print(\"========== BEGIN: Compiling verilator test harness ===========\")\n verilatorcpp = harness(top_name, opcode, tests)\n with open('build/sim_'+name+'.cpp', \"w\") as f:\n f.write(verilatorcpp)\n print(\"========== DONE: Compiling verilator test harness ===========\")\n\n\n\ndef run_verilator_test(verilog_file_name, driver_name, top_module):\n (_, filename, _, _, _, _) = inspect.getouterframes(inspect.currentframe())[1]\n file_path = os.path.dirname(filename)\n build_dir = os.path.join(file_path, 'build')\n print(\"========== BEGIN: Using verilator to generate test files =====\")\n assert not subprocess.call('verilator -I../rtl -Wno-fatal --cc {} --exe {}.cpp --top-module {}'.format(verilog_file_name, driver_name, top_module), cwd=build_dir, shell=True)\n print(\"========== DONE: Using verilator to generate test files =====\")\n print(\"========== BEGIN: Compiling verilator test ===================\")\n assert not subprocess.call('make -C obj_dir -j -f V{0}.mk V{0} -B'.format(top_module), cwd=build_dir, shell=True)\n print(\"========== DONE: Compiling verilator test ===================\")\n print(\"========== BEGIN: Running verilator test =====================\")\n assert not subprocess.call('./obj_dir/V{}'.format(top_module), cwd=build_dir, shell=True)\n print(\"========== DONE: Running verilator test =====================\")\n","sub_path":"tests/test_pe/verilator.py","file_name":"verilator.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"579859205","text":"#!/usr/bin/python\n# coding=utf-8\n##########################################################################\n\nimport os\nimport time\nimport mock\nfrom test import CollectorTestCase\nfrom test import get_collector_config\nfrom test import unittest\nfrom test import run_only\nfrom mock import patch\n\nfrom diamond.collector import Collector\nfrom loggly import LogglyCollector\n\n##########################################################################\n\n\ndef run_only_if_requirements_present(func):\n try:\n import requests\n except ImportError:\n requests = None\n try:\n import futures\n except ImportError:\n futures = None\n try:\n import bunch\n except ImportError:\n bunch = None\n return run_only(func,\n lambda: all((module is not None\n for module in [requests, futures, bunch])))\n\n\nclass TestLogglyCollector(CollectorTestCase):\n TEST_CONFIG = {\n 'interval': 10,\n 'subdomain': 'mocksub',\n 'username': 'mockuser',\n 'password': 'mockpass',\n 'metric': {\n 'testmetric': {\n 'field': 'mock.field',\n 'query': 'mock: query'\n },\n 'countmetric': {\n 'field': 'mock.field',\n 'count': 'true',\n 'query': 'mock: count_query'\n },\n 'badmetric': {\n 'field': 'mock.field',\n 'count': 'true',\n 'query': 'mock: bad'\n },\n 'unauthorizedmetric': {\n 'field': 'mock.field',\n 'count': 'true',\n 'query': 'mock: unauthorized'\n },\n 'forbiddenmetric': {\n 'field': 'mock.field',\n 'count': 'true',\n 'query': 'mock: forbidden'\n },\n 'gonemetric': {\n 'field': 'mock.field',\n 'count': 'true',\n 'query': 'mock: gone'\n },\n 'serverrormetric': {\n 'field': 'mock.field',\n 'count': 'true',\n 'query': 'mock: serverror'\n },\n 'notimplementedmetric': {\n 'field': 'mock.field',\n 'count': 'true',\n 'query': 'mock: not implemented'\n },\n 'throttledmetric': {\n 'field': 'mock.field',\n 'count': 'true',\n 'query': 'mock: throttled'\n },\n 'timeoutmetric': {\n 'field': 'mock.field',\n 'query': 'mock: timeout'\n },\n }\n }\n\n def mocked_requests_get(*args, **kwargs):\n class MockResponse:\n def __init__(self, json_data, status_code):\n self.json_data = json_data\n self.status_code = status_code\n\n def json(self):\n return self.json_data\n\n recorded_responses = {\n 'https://mocksub.loggly.com/apiv2/search?'\n 'q=mock: query&from=-10s&until=now':\n MockResponse({'rsid': {'id': 1}}, 200),\n 'https://mocksub.loggly.com/apiv2/search?'\n 'q=mock: count_query&from=-10s&until=now':\n MockResponse({'rsid': {'id': 1}}, 200),\n 'https://mocksub.loggly.com/apiv2/search?'\n 'q=mock: bad&from=-10s&until=now':\n MockResponse({'rsid': {'id': 1}}, 400),\n 'https://mocksub.loggly.com/apiv2/search?'\n 'q=mock: unauthorized&from=-10s&until=now':\n MockResponse({'rsid': {'id': 1}}, 401),\n 'https://mocksub.loggly.com/apiv2/search?'\n 'q=mock: forbidden&from=-10s&until=now':\n MockResponse({'rsid': {'id': 1}}, 403),\n 'https://mocksub.loggly.com/apiv2/search?'\n 'q=mock: gone&from=-10s&until=now':\n MockResponse({'rsid': {'id': 1}}, 410),\n 'https://mocksub.loggly.com/apiv2/search?'\n 'q=mock: serverror&from=-10s&until=now':\n MockResponse({'rsid': {'id': 1}}, 500),\n 'https://mocksub.loggly.com/apiv2/search?'\n 'q=mock: not implemented&from=-10s&until=now':\n MockResponse({'rsid': {'id': 1}}, 501),\n 'https://mocksub.loggly.com/apiv2/search?'\n 'q=mock: throttled&from=-10s&until=now':\n MockResponse({'rsid': {'id': 1}}, 503),\n 'https://mocksub.loggly.com/apiv2/search?'\n 'q=mock: timeout&from=-10s&until=now':\n MockResponse({'rsid': {'id': 1}}, 504),\n 'https://mocksub.loggly.com/apiv2/events?rsid=1':\n MockResponse({\n 'events': [{'timestamp': 1443092343,\n 'event': {'mock': {'field': 123.456}}}],\n 'total_events': 4}, 200)\n }\n try:\n return recorded_responses[args[1]]\n except:\n return MockResponse({}, 404)\n\n def setUp(self):\n config = get_collector_config('LogglyCollector',\n self.TEST_CONFIG)\n\n self.collector = LogglyCollector(config, None)\n\n def test_import(self):\n self.assertTrue(LogglyCollector)\n\n # @run_only_if_requirements_present\n @patch.object(Collector, 'publish_metric')\n def test(self, publish_mock):\n patch_requests_get = patch('requests.get',\n side_effect=self.mocked_requests_get)\n patch_requests_get.start()\n self.collector.collect()\n patch_requests_get.stop()\n\n published_metrics = {\n 'testmetric.mock.field': (123.456, None),\n 'countmetric.mock.field': (123.456, None),\n 'countmetric.count': 4\n }\n unpublished_metrics = {\n 'badmetric.mock.field': 0,\n 'unauthorizedmetric.mock.field': 0,\n 'forbiddenmetric.mock.field': 0,\n 'gonemetric.mock.field': 0,\n 'serverrormetric.mock.field': 0,\n 'notimplementedmetric.mock.field': 0,\n 'throttledmetric.mock.field': 0,\n 'timeoutmetric.mock.field': 0,\n 'testmetric.count': 0\n }\n\n self.assertPublishedMetricMany(publish_mock, published_metrics)\n self.assertUnpublishedMetricMany(publish_mock, unpublished_metrics)\n\n##########################################################################\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"src/collectors/loggly/test/testloggly.py","file_name":"testloggly.py","file_ext":"py","file_size_in_byte":6491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"203910828","text":"from project3.YOLOWithMobileNet.MoblieNetV2 import MobileNetV2\nfrom project3.YOLOWithMobileNet.SET import Set\nimport torch\nimport numpy\nimport cv2\nfrom time import time\nimport os\n\n\nclass Explorer:\n\n def __init__(self, is_cuda=False):\n self.set = Set()\n self.device = torch.device('cuda:0' if torch.cuda.is_available() and is_cuda else 'cpu')\n self.device = torch.device('cpu')\n self.net = MobileNetV2()\n self.net.load_state_dict(torch.load('D:/data/object3/netparm/net (2).pth'))\n self.net.eval()\n\n def explore(self, input_):\n start = time()\n input_ = torch.from_numpy(input_).float() / 255\n input_ = input_.permute(2, 0, 1).unsqueeze(0)\n input_ = input_.to(self.device) # 数据传入处理设备\n\n '''模型预测'''\n predict1, predict2, predict3 = self.net(input_)\n print('cost_time1:', time() - start)\n boxes1, category1 = self.select(predict1.detach().cpu().numpy(), 32, 13)\n boxes2, category2 = self.select(predict2.detach().cpu().numpy(), 16, 26)\n boxes3, category3 = self.select(predict3.detach().cpu().numpy(), 8, 52)\n boxes = numpy.vstack((boxes1, boxes2, boxes3))\n category = numpy.hstack((category1, category2, category3))\n boxes, category = self.nms_with_category(boxes, category)\n print('cost_time2:',time()-start)\n return boxes, category\n\n def select(self, predict, len_side, fm_size):\n \"\"\"\n 通过阈值筛选,并且完成反算。传输参数为array(N,C,H,W).\n\n 参数:\n predict: 预测值\n 返回:\n\n \"\"\"\n n, h, w, c, _ = predict.shape\n\n '''形状变换'''\n\n '''挑选置信度大于阈值的数据,获取位置索引'''\n predict[:, :, :, :, 0] = self.sigmoid(predict[:, :, :, :, 0])\n index = numpy.where(predict[:, :, :, :, 0] > self.set.threshold)\n\n '''获取宽高,框类索引'''\n index_h = index[1]\n index_w = index[2]\n box_base = index[3]\n\n '''通过索引,索引出数据'''\n boxes_with_category = predict[index]\n\n '''反算回原图'''\n c_x = (index_w + self.sigmoid(boxes_with_category[:, 1])) * len_side\n c_y = (index_h + self.sigmoid(boxes_with_category[:, 2])) * len_side\n\n w = numpy.exp(boxes_with_category[:, 3]) * self.set.boxes_base2[fm_size][box_base][:, 0]\n h = numpy.exp(boxes_with_category[:, 4]) * self.set.boxes_base2[fm_size][box_base][:, 1]\n\n x1 = c_x - w / 2\n y1 = c_y - h / 2\n\n x2 = x1 + w\n y2 = y1 + h\n\n '''计算所属类别'''\n category = boxes_with_category[:, 5:]\n category = numpy.argmax(category, axis=1)\n\n '''返回边框和类别信息'''\n return numpy.stack((boxes_with_category[:, 0], x1, y1, x2, y2), axis=1), category\n\n def nms_with_category(self, boxes, categorys):\n if boxes.size == 0:\n return numpy.array([]), numpy.array([])\n \"\"\"根据类别的不同,进行非极大值抑制\"\"\"\n picked_boxes = []\n picked_category = []\n for category_index in range(self.set.num_category):\n '''索引该类别的数据'''\n index = categorys == category_index\n box1 = boxes[index]\n '''排序'''\n order = numpy.argsort(box1[:, 0])[::-1]\n box1 = box1[order]\n\n while box1.shape[0] > 1:\n max_box = box1[0]\n picked_boxes.append(max_box)\n picked_category.append(numpy.array([category_index]))\n left_box = box1[1:]\n iou = self.calculate_iou(max_box, left_box)\n index = iou < self.set.iou_threshold\n box1 = left_box[index]\n if box1.shape[0] > 0:\n picked_boxes.append(box1[0])\n picked_category.append(numpy.array([category_index]))\n\n return numpy.vstack(picked_boxes), numpy.hstack(picked_category)\n\n def calculate_iou(slef, box1, box2):\n area1 = (box1[3] - box1[1]) * (box1[4] - box1[2])\n area2 = (box2[:, 3] - box2[:, 1]) * (box2[:, 4] - box2[:, 2])\n\n x1 = numpy.maximum(box1[1], box2[:, 1])\n y1 = numpy.maximum(box1[2], box2[:, 2])\n x2 = numpy.minimum(box1[3], box2[:, 3])\n y2 = numpy.minimum(box1[4], box2[:, 4])\n\n intersection_area = numpy.maximum(0, x2 - x1) * numpy.maximum(\n 0, y2 - y1)\n return intersection_area / numpy.minimum(area1, area2)\n\n def sigmoid(self, x):\n x = torch.from_numpy(x)\n x = torch.sigmoid(x)\n return x.numpy()\n\n\nif __name__ == '__main__':\n\n explorer = Explorer()\n set1 = Set()\n for file_name in os.listdir('D:/data/object3/dataset'):\n s = time()\n image = cv2.imread(f'D:/data/object3/dataset/{file_name}')\n boxes = explorer.explore(image)\n print(boxes)\n\n for box, index in zip(boxes[0], boxes[1]):\n name = set1.category[index]\n x1 = int(box[1])\n y1 = int(box[2])\n x2 = int(box[3])\n y2 = int(box[4])\n image = cv2.rectangle(image, (x1, y1), (x2, y2), (0, 0, 255), 1)\n image = cv2.putText(image, name, (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2)\n print(time()-s)\n cv2.imshow('JK', image)\n if cv2.waitKey(0) == ord('c'):\n continue","sub_path":"project3/YOLOWithMobileNet/EXPLORER.py","file_name":"EXPLORER.py","file_ext":"py","file_size_in_byte":5423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"517268805","text":"from django.shortcuts import render, redirect\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth import login, authenticate\n\nfrom .models import Product\nfrom .forms import SearchForm\n\n\ndef index(request):\n if request.method == 'POST':\n form = SearchForm(request.POST)\n if form.is_valid():\n\n return HttpResponseRedirect('/result/')\n else:\n form = SearchForm()\n\n products_list = Product.objects.all()\n\n paginator = Paginator(products_list, 25)\n\n page = request.GET.get('page')\n products = paginator.get_page(page)\n return render(request, 'home/index.html', {'form': form, 'products': products})\n\n\ndef result(request):\n keywords = ''\n if request.method == 'POST':\n form = SearchForm(request.POST)\n if form.is_valid():\n keywords = [element.strip() for element in form.cleaned_data['keywords'].split(',')]\n\n else:\n form = SearchForm()\n\n products = Product.objects.all()\n\n return render(request, 'home/result.html', {'form': form, 'keywords': keywords, 'products': products})\n\n\ndef intro(request):\n return render(request, 'home/intro.html')\n\n\ndef signup(request):\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n raw_password = form.cleaned_data.get('password1')\n user = authenticate(username=username, password=raw_password)\n login(request, user)\n return redirect('/')\n else:\n form = UserCreationForm()\n return render(request, 'home/signup.html', {'form': form})\n","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"568857392","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport healpy as hp\nimport os\n\ndef make_map_from_spectra(spectra, nside, lmax, resol, seed=1234, pixwin=False, verbose=False):\n np.random.seed(seed)\n cmb_map = hp.synfast(spectra, nside=nside, lmax=lmax, fwhm=np.radians(resol/60.0), new=True, pol=True, pixwin=pixwin, verbose=verbose)\n\n return cmb_map\n\nif __name__==\"__main__\":\n r_list = [0.0, 0.001, 0.01, 0.02, 0.03, 0.04, 0.05, 0.1] \n spectra_dir = \"../spectra/spectra_files\"\n spectra_tag = \"planck_params_r_variation_formatted\"\n\n out_dir = os.path.join(\"map_files/CMB_Fiducial\",spectra_tag)\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n nside_resol_lmax_list = ((16, 600.0, 47), (128, 60.0, 383))\n\n for r in r_list:\n print(\"Doing r = {}\".format(r))\n spectra_file = os.path.join(spectra_dir, spectra_tag, 'r'+str(r), 'lensedtotCls.npy')\n if os.path.isfile(spectra_file):\n print(\"{} : EXISTS\".format(spectra_file))\n else:\n print(\"{} : DOES NOT EXIST\".format(spectra_file))\n spectra = np.load(spectra_file)\n print(spectra.shape)\n for nside, resol, lmax in nside_resol_lmax_list:\n print(\"nside : {}\\nresol : {}\\nlmax : {}\\n\".format(nside, resol, lmax))\n cmb_map = make_map_from_spectra(spectra, nside, lmax, resol)\n out_dir_r = os.path.join(out_dir, 'r'+str(r))\n if not os.path.exists(out_dir_r):\n os.makedirs(out_dir_r)\n hp.write_map(os.path.join(out_dir_r, 'sky_map_ns_'+str(nside)+'_'+str(int(resol))+'_arcmins.fits'), cmb_map)\n","sub_path":"maps/generate_maps_from_spectra.py","file_name":"generate_maps_from_spectra.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"392924793","text":"import sys\r\nimport pygame\r\nfrom setting3 import Settings\r\nfrom ship3 import Ship\r\nfrom bullet3 import Bullet\r\n\r\n\r\nclass AlienInvasion:\r\n \"\"\"管理游戏资源的行为的类\"\"\"\r\n def __init__(self):\r\n \"\"\"初始化游戏并创建游戏资源\"\"\"\r\n pygame.init()\r\n self.settings = Settings()\r\n\r\n self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)\r\n self.settings.screen_width = self.screen.get_rect().width\r\n self.settings.screen_height = self.screen.get_rect().height\r\n self.screen = pygame.display.set_mode(\r\n (self.settings.screen_width, self.settings.screen_height))\r\n pygame.display.set_caption(\"Alien Invasion\")\r\n\r\n self.ship = Ship(self)\r\n self.bullets = pygame.sprite.Group()\r\n\r\n def run_game(self):\r\n \"\"\"开始游戏的主循环\"\"\"\r\n while True:\r\n self._cheak_events()\r\n self.ship.update()\r\n self.bullets.update()\r\n self._update_bullets()\r\n self._update_screen()\r\n\r\n def _cheak_events(self):\r\n \"\"\"响应按键和鼠标事件\"\"\"\r\n # 监视键盘和鼠标事件\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n sys.exit()\r\n elif event.type == pygame.KEYDOWN:\r\n self._cheak_keydown_events(event)\r\n\r\n elif event.type == pygame.KEYUP:\r\n self._cheak_keyup_events(event)\r\n\r\n def _cheak_keydown_events(self, event):\r\n \"\"\"按键\"\"\"\r\n if event.key == pygame.K_RIGHT:\r\n self.ship.moving_right = True\r\n elif event.key == pygame.K_LEFT:\r\n self.ship.moving_left = True\r\n elif event.key == pygame.K_SPACE:\r\n self._fire_bullet()\r\n elif event.key == pygame.K_q:\r\n sys.exit()\r\n\r\n def _cheak_keyup_events(self, event):\r\n \"\"\"松开\"\"\"\r\n if event.key == pygame.K_RIGHT:\r\n self.ship.moving_right = False\r\n elif event.key == pygame.K_LEFT:\r\n self.ship.moving_left = False\r\n\r\n def _fire_bullet(self):\r\n \"\"\"创建一颗子弹, 并将其加入编组bullets中\"\"\"\r\n if len(self.bullets) < self.settings.bullets_allowed:\r\n new_bullet = Bullet(self)\r\n self.bullets.add(new_bullet)\r\n\r\n def _update_bullets(self):\r\n \"\"\"更新子弹的位置并删除消失的子弹\"\"\"\r\n # 更新子弹的位置\r\n self.bullets.update()\r\n # 删除消失的子弹\r\n for bullet in self.bullets.copy():\r\n if bullet.rect.bottom <= 0:\r\n self.bullets.remove(bullet)\r\n print(len(self.bullets))\r\n\r\n def _update_screen(self):\r\n \"\"\"更新屏幕上的图像, 并切换到新屏幕\"\"\"\r\n # 每次循环时都重绘屏幕\r\n self.screen.fill(self.settings.bg_color)\r\n self.ship.blitme()\r\n for bullet in self.bullets.sprites():\r\n bullet.draw_bullet()\r\n # 让最近绘制的屏幕可见\r\n pygame.display.flip()\r\n\r\n\r\nif __name__ == '__main__':\r\n # 创建游戏实例并运行游戏\r\n ai = AlienInvasion()\r\n ai.run_game()\r\n","sub_path":"Python/alien_invasion_12/alian3.py","file_name":"alian3.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"193788886","text":"import os\nimport time\nimport json\nimport pickle\n\nfrom getNet import get_adj\nfrom getDict import get_dict\nfrom getNet import divide_name\n\n\ndef get_all_edge_time(net_name):\n \"\"\"\n 获得网络所有边的生成时间\n :param net_name:\n :return: {(node1, node2): edge_time, ...}\n \"\"\"\n net_type, net_time = divide_name(net_name)\n if net_type == 'sci_net_contacts':\n file_name = '.\\\\net_data\\\\' + net_type + \"\\\\edge_time\\\\\" + str(net_time) + 'edges_day.txt'\n edge_days = dict()\n had_file = os.path.exists(file_name)\n if had_file is False:\n edge_list = get_adj(net_name)\n with open(file_name, 'w') as f:\n for edge in edge_list:\n since = time.time()\n edge_day = 0\n # 常规找法,从前往后找\n adjs = dict() # 获取网络顺便存到内存中,加速\n for day in range(int(net_time)+1):\n # 获得该天的网络\n if day not in adjs.keys():\n adj = get_adj(net_type + \"%\" + str(day))\n adjs[day] = adj\n else:\n adj = adjs[day]\n # 判断边是否在该天\n if edge_day == 0 and edge in adj:\n edge_day = day\n break\n edge_days[edge] = edge_day\n f.write(str(edge) + \":\" + str(edge_day) + \"\\n\") # 持久化\n print(\"生成所有边的天数,第\", str(edge_list.index(edge)), \"条边\", edge, \"第\", day, \"天\",\n \"时间:\", str(time.time() - since))\n else:\n edge_days = get_dict(file_name)\n return edge_days\n elif net_type == 'ht09_contacts':\n file_name = '.\\\\net_data\\\\' + net_type + \"\\\\edge_time\\\\\" + str(net_type) + '_edges_day.txt'\n edge_days = dict()\n had_file = os.path.exists(file_name)\n if had_file is False:\n edge_list = get_adj(net_name)\n with open(file_name, 'w') as f:\n for edge in edge_list:\n since = time.time()\n edge_day = 0\n with open(\".\\\\net_data\\\\\" + net_type + \"\\\\ori_adj\\\\\" + \"ht09_contact.txt\", 'r') as ori_f:\n for line in ori_f:\n line = line.strip().split(' ')\n if edge == (int(line[1]), int(line[2])) or edge == (int(line[2]), int(line[1])):\n edge_day = int(line[0])\n break\n edge_days[edge] = edge_day\n f.write(str(edge) + \":\" + str(edge_day) + \"\\n\") # 持久化\n print(net_name + \"生成所有边的天数,第\", str(edge_list.index(edge)), \"条边\", edge,\n \"时间:\", str(time.time() - since))\n else:\n edge_days = get_dict(file_name)\n return edge_days\n elif net_type == 'ant':\n file_name = '.\\\\net_data\\\\' + net_type + \"\\\\edge_time\\\\\" + str(net_type) + '_edges_day.txt'\n edge_days = dict()\n had_file = os.path.exists(file_name)\n if had_file is False:\n edge_list = get_adj(net_name)\n with open(file_name, 'w') as f:\n for edge in edge_list:\n since = time.time()\n _days = []\n with open(\".\\\\net_data\\\\\" + net_type + \"\\\\ori_adj\\\\\" + \"Ant_Adj_py.txt\", 'r') as ori_f:\n for line in ori_f:\n line = line.strip().split(' ')\n if edge == (int(line[0]), int(line[1])) or edge == (int(line[1]), int(line[0])):\n _days.append(int(line[2]))\n edge_days[edge] = min(_days)\n f.write(str(edge) + \":\" + str(edge_days[edge]) + \"\\n\") # 持久化\n print(net_name + \"生成所有边的天数,第\", str(edge_list.index(edge)), \"条边\", edge,\n \"时间:\", str(time.time() - since))\n else:\n edge_days = get_dict(file_name)\n return edge_days\n elif net_type == 'facebook':\n file_name = '.\\\\net_data\\\\' + net_type + \"\\\\edge_time\\\\\" + str(net_type) + '_edges_day.txt'\n edge_days = dict()\n had_file = os.path.exists(file_name)\n if had_file is False:\n edge_list = set(get_adj(net_name))\n with open(file_name, 'w') as f:\n edge_num = 0\n with open(\".\\\\net_data\\\\\" + net_type + \"\\\\ori_adj\\\\\" + \"facebook.edges\", 'r') as ori_f:\n since = time.time()\n for line in ori_f:\n line = line.replace('\\t', '').strip().split(' ')\n edge = (int(line[0]), int(line[1]))\n if edge in edge_list or (int(line[1]), int(line[0])) in edge_list:\n if edge not in edge_days.keys() and (int(line[1]), int(line[0])) not in edge_days.keys():\n edge_day = int(line[2])\n edge_days[edge] = edge_day\n f.write(str(edge) + \":\" + str(edge_days[edge]) + \"\\n\") # 持久化\n edge_num += 1\n if edge_num % 1000 == 0:\n print(net_name + \"生成所有边的天数,第\", edge_num, \"条边\", edge,\n \"时间:\", str(time.time() - since))\n since = time.time()\n else:\n edge_days = get_dict(file_name)\n return edge_days\n elif net_type == 'coauthor':\n file_name = '.\\\\net_data\\\\' + net_type + \"\\\\edge_time\\\\\" + str(net_type) + '_edges_day.txt'\n edge_days = dict()\n had_file = os.path.exists(file_name)\n if had_file is False:\n edge_list = set(get_adj(net_name))\n edge_num = 0\n with open(file_name, 'w') as f:\n with open(\".\\\\net_data\\\\\" + net_type + \"\\\\ori_adj\\\\\" + \"tmp_dblp_coauthorship.json\", 'r') as ori_f:\n json_data = json.load(ori_f)\n with open(\".\\\\net_data\\\\\" + net_type + \"\\\\ori_adj\\\\\" + \"author_id_map.pickle\",\n 'rb') as author_id_map_file:\n author_list = pickle.load(author_id_map_file)\n since = time.time()\n for data in json_data:\n if data[2] is not None:\n data_edge = (author_list[data[0]], author_list[data[1]]) if data_edge in edge_list \\\n else (author_list[data[1]], author_list[data[0]])\n if edge_num % 1000 == 0:\n print(net_name + \"生成所有边的天数,第\", edge_num, \"条边\", data_edge,\n \"时间:\", str(time.time() - since), \"数据:\", data)\n since = time.time()\n edge_num += 1\n # 如过没有添加过这条边,则添加这条边及其时间,否则比较当前的时间和之前时间取较小的\n if data_edge not in edge_days.keys() and (data_edge[1], data_edge[0]) not in edge_days.keys():\n edge_days[data_edge] = int(data[2])\n else:\n edge_days[data_edge] = int(data[2]) if int(data[2]) < edge_days[data_edge]\\\n else edge_days[data_edge]\n for edge in edge_days.keys():\n f.write(str(edge) + \":\" + str(edge_days[edge]) + \"\\n\") # 持久化\n else:\n edge_days = get_dict(file_name)\n return edge_days\n elif net_type == 'fungi' or net_type == 'human' or net_type == 'fruit_fly' or net_type == 'worm'\\\n or net_type == 'bacteria':\n file_name = '.\\\\net_data\\\\' + net_type + \"\\\\edge_time\\\\\" + str(net_time) + '_edges_day.txt'\n edge_days = dict()\n had_file = os.path.exists(file_name)\n if had_file is False:\n edge_list = get_adj(net_name)\n adjs = dict() # 获取网络顺便存到内存中,加速\n with open(file_name, 'w') as f:\n for edge in edge_list:\n since = time.time()\n edge_day = 0\n # 常规找法,从前往后找\n for day in range(1, int(net_time)+1):\n if day not in adjs.keys():\n adj = get_adj(net_type + \"%\" + str(day))\n adjs[day] = adj\n else:\n adj = adjs[day]\n # 判断边是否在该天\n if edge_day == 0 and edge in adj:\n edge_day = day\n break\n edge_days[edge] = edge_day\n f.write(str(edge) + \":\" + str(edge_day) + \"\\n\") # 持久化\n print(\"生成所有边的天数,第\", str(edge_list.index(edge)), \"条边\", edge, \"第\", day, \"天\",\n \"时间:\", str(time.time() - since))\n else:\n edge_days = get_dict(file_name)\n return edge_days\n\n\ndef is_different_time(edge_pair, edge_days):\n \"\"\"\n 判断两条边的新旧关系\n :param edge_pair: ((node1, node2), (node3, node4))\n :param edge_days: get_all_edge_day(day)\n :return:\n -1,同一天的边, 或无法判断新旧的边对\n 1,前一条边为新边\n 0,后一条边为新边\n \"\"\"\n edge1, edge2 = edge_pair[0], edge_pair[1]\n if edge1 in edge_days.keys() and edge2 in edge_days.keys():\n day1 = edge_days[edge1]\n day2 = edge_days[edge2]\n # 判断前一条边是否为新边或者不可区分两条边的新旧\n if day1 < day2:\n new = 0\n elif day1 > day2:\n new = 1\n else:\n new = -1\n return new\n else:\n return -1\n\n\ndef get_sorted_edge_time(edge_days):\n \"\"\"\n 将不规范的时间点按顺序变为0,1,2,...这样的形式\n 边顺序不变\n :param edge_days:\n :return:\n \"\"\"\n days = set(edge_days.values())\n sorted_days = sorted(days)\n for edge in edge_days:\n edge_days[edge] = sorted_days.index(edge_days[edge])\n return edge_days\n\n\nif __name__ == '__main__':\n # _edge_days_ = get_all_edge_time(\"sci_net_contacts%51\")\n # get_all_edge_time('ht09_contacts%')\n # get_all_edge_time(\"ant%\")\n # get_all_edge_time(\"fungi%4\")\n # get_all_edge_time(\"human%7\")\n # get_all_edge_time(\"fruit_fly%5\")\n # get_all_edge_time(\"worm%4\")\n # get_all_edge_time(\"bacteria%2\")\n # get_all_edge_time(\"facebook%\")\n get_all_edge_time(\"coauthor%\")\n","sub_path":"getEdgeTime.py","file_name":"getEdgeTime.py","file_ext":"py","file_size_in_byte":11136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"53406561","text":"import asyncio\nimport os.path\n\nfrom ..abstract_task import AbstractTask\n\n\nclass DownloadFileTask(AbstractTask):\n _expected_required_params = {\n \"url\": str\n }\n\n _expected_optional_params = {\n \"file_name\": str\n }\n\n async def run_task(self, output_dir, *args, **kwargs):\n url = self.required_params[\"url\"]\n file_name = self.optional_params.get(\"file_name\", \"\")\n\n if file_name:\n file_name += get_file_type(url)\n else:\n file_name = get_file_name(url)\n\n file_path = os.path.join(output_dir, file_name)\n file_path = adjust_file_name_for_duplicates(file_path)\n\n command = \"curl -o \\\"./%s\\\" \\\"%s\\\"\" % (file_path, url)\n\n process = await asyncio.create_subprocess_shell(\n command, stdout=asyncio.subprocess.PIPE)\n\n stdout, stderr = await process.communicate()\n\n is_success = process.returncode == 0\n\n if is_success:\n print(stdout)\n else:\n print(stderr)\n\n return is_success\n\n\ndef get_file_type(file_name):\n index = file_name.rindex(\".\")\n if index > 0:\n return file_name[index:]\n\n raise ValueError(\"Unknown file type for: %s\" % file_name)\n\n\ndef get_file_name(url):\n index = url.rindex(\"/\")\n if index > 0:\n return url[index + 1:]\n\n raise ValueError(\"Invalid url: %s\" % url)\n\n\ndef adjust_file_name_for_duplicates(file_full_name):\n if not os.path.exists(file_full_name):\n return file_full_name\n\n file_name, file_type = file_full_name.rsplit(\".\", 1)\n\n for i in range(1, 101):\n file_full_name = \"%s(%d).%s\" % (file_name, i, file_type)\n\n if not os.path.exists(file_full_name):\n return file_full_name\n\n raise OSError(\"File name cannot be used, too many duplicates\")\n","sub_path":"pidelegator/tasks/implemented/download_file_task.py","file_name":"download_file_task.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"237199683","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@author:knktc\n@contact:me@knktc.com\n@create:2018-07-20 22:31\n\"\"\"\n\n\"\"\"\nGiven an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.\n\nExample:\n\nInput: [-2,1,-3,4,-1,2,1,-5,4],\nOutput: 6\nExplanation: [4,-1,2,1] has the largest sum = 6.\nFollow up:\n\nIf you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.\n\n\"\"\"\n\n\"\"\"\n最大子序列和问题\n相加后为负值的子序列不能作为最优子序列的开头,可以被排除掉。\n使用一个临时sum值来存储子序列的和值。\n\n\"\"\"\n\n__author__ = 'knktc'\n__version__ = '0.1'\n\n\nclass Solution:\n def maxSubArray(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n tmp_value = nums[0]\n max_sum = tmp_value\n\n for i in nums[1:]:\n if tmp_value + i < i:\n tmp_value = i\n else:\n tmp_value += i\n\n if max_sum < tmp_value:\n max_sum = tmp_value\n\n return max_sum\n\n\n\ndef main():\n \"\"\"\n main process\n\n \"\"\"\n s = Solution()\n\n test_cases = [\n [-2, 1, -3, 4, -1, 2, 1, -5, 4],\n [1],\n [-2, 1]\n ]\n for case in test_cases:\n print(\"==========\")\n print(\"input: {}\".format(case))\n print(\"output: {}\".format(s.maxSubArray(nums=case)))\n\n\nif __name__ == '__main__':\n main()","sub_path":"python/53.Maximum_Subarray.py","file_name":"53.Maximum_Subarray.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"193999223","text":"from django.conf.urls import patterns, url\nfrom voting import views\n\nurlpatterns = patterns('',\n \n #main voting page\n url(r'^$', views.index, name='index'),\n \n # voting mechanics\n url(r'^(?P<sub_id>\\d+)/detail$', views.detail, name='detail'),\n url(r'^(?P<sub_id>\\d+)/vote$', views.vote, name='vote'),\n url(r'^(?P<sub_id>\\d+)/result$', views.result, name='result'),\n \n # submission mechanics \n url(r'^form$', views.form, name='form'),\n url(r'^form_recv$', views.form_recv, name='form_recv'),\n)\n","sub_path":"voting/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"371916927","text":"from PIL import Image, ImageDraw\n\nphotolist = ['LCM + CSZD1.png','LCM + CSZD2.png','LCM + CSZD3.png']\n\n\n\nfor photo in photolist :\n\n im = Image.open(photo)\n d = ImageDraw.Draw(im)\n\n\n height = 2320\n width = 3480\n\n for i in range(0,width,int(width/12)):\n d.line((i,0,i,height),fill=(0,255,0),width = 30)\n\n for i in range(0,height,int(height/8)):\n d.line((0,i,width,i),fill = (0,255,0),width = 30)\n\n name = 'grided' + photo\n print(name)\n im.save(photo)\n","sub_path":"MainBacteria-master/drawGrids.py","file_name":"drawGrids.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"183402558","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom scipy.linalg import expm\nimport function\nfrom utils import load_class\nimport random, pickle, json\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport datetime, os\nimport pandas as pd\nimport sys\nimport math\nimport copy\n\nclass RealSolution(object):\n # 実数個体クラス\n def __init__(self, **params):\n self.f = float('nan')\n self.x = np.zeros([params['dim'], 1])\n self.z = np.zeros([params['dim'], 1])\n self.epsilon = np.zeros([params['mu'], 1])\n\ndef log_generation(log, g, evals, fval, tau, s_mean, dim, cm):\n log['g'].append(g)\n log['evals'].append(evals)\n log['fval'].append(fval)\n\n X, Y, Z = np.linalg.svd(cm)\n Y = np.sqrt(Y)\n # print(\"Y:\", Y)\n for i in range(dim):\n log['s_mean%d' % i].append(s_mean[i, 0])\n log['eig%d' % i].append(Y[i])\n\n\n\ndef plot_fval(df, path, save=True):\n plt.figure()\n plt.title('%s/eval' % path)\n plt.plot(df['evals'], df['fval'])\n plt.xlim([0, params['graph_end']])\n\n # plt.ylim([1e-10, 1e+2])\n plt.ylim([1e-10, 1e+2])\n plt.yscale('log')\n plt.xlabel('# evaluations')\n plt.ylabel(r'$f(\\mathbf{x}_\\mathrm{best})$')\n plt.grid()\n plt.minorticks_on()\n if save:\n plt.savefig('%s/eval.pdf' % path)\n plt.close()\n else:\n plt.show()\n\n\ndef plot_mean(df, path, n, color=cm.hsv, save=True):\n plt.figure()\n plt.title('%s/meanvector' % path)\n test_arr = []\n for i in range(n):\n test, = plt.plot(df['evals'], df['s_mean%d' % i], color=color(float(i)/n), \\\n label='m%d' % i)\n test_arr.append(test)\n\n # plt.legend(handles=test_arr)\n plt.xlabel('# evaluations')\n plt.ylabel('position of mean vector')\n plt.xlim([0, params['graph_end']])\n\n plt.ylim(-2, 2)\n plt.grid()\n plt.minorticks_on()\n if save:\n plt.savefig('%s/mean.pdf' % path)\n plt.close()\n else:\n plt.show()\n\n\ndef plot_eig(df, path, n, color=cm.hsv, save=True):\n plt.figure()\n plt.title('%s/eigenvalues' % path)\n for i in range(n):\n plt.plot(df['evals'], df['eig%d' % i], color=color(float(i)/n), \\\n label='eig%d' % i)\n plt.xlabel('# evaluations')\n plt.ylabel('eigenvalues of covariance matrix')\n plt.xlim([0, params['graph_end']])\n\n plt.ylim([1e-8, 1e+1])\n plt.yscale('log')\n plt.grid()\n plt.minorticks_on()\n if save:\n plt.savefig('%s/eig.pdf' % path)\n plt.close()\n else:\n plt.show()\n\ndef calc_euclid_square(x, y):\n val = np.dot((x - y).T, (x - y))\n return val\n\ndef calc_mahalanobis_square(x, y, cm):\n val = 0.0\n inv_cm = np.linalg.inv(cm)\n val = (x - y).T.dot(inv_cm).dot((x - y))\n return val\n\ndef get_covariance(solutions, dim, npop):\n cm = np.zeros([dim, dim])\n mean = np.zeros([dim, 1])\n for s in solutions:\n mean += s.x\n mean /= npop\n for i in range(dim):\n for j in range(dim):\n tmp_sum = 0.0\n for k in range(npop):\n tmp_sum += (solutions[k].x[i][0] - mean[i][0]) * (solutions[k].x[j][0] - mean[j][0])\n cm[i][j] = tmp_sum / npop\n return cm\n\ndef swap(solutions, index1, index2):\n tmp = solutions[index1]\n solutions[index1] = solutions[index2]\n solutions[index2] = tmp\n return\n\n\ndef main(path, **params):\n dim = params['dim']\n npop = params['npop']\n mu = params['mu']\n lamb = params['lamb']\n np.random.seed(params['seed'])\n obj_func = params['obj_func']\n solutions = params['solutions']\n variance = params['variance']\n\n weight = []\n tmp_sum = 0.0\n for i in range(mu):\n tmp = float(2.0*(mu+1-(i+1)))/float(mu*(mu+1.0))\n weight.append(tmp)\n tmp_sum += tmp\n\n no_of_evals = 0\n # init\n solutions = [RealSolution(**params) for i in range(npop)]\n for i in range(npop):\n for j in range(dim):\n solutions[i].x[j][0] = (np.random.rand() * (params['init_range_max'] - params['init_range_min'])) + params['init_range_min']\n\n for s in solutions:\n s.f = obj_func.evaluate(s.x)\n no_of_evals += 1\n\n s_mean = np.zeros([dim, 1])\n for (i,s) in enumerate(solutions):\n s_mean += s.x\n s_mean /= npop\n\n log = {'g':[], 'evals':[], 'fval':[]}\n for i in range(dim):\n log['s_mean%d' % i] = []\n log['eig%d' % i] = []\n\n log_data = {'logfile':[], 'g':[]}\n\n g = 0\n tau = 1\n solutions.sort(key=lambda s: s.f)\n best = solutions[0].f\n cm = get_covariance(solutions, dim, npop)\n log_generation(log, g, no_of_evals, best, tau, s_mean, dim, cm)\n\n\n while no_of_evals < params['max_evals']:\n cm = get_covariance(solutions, dim, npop)\n\n g += 1\n\n parents = []\n for i in range(mu):\n # sampling without replacement from S\n rand = np.random.randint(npop - i) + i\n swap(solutions, i, rand)\n parents.append(solutions[i])\n\n s_mean = np.zeros([dim, 1])\n for i in range(npop):\n s_mean += solutions[i].x\n s_mean /= npop\n # print(\"s_mean:\", s_mean)\n\n parent_mean = np.zeros([dim, 1])\n for p in parents:\n parent_mean += p.x\n parent_mean /= mu\n\n children = [RealSolution(**params) for i in range(lamb)]\n\n for i in range(lamb):\n for j in range(mu):\n children[i].epsilon[j][0] = math.sqrt(variance) * np.random.randn()\n\n block_epsilon = np.zeros([dim, 1])\n for j in range(mu):\n block_epsilon += children[i].epsilon[j][0] * (parents[j].x - parent_mean)\n children[i].x = parent_mean + block_epsilon\n children[i].f = obj_func.evaluate(children[i].x)\n no_of_evals += 1\n\n children.sort(key=lambda c: c.f)\n\n fname = '%s/logData%s.obj' % (path, str(g))\n log_data['logfile'].append(fname)\n log_data['g'].append(g)\n f = open(fname, 'wb')\n pickle.dump({'solutions': solutions, 'children': children }, f)\n f.close()\n\n for i in range(mu):\n solutions[i] = copy.deepcopy(children[i])\n\n solutions.sort(key=lambda s: s.f)\n best = solutions[0].f\n log_generation(log, g, no_of_evals, best, tau, s_mean, dim, cm)\n\n if best < params['criterion']:\n # print(no_of_evals, solutions[0].f)\n break\n\n print(no_of_evals, solutions[0].f, params['seed'])\n df = pd.DataFrame(log)\n df.index.name = '#index'\n df.to_csv('%s/log.csv' % path, seq=',')\n plot_fval(df, path)\n plot_mean(df, path, dim)\n plot_eig(df, path, dim)\n\n df = pd.DataFrame(log_data)\n df.index.name = '#index'\n df.to_csv('%s/log_data.csv' % path, seq='')\n\nif __name__ == '__main__':\n params = {}\n params['seed'] = random.randint(0, 2**32 - 1)\n # params['seed'] = 3425007337\n params['dim'] = 20\n params['npop'] = params['dim'] * 7\n params['mu'] = params['dim'] + 1\n params['lamb'] = params['dim'] * 6\n\n # params['max_evals'] = int(params['dim'] * 5000)\n params['max_evals'] = 30000\n params['graph_end'] = params['max_evals']\n params['criterion'] = 1e-7\n params['init_range_max'] = -1.0\n params['init_range_min'] = 1.0\n params['variance'] = 1 / (params['mu'] - 1)\n \n params['obj_func_name'] = 'function.SphereFunction'\n # params['obj_func_name'] = 'function.KTabletFunction'\n # params['obj_func_name'] = 'function.RosenbrockChainFunction'\n\n func = load_class(params['obj_func_name'])\n obj_func = func(params['dim'])\n path = 'log/' + obj_func.name + '_' + datetime.datetime.now().strftime('%Y-%m-%d-%H-%M')\n if not os.path.isdir(path):\n os.makedirs(path)\n print('create directory which is ' + path)\n f = open('%s/params_setting.json' % path, 'w')\n json.dump(params, f)\n f.close()\n\n params['solutions'] = [RealSolution(**params) for i in range(params['npop'])]\n params['obj_func'] = obj_func\n\n main(path, **params)\n print('create directory which is ' + path)\n\n","sub_path":"rex_jgg.py","file_name":"rex_jgg.py","file_ext":"py","file_size_in_byte":8063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"52846417","text":"\"\"\"\nRex material support for the ogre exporter.\n\"\"\"\nimport bpy\nimport os\n\nlayerMappings = {'normalMap':'normal',\n 'heightMap':'displacement',\n 'reflectionMap':'reflect',\n 'opacityMap':'alpha',\n 'lightMap':'ambient',\n 'specularMap':'specular' }\ninvLayerMappings = {}\nfor key, val in layerMappings.items():\n invLayerMappings[val] = key\n\ndef PathName(filename):\n print(\"PathName\", filename)\n return filename\n\ndef indent(howmuch):\n return \" \"*howmuch\n\ndef clamp(value):\n return max(0.0, min(1.0, value))\n\nclass RexMaterialIO(object):\n \"\"\"\n Material exporter and parser to export for the rex cg supershader\n \"\"\"\n def __init__(self, manager, blenderMesh, blenderFace, blenderMaterial):\n self.manager = manager\n self.mesh = blenderMesh\n self.face = blenderFace\n self.colouredAmbient = False\n # check if a Blender material is assigned\n try:\n blenderMaterial = blenderMaterial\n except:\n blenderMaterial = None\n self.TEXFACE = blenderFace and blenderFace.use_twoside\n self.IMAGEUVCOL = blenderFace and blenderFace.use_image\n self.fp_parms = {}\n self.vp_parms = {}\n self.alpha = 1.0\n self.shadows = False # doesnt work with rex for now..\n self.material = blenderMaterial\n self._parseMaterial(blenderMaterial)\n return\n\n def getAutodetect(self):\n \"\"\"\n Get the autodetect property for the material.\n \"\"\"\n mat = self.material\n if not mat:\n return True\n return mat.opensim.autodetect\n\n def toggleAutodetect(self):\n \"\"\"\n Toggle the autodetect property.\n \"\"\"\n mat = self.material\n if mat:\n mat.opensim.autodetect = True\n self._parseShader(mat)\n\n def setShader(self, shader):\n \"\"\"\n Set the custom shader to use if autodetect is off\n \"\"\"\n mat = self.material\n if mat:\n mat.opensim.shader = shader\n def getShader(self):\n \"\"\"\n Get the custom shader to use if autodetect is off\n \"\"\"\n mat = self.material\n if not mat:\n return \"\"\n return mat.opensim.shader\n\n def _parseMaterial(self, mat):\n \"\"\"\n Parse the blender material and fill up internal structures.\n \"\"\"\n if mat:\n self.alpha = mat.alpha\n self.shadows = mat.use_cast_buffer_shadows\n self.colouredAmbient = False\n\n # mat.use_shadows - receive shadows\n # mat.use_shadeless - insensitive to light and shadow\n #print \"shadows\", self.shadows #, Blender.Material.Modes.keys()\n if self.mesh.uv_textures:\n self.TEXFACE = True\n self._parseShader(mat)\n\n def getFPShaderVariables(self):\n \"\"\"\n Unused for the moment\n \"\"\"\n shVars = {}\n if 'Spec' in self.shader:\n shVars['specularPower'] = 0.8\n return shVars\n\n def _parseShader(self, mat):\n \"\"\"\n Find out what shader and shader properties to use.\n \"\"\"\n fp_parms = {}\n vp_parms = {}\n textures = self.getTextureLayers(mat)\n spectex = textures['specular']\n nortex = textures['normal']\n reftex = textures['reflect']\n ambtex = textures['ambient']\n disptex = textures['displacement']\n\n specHardness = 0.8\n if mat:\n specHardness = mat.specular_hardness\n if disptex and spectex and nortex:\n shader = \"rex/DiffSpecmapNormalParallax\"\n fp_parms['specularPower'] = specHardness\n elif nortex and ambtex:\n shader = \"rex/DiffNormalLightmap\"\n elif nortex and nortex.texture and nortex.texture.image:\n if spectex:\n shader = \"rex/DiffSpecmapNormal\"\n fp_parms['specularPower'] = specHardness\n else:\n shader = \"rex/DiffNormal\"\n if self.shadows:\n shader += \"Shadow\"\n elif reftex and spectex:\n shader = \"rex/DiffSpecmapRefl\"\n fp_parms['specularPower'] = specHardness\n elif reftex:\n fp_parms['opacity'] = alpha\n shader = \"rex/DiffReflAlpha\"\n else:\n shader = \"rex/Diff\"\n if self.shadows:\n shader += \"Shadow\"\n\n if mat and mat.opensim.shader and not mat.opensim.autodetect:\n shader = mat.opensim.shader\n\n self.shader = shader\n self.fp_parms = fp_parms\n\n def _writeShaderPrograms(self, f):\n \"\"\"\n Write the rex specific shader references into the material.\n \"\"\"\n shader = self.shader\n fp_parms = self.fp_parms\n vp_parms = self.vp_parms\n f.write(indent(3)+\"vertex_program_ref \" + shader + \"VP\\n\")\n f.write(indent(3)+\"{\\n\")\n for par, value in vp_parms.items():\n par_type = \"float\"\n f.write(indent(4)+\"param_named %s %s %s\\n\"%(par, par_type, value))\n f.write(indent(3)+\"}\\n\")\n f.write(indent(3)+\"fragment_program_ref \" + shader + \"FP\\n\")\n f.write(indent(3)+\"{\\n\")\n for par, value in fp_parms.items():\n par_type = \"float\"\n f.write(indent(4)+\"param_named %s %s %s\\n\"%(par, par_type, value))\n f.write(indent(3)+\"}\\n\")\n\n def writeTechniques(self, f):\n \"\"\"\n Write the techniques for the material.\n \"\"\"\n mat = self.material\n if (not(mat)\n and not len(self.mesh.vertex_colors)\n and not len(self.mesh.uv_textures)):\n # default material\n self.writeDefaultTechniques(self, f)\n else:\n self.writeRexTechniques(f, mat)\n\n def _writePassContents(self, f, mat):\n \"\"\"\n Write a full pass information.\n \"\"\"\n f.write(indent(3)+\"iteration once\\n\")\n\n # shader programs\n self._writeShaderPrograms(f)\n\n # material colors\n self._writeMaterialParameters(f, mat)\n\n # texture units\n self._writeTextureUnits(f, mat)\n\n def _writeMaterialParameters(self, f, mat):\n \"\"\"\n Write the material parameters.\n \"\"\"\n # alpha\n if self.alpha < 1.0:\n f.write(indent(3)+\"scene_blend alpha_blend\\n\")\n f.write(indent(3)+\"depth_write off\\n\")\n\n # ambient\n # (not used in Blender's game engine)\n if mat:\n if (not(mat.use_face_texture)\n and not(mat.use_vertex_color_paint)\n and (mat.ambient)):\n #ambientRGBList = mat.rgbCol\n ambientRGBList = [1.0, 1.0, 1.0]\n else:\n ambientRGBList = [1.0, 1.0, 1.0]\n # ambient <- amb * ambient RGB\n ambR = clamp(mat.ambient * ambientRGBList[0])\n ambG = clamp(mat.ambient * ambientRGBList[1])\n ambB = clamp(mat.ambient * ambientRGBList[2])\n f.write(indent(3)+\"ambient %f %f %f\\n\" % (ambR, ambG, ambB))\n # diffuse\n # (Blender's game engine uses vertex colours\n # instead of diffuse colour.\n #\n # diffuse is defined as\n # (mat->r, mat->g, mat->b)*(mat->emit + mat->ref)\n # but it's not used.)\n if self.mesh.vertex_colors and False:\n # we ignore this possibility for now...\n # Blender does not handle \"texface\" mesh with vertex colours\n f.write(indent(3)+\"diffuse vertexcolour\\n\")\n elif mat:\n if (not(mat.use_face_texture)\n and not(mat.use_vertex_color_paint) and not len(mat.texture_slots)):\n # diffuse <- rgbCol\n diffR = clamp(mat.diffuse_color[0])\n diffG = clamp(mat.diffuse_color[1])\n diffB = clamp(mat.diffuse_color[2])\n f.write(indent(3)+\"diffuse %f %f %f\\n\" % (diffR, diffG, diffB))\n elif (mat.use_vertex_color_paint):\n f.write(indent(3)+\"diffuse vertexcolour\\n\")\n\n # specular <- spec * specCol, hard/4.0\n specR = clamp(mat.specular_intensity * mat.specular_color[0])\n specG = clamp(mat.specular_intensity * mat.specular_color[1])\n specB = clamp(mat.specular_intensity * mat.specular_color[2])\n specShine = mat.specular_hardness/4.0\n f.write(indent(3)+\"specular %f %f %f %f\\n\" % (specR, specG, specB, specShine))\n # emissive\n # (not used in Blender's game engine)\n if(not(mat.use_face_texture)\n and not(mat.use_vertex_color_paint) and not len(mat.texture_slots)):\n # emissive <-emit * rgbCol\n emR = clamp(mat.emit * mat.rgbCol[0])\n emG = clamp(mat.emit * mat.rgbCol[1])\n emB = clamp(mat.emit * mat.rgbCol[2])\n ##f.write(indent(3)+\"emissive %f %f %f\\n\" % (emR, emG, emB))\n\n def _writeTextureUnits(self, f, mat):\n \"\"\"\n Write the texture units for the material.\n \"\"\"\n textures = self.getTextureLayers(mat)\n spectex = textures['specular']\n nortex = textures['normal']\n reftex = textures['reflect']\n ambtex = textures['ambient']\n disptex = textures['displacement']\n shader = self.shader\n # texture units\n if self.mesh.uv_textures:\n # mesh has texture values, resp. tface data\n # scene_blend <- transp\n if (self.face.blend_type == \"ALPHA\"):\n f.write(indent(3)+\"scene_blend alpha_blend \\n\")\n elif (self.face.blend_type == \"ADD\"):\n f.write(indent(3)+\"scene_blend add\\n\")\n # cull_hardware/cull_software\n # XXX twoside?\n if (self.face.use_twoside):\n f.write(indent(3) + \"cull_hardware none\\n\")\n f.write(indent(3) + \"cull_software none\\n\")\n # shading\n # (Blender's game engine is initialized with glShadeModel(GL_FLAT))\n ##f.write(indent(3) + \"shading flat\\n\")\n # texture\n if (self.face.use_image) and (self.face.image):\n # 0.0-heightMap\n if disptex:\n self._exportTextureUnit(f, \"heightMap\", disptex)\n\n # 0-diffuse\n f.write(indent(3)+\"texture_unit baseMap\\n\")\n f.write(indent(3)+\"{\\n\")\n f.write(indent(4)+\"texture %s\\n\" % self.manager.registerTextureImage(self.face.image))\n f.write(indent(3)+\"}\\n\") # texture_unit\n # 1-specular\n if spectex:\n self._exportTextureUnit(f, \"specularMap\", spectex)\n # 2-normal\n if len(self.mesh.materials):\n tex = self.findMapToTexture(mat, 'normal')\n if tex and tex.texture and tex.texture.type == 'IMAGE' and tex.texture.image:\n self._exportTextureUnit(f, \"normalMap\", tex)\n # 3-lightMap\n if ambtex:\n self._exportTextureUnit(f, \"lightMap\", ambtex)\n\n # 4-shadow\n if self.shadows and \"Shadow\" in self.shader:\n f.write(indent(3)+\"texture_unit shadowMap0\\n\")\n f.write(indent(3)+\"{\\n\")\n f.write(indent(4)+\"content_type shadow\\n\")\n f.write(indent(4)+\"tex_address_mode clamp\\n\")\n f.write(indent(3)+\"}\\n\") # texture_unit\n f.write(indent(3)+\"texture_unit shadowMap1\\n\")\n f.write(indent(3)+\"{\\n\")\n f.write(indent(4)+\"content_type shadow\\n\")\n f.write(indent(4)+\"tex_address_mode clamp\\n\")\n f.write(indent(3)+\"}\\n\") # texture_unit\n f.write(indent(3)+\"texture_unit shadowMap2\\n\")\n f.write(indent(3)+\"{\\n\")\n f.write(indent(4)+\"content_type shadow\\n\")\n f.write(indent(4)+\"tex_address_mode clamp\\n\")\n f.write(indent(3)+\"}\\n\") # texture_unit\n\n # 5-luminanceMap\n # 6-opacityMap\n if textures['alpha']:\n self._exportTextureUnit(f, \"opacityMap\", textures['alpha'])\n # 7-reflectionMap\n if reftex:\n self._exportTextureUnit(f, \"reflectionMap\", reftex)\n\n\n\n def writeRexTechniques(self, f, mat):\n \"\"\"\n Write a rex material technique.\n \"\"\"\n # default material\n # SOLID, white, no specular\n f.write(indent(1)+\"technique\\n\")\n f.write(indent(1)+\"{\\n\")\n f.write(indent(2)+\"pass\\n\")\n f.write(indent(2)+\"{\\n\")\n self._writePassContents(f, mat)\n f.write(indent(2)+\"}\\n\") # pass\n f.write(indent(1)+\"}\\n\") # technique\n return\n\n def getTextureLayers(self, mat):\n \"\"\"\n Get an array with the texture layers.\n \"\"\"\n textures = {}\n if mat:\n for tex in invLayerMappings:\n textures[tex.lower()] = self.findMapToTexture(mat, tex)\n else:\n for tex in invLayerMappings:\n textures[tex.lower()] = None\n return textures\n\n def _exportTextureUnit(self, f, name, btex):\n \"\"\"\n Export a single texture unit based on a blender mapto texture.\n \"\"\"\n f.write(indent(3)+\"texture_unit \" + name + \"\\n\")\n f.write(indent(3)+\"{\\n\")\n if btex.texture and btex.texture.type == 'IMAGE' and btex.texture.image:\n f.write(indent(4)+\"texture %s\\n\" % self.manager.registerTextureImage(btex.texture.image))\n f.write(indent(3)+\"}\\n\") # texture_unit\n\n def findMapToTexture(self, meshmat, mapto):\n \"\"\"\n Find a mapto texture to apply for a specific mapto.\n \"\"\"\n bmapto = \"use_map_\"+mapto\n if not meshmat and len(self.mesh.materials):\n meshmat = self.mesh.materials[0]\n if meshmat:\n image = None\n for tex in meshmat.texture_slots:\n if tex and getattr(tex, bmapto):\n return tex\n\n # private, might need to override later..\n def _createName(self):\n \"\"\"Create unique material name.\n \n The name consists of several parts:\n <OL>\n <LI>rendering material name/</LI>\n <LI>blend mode (ALPHA, ADD, SOLID)</LI>\n <LI>/TEX</LI>\n <LI>/texture file name</LI>\n <LI>/VertCol</LI>\n <LI>/TWOSIDE></LI>\n </OL>\n \"\"\"\n return self.material.name # for now we need to trick the ogre exporter\n # must be called after _generateKey()\n materialName = self.material.name\n # two sided?\n if self.mesh.uv_textures and (self.face.use_twoside):\n materialName += '/TWOSIDE'\n # use UV/Image Editor texture?\n if self.TEXFACE:\n materialName += '/TEXFACE'\n if self.mesh.uv_textures and self.face.image:\n materialName += '/' + PathName(self.face.image.filepath)\n return materialName\n\n def getName(self):\n return self._createName()\n\n def write(self, f):\n f.write(\"material %s\\n\" % self.getName())\n f.write(\"{\\n\")\n self.writeTechniques(f)\n f.write(\"}\\n\")\n return\n \n","sub_path":"All_In_One/addons/b2rexpkg/b25/material.py","file_name":"material.py","file_ext":"py","file_size_in_byte":15428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"524383399","text":"#!/usr/bin/env python3\n\nfrom typing import Dict, Any\nimport logging\n\nfrom keras.layers import LSTM, Bidirectional, Dense, Embedding, Input,\\\n Masking, GRU, SimpleRNN\nfrom keras.layers import Dropout\nfrom keras.models import Model\nfrom keras import optimizers\nfrom keras.regularizers import l1_l2\nfrom tensorflow import Tensor\nfrom rasa_nlu.classifiers.keras_model.keras_base_model import KerasBaseModel\nfrom numpy import ndarray\n\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass Word2vecIntentClassifier(KerasBaseModel):\n\n def __init__(self, clf_config: Dict[str, Any], lookup_table: ndarray,\n nlabels: int) -> None:\n super(Word2vecIntentClassifier, self).__init__(clf_config, None)\n LOGGER.info(f'KERAS CONFIG: {clf_config}')\n input_dim: int\n output_dim: int\n input_dim, output_dim = lookup_table.shape\n self.embedding_layer: Embedding = Embedding(input_dim, output_dim,\n name='word_emb',\n weights=[lookup_table],\n mask_zero=True)\n self.embedding_dropout = Dropout(self.clf_config['input_dropout'])\n rnn_regularizer = l1_l2(clf_config['rnn_regularizer'])\n if clf_config['rnn_type'].lower() == 'lstm':\n rnn_layer = LSTM(clf_config['hidden_size'], name='rnn',\n kernel_regularizer=rnn_regularizer,\n bias_regularizer=rnn_regularizer)\n elif clf_config['rnn_type'].lower() == 'gru':\n rnn_layer = GRU(clf_config['hidden_size'], name='rnn',\n kernel_regularizer=rnn_regularizer,\n bias_regularizer=rnn_regularizer)\n else:\n rnn_layer = SimpleRNN(clf_config['hidden_size'], name='rnn')\n self.bi_rnn = Bidirectional(rnn_layer, merge_mode='concat',\n name='bilstm')\n self.lstm_dropout: Dropout = Dropout(clf_config['output_dropout'])\n fc_regularizer = l1_l2(clf_config['fc_regularizer'])\n self.fc: Dense = Dense(nlabels, activation='softmax', name='fc',\n bias_regularizer=fc_regularizer,\n kernel_regularizer=fc_regularizer)\n\n def compile(self):\n if self.model is None:\n token_input: Input = Input(shape=(None, ), dtype='int32')\n emb_out: Tensor = self.embedding_layer(token_input)\n emb_out: Tensor = self.embedding_dropout(emb_out)\n mask_out: Tensor = Masking()(emb_out)\n bi_lstm_out: Tensor = self.bi_rnn(mask_out)\n dropout_out: Tensor = self.lstm_dropout(bi_lstm_out)\n fc_out: Tensor = self.fc(dropout_out)\n model = Model(token_input, fc_out)\n metrics = ['sparse_categorical_accuracy']\n optimizer_config = {'class_name': self.clf_config['optimizer'],\n 'config': {'lr': self.clf_config['lr']}}\n optimizer = optimizers.get(optimizer_config)\n model.compile(optimizer=optimizer, loss=self.clf_config['loss'],\n metrics=metrics)\n self.model = model\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"rasa_nlu/classifiers/keras_model/word2vec_bi_rnn.py","file_name":"word2vec_bi_rnn.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"159209112","text":"\n\ndef pair_sum(arr, target):\n\n seen = set()\n for i in arr:\n if i in seen:\n return True\n else:\n seen.add(target-i)\n return False\n\npair_sum([1,2,3,-1,5,-11,7], 11)\n\n\n ","sub_path":"Interview_Portilla/Interview Mocks/09_pair_sum_to_k.py","file_name":"09_pair_sum_to_k.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"254413786","text":"import pygame\nfrom algorithm import Rose\n\nWIDTH, HEIGHT = 500, 500\nSCREEN = (WIDTH, HEIGHT)\n\npygame.display.set_caption(\"Maurer Rose Curve\")\nwin = pygame.display.set_mode(SCREEN)\n\n#Colors\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\n\n#set background\nwin.fill(WHITE)\n\ndef Draw(d, num, size):\n\n\tcurve = Rose(d, num, size, WIDTH, HEIGHT, BLACK, win)\n\tcurve.Maurer()\n\tcurve.Rhodonea()\nDraw(71, 6, 200)\n\n\npygame.display.flip()\n\nrun = True\n\nwhile run:\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT:\n\t\t\tpygame.quit()\t\n\t\t\trun = False\n\n\t\tpygame.display.update()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"46463079","text":"from PyQt5 import QtCore, QtGui, QtWidgets\r\nfrom datetime import datetime\r\nfrom PyQt5.QtWidgets import * \r\nimport sys\r\nimport re\r\nimport os\r\nfrom previousPatientData import *\r\nfrom mainWindows import *\r\nfrom dialogs import *\r\n\r\nLOAD_PREVIOUS = 1\r\nNEW_PATIENT = 0\r\nYES = 1\r\n\r\n\r\n\r\n########################################################################################################################################\r\n # CLASSES #\r\n########################################################################################################################################\r\n\r\nclass previousPatientData:\r\n wristMVC = None;\r\n shoulderMVC = None;\r\n fingerMVC = None;\r\n previousSessionNum = None\r\n setupMeas = None;\r\n\r\n\r\nclass patientDetails:\r\n clinicanName = None\r\n date = None\r\n patientID = None\r\n patientName = None\r\n ur = None\r\n sessionNum = 0\r\n setupMeas = None\r\n setupMeasWrist = None\r\n setupMeasFinger = None\r\n setupMeasShoulder = None\r\n wristMVC = None\r\n fingerMVC = None\r\n shoulderMVC = None\r\n beenExported = None\r\n\r\n########################################################################################################################################\r\n # SCROLL #\r\n########################################################################################################################################\r\n\r\n\r\nclass ScrollLabel(QScrollArea):\r\n \r\n # contructor\r\n def __init__(self, parent=None):\r\n super(ScrollLabel,self).__init__(parent)\r\n \r\n # making widget resizable\r\n self.setWidgetResizable(True)\r\n # making qwidget object\r\n content = QWidget(self)\r\n self.setWidget(content)\r\n # vertical box layout\r\n lay = QVBoxLayout(content)\r\n # creating label\r\n self.label = QLabel(content)\r\n # setting alignment to the text\r\n self.label.setAlignment(Qt.AlignLeft | Qt.AlignTop)\r\n # making label multi-line\r\n self.label.setWordWrap(True)\r\n # adding label to the layout\r\n lay.addWidget(self.label) \r\n\r\n def UiComponents(self,text):\r\n # creating scroll label\r\n label = ScrollLabel(self)\r\n \r\n tableFrame = Q\r\n tableFrame = QtWidgets.QFrame(self.centralwidget)\r\n tableFrame.setGeometry(QtCore.QRect(300,200,300,200))\r\n tableFrame.setStyleSheet(\"background-color: rgb(255, 255, 255);\")\r\n tableFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)\r\n tableFrame.setFrameShadow(QtWidgets.QFrame.Raised)\r\n tableFrame.setObjectName(\"WelcomeFrame\")\r\n\r\n\r\n table = QTableWidget(self)\r\n table.setGeometry(300,200,300,200)\r\n table.raise_()\r\n table.setStyleSheet(\"background-color: rgb(255, 255, 255);\")\r\n table.setRowCount(1)\r\n table.setColumnCount(1)\r\n table.adjustSize()\r\n\r\n # setting text to the label\r\n # label.setText(text)\r\n label.label.setText(\"\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r\\n\\r-----------------------------------------------------------------------------------------\\n\\r{}\".format(text))\r\n label.label.setStyleSheet(\"font: 13pt \\\".AppleSystemUIFont\\\"; \\n\"\r\n \"background-color: rgb(255, 255, 255);\\n\"\r\n \"color: #000000\") \r\n # setting geometry\r\n label.setGeometry(QtCore.QRect(450, 150, 621, 581))\r\n\r\n\r\n########################################################################################################################################\r\n # Table #\r\n########################################################################################################################################\r\n \r\nclass dataTable(QTableWidget):\r\n # contructor\r\n def __init__(self, parent=None):\r\n super(dataTable,self).__init__(parent)\r\n\r\n # self.table = QTableWidget(parent=self)\r\n # self.table.setColumnCount(2)\r\n # self.table.setRowCount(2)\r\n # self.table.setHorizontalHeaderLabels(['col1','col2'])\r\n # self.table.setVerticalHeaderLabels(['row1','row2'])\r\n # self.table.setItem(0,0,QTableWidgetItem('foo'))\r\n # self.table.setItem(0,1,QTableWidgetItem('bar'))\r\n # self.table.setItem(1,0,QTableWidgetItem('baz'))\r\n # self.table.setItem(1,1,QTableWidgetItem('qux'))\r\n # self.table.setGeometry(QtCore.QRect(0, 10, 20, 101))\r\n # layout = QGridLayout()\r\n # layout.addWidget(self.table, 1, 0)\r\n # self.setLayout(layout)\r\n # self.table.raise_()\r\n\r\n # self.clip = QApplication.clipboard()\r\n\r\n########################################################################################################################################\r\n # Generic Functions #\r\n########################################################################################################################################\r\n\r\ndef close_all():\r\n sys.exit(0)\r\n\r\ndef loadClinicianName():\r\n # dir_path = os.path.dirname(os.path.realpath(__file__))\r\n text_file = open('ClinicianName.txt' , \"r+\")\r\n data = text_file.read()\r\n text_file.close()\r\n return data\r\n\r\ndef get_meas_txt():\r\n text_file = open(\"meas.txt\", \"r+\")\r\n data = text_file.read()\r\n text_file.truncate(0)\r\n text_file.close()\r\n return data\r\n \r\n########################################################################################################################################\r\n # MAIN SECTION #\r\n########################################################################################################################################\r\n\r\n\r\nclass MainWindow(QMainWindow):\r\n\r\n def __init__(self, parent=None):\r\n super(MainWindow, self).__init__(parent)\r\n self.setGeometry(50, 50, 400, 450)\r\n self.setFixedSize(1280, 800)\r\n self.setStyleSheet(\"background-color: rgb(255,252,241);\");\r\n loadClinicianName()\r\n self.currentDetails = patientDetails()\r\n self.startUIToolTab()\r\n self.current_delsys_MVC = None\r\n self.EXERCISE_SET = None\r\n self.patientDetail = patientDetails() #start instance of patient details\r\n\r\n def startUIToolTab(self):\r\n \r\n self.ToolTab = UIToolTab(self)\r\n self.setCentralWidget(self.ToolTab)\r\n self.ToolTab.lineEdit.returnPressed.connect(self.patientRegister)\r\n self.ToolTab.startButton.clicked.connect(self.patientRegister)\r\n self.show()\r\n\r\n def startUIWindow(self):\r\n self.Window = UIWindow(self)\r\n self.setCentralWidget(self.Window)\r\n\r\n self.Window.Logout.clicked.connect(self.logout) \r\n\r\n #set up patient details run next class\r\n if (self.currentDetails.sessionNum!=0):\r\n self.Window.label_5.setText(self.Window._translate(\"OverViewWindow\", \"Session no.{} \".format(self.currentDetails.sessionNum))) \r\n\r\n #Checks the name once patient set up is done\r\n if (self.patientDetail.patientName == None):\r\n self.Window.label_10.setText(self.Window._translate(\"OverViewWindow\", \"Patient: - \"))\r\n else:\r\n self.Window.label_10.setText(self.Window.\r\n _translate(\"OverViewWindow\", \"Patient: {}\".format(self.patientDetail.patientName) ))\r\n\r\n #change the exercise\r\n self.Window.changeExerciseButton.clicked.connect(self.changeExercisePopUp)\r\n #export data button\r\n self.Window.ExportDataButton.clicked.connect(self.exportData)\r\n #view all past patient history\r\n self.Window.changePatient.clicked.connect(self.patientChangeCheckPopUp)\r\n\r\n # this is for the start and stop functionality \r\n self.Window.startButton.clicked.connect(self.startButtonFun)\r\n self.Window.stopButton.clicked.connect(lambda: self.stopButtonCheck(self.EXERCISE_SET))\r\n\r\n self.Window.historySide.clicked.connect(self.startUIpatietnHistory)\r\n \r\n if (self.EXERCISE_SET == None):\r\n #We must select an exercise to know imgs to display\r\n\r\n self.Window.patientSetup.clicked.connect(self.patientCheckExercisePopUp) \r\n else:\r\n # This will check if a name is in the database and then re check if they want to overwrite this\r\n self.Window.patientSetup.clicked.connect(self.startSetUpPopup)\r\n self.show() \r\n\r\n # performs all clearing of data for logout\r\n def logout(self):\r\n self.currentDetails.clinicanName = None\r\n self.currentDetails.date = None\r\n self.currentDetails.patientID = None\r\n self.currentDetails.patientName = None\r\n self.currentDetails.sessionNum = 0\r\n self.currentDetails.setupMeas = None\r\n self.currentDetails.setupMeasWrist = None\r\n self.currentDetails.setupMeasFinger = None\r\n self.currentDetails.setupMeasShoulder = None\r\n self.currentDetails.wristMVC = None\r\n self.currentDetails.fingerMVC = None\r\n self.currentDetails.shoulderMVC = None\r\n self.currentDetails.beenExported = None \r\n self.currentDetails.ur = None\r\n\r\n self.patientDetail.patientName = None\r\n self.patientDetail.patientID = None\r\n self.patientDetail.date = None\r\n self.patientDetail.sessionNum = 0\r\n self.patientDetail.setupMeas = None\r\n self.patientDetail.setupMeasWrist = None\r\n self.patientDetail.setupMeasFinger = None\r\n self.patientDetail.setupMeasShoulder = None\r\n self.patientDetail.wristMVC = None\r\n self.patientDetail.fingerMVC = None\r\n self.patientDetail.shoulderMVC = None\r\n self.patientDetail.beenExported = None \r\n \r\n self.startUIToolTab()\r\n\r\n def patientRegister(self):\r\n self.startUIWindow()\r\n ui_patientReg = Ui_Register(self)\r\n popup = QMessageBox(ui_patientReg)\r\n ui_patientReg.OK.clicked.connect(self.startUIWindow)\r\n ui_patientReg.OK.clicked.connect(lambda: self.checkDetail(ui_patientReg))\r\n ui_patientReg.URnumLine.returnPressed.connect(lambda: self.checkDetail(ui_patientReg))\r\n ui_patientReg.URnumLine.returnPressed.connect(self.startUIWindow)\r\n ui_patientReg.show()\r\n\r\n def startUIpatietnHistory(self):\r\n self.historyWindow = Ui_PatientHistoryWindow(self)\r\n self.setCentralWidget(self.historyWindow)\r\n\r\n self.historyWindow.Logout.clicked.connect(self.logout) \r\n self.historyWindow.changePatient.clicked.connect(self.patientChangeCheckPopUp)\r\n self.historyWindow.patientSetup.clicked.connect(self.changetoHome)\r\n\r\n ######################## TABLE ########################\r\n # table = QTableWidget(self.historyWindow)\r\n # table.setGeometry(300,200,300,200)\r\n # table.raise_()\r\n # table.setStyleSheet(\"background-color: rgb(255, 255, 255);\")\r\n # table.setRowCount(1)\r\n # table.setColumnCount(1)\r\n # table.adjustSize()\r\n #######################################################\r\n\r\n self.scroll = QtWidgets.QScrollBar(self.historyWindow.PastSessions)\r\n\r\n historyList = displayPatientHistory(self.currentDetails.patientID,self.currentDetails.ur,self.currentDetails.sessionNum, self.currentDetails.beenExported)\r\n if (historyList == 0):\r\n ScrollLabel.UiComponents(self.historyWindow,\"no previous sessions\")\r\n else:\r\n ScrollLabel.UiComponents(self.historyWindow,historyList)\r\n\r\n #Checks the name once patient set up is done\r\n if (self.patientDetail.patientName == None):\r\n self.historyWindow.label_10.setText(self.historyWindow._translate(\"OverViewWindow\", \"Patient: - \"))\r\n else:\r\n self.historyWindow.label_10.setText(self.historyWindow._translate(\"OverViewWindow\", \"Patient: {}\".format(self.patientDetail.patientName) ))\r\n \r\n self.historyWindow.overviewSide.clicked.connect(self.startUIWindow)\r\n\r\n self.show()\r\n\r\n \r\n\r\n def startSetUpPopup(self):\r\n #init the patient setup\r\n listInfo = self.EXERCISE_SET\r\n setUpPatient = UIinitPatientSetUp(parent=self, listInfo=listInfo)\r\n setUpPatient.setStyleSheet(\"background-color: rgb(255,252,241);\");\r\n popup = QMessageBox(setUpPatient)\r\n\r\n setUpPatient.nextButton.clicked.connect(self.startEnterMeasurementsPopup)\r\n\r\n setUpPatient.show()\r\n \r\n def startEnterMeasurementsPopup(self):\r\n \r\n listInfo = self.EXERCISE_SET\r\n self.startEnterMeasurementsPopup = UIinitMeasurePatientSetUp(parent=self,listInfo=listInfo)\r\n\r\n if ((self.currentDetails.setupMeasWrist != None) and (self.EXERCISE_SET ==1)):\r\n self.startEnterMeasurementsPopup.PatientsNameEnter.setText(self.currentDetails.setupMeasWrist)\r\n elif((self.currentDetails.setupMeasFinger != None) and (self.EXERCISE_SET ==2)):\r\n self.startEnterMeasurementsPopup.PatientsNameEnter.setText(self.currentDetails.setupMeasFinger)\r\n elif((self.currentDetails.setupMeasShoulder != None) and (self.EXERCISE_SET ==3)):\r\n self.startEnterMeasurementsPopup.PatientsNameEnter.setText(self.currentDetails.setupMeasShoulder)\r\n\r\n # print(self.startEnterMeasurementsPopup.PatientsNameEnter.text())\r\n\r\n self.startEnterMeasurementsPopup.backButton.clicked.connect(self.startSetUpPopup)\r\n self.startEnterMeasurementsPopup.doneButton.clicked.connect(self.sampleEMGPopup)\r\n self.startEnterMeasurementsPopup.show()\r\n \r\n\r\n\r\n def sampleEMGPopup(self):\r\n popup = Ui_SampleEMG(self)\r\n if ((self.currentDetails.setupMeasWrist == None) and (self.EXERCISE_SET ==1)):\r\n self.currentDetails.setupMeasWrist = get_meas_txt()\r\n elif((self.currentDetails.setupMeasFinger == None) and (self.EXERCISE_SET ==2)):\r\n self.currentDetails.setupMeasFinger = get_meas_txt()\r\n elif((self.currentDetails.setupMeasShoulder == None) and (self.EXERCISE_SET ==3)):\r\n self.currentDetails.setupMeasShoulder = get_meas_txt() \r\n\r\n \r\n popup.nextButton.clicked.connect(self.startUIWindow)\r\n popup.backBB.clicked.connect(self.startEnterMeasurementsPopup)\r\n popup.show() \r\n\r\n def changeExercisePopUp(self):\r\n changeExercisePopUp = UIchangeExercisePopUp(self)\r\n self.EXERCISE_SET = 1\r\n\r\n popup = QMessageBox(changeExercisePopUp)\r\n changeExercisePopUp.WristExtension.clicked.connect(lambda: self.passCurrentExercise(1))\r\n changeExercisePopUp.FingerFlexion.clicked.connect(lambda: self.passCurrentExercise(2))\r\n changeExercisePopUp.Deltoid.clicked.connect(lambda: self.passCurrentExercise(3))\r\n\r\n # changeExercisePopUp.WristExtension.clicked.connect(self.startUIWindow)\r\n\r\n changeExercisePopUp.show() \r\n\r\n#################################################################\r\n # Small checking dialog popup classes #\r\n#################################################################\r\n def changetoHome(self):\r\n popHome = changetohomeUI(self)\r\n popHome.DONE.clicked.connect(self.startUIWindow)\r\n popHome.show() \r\n\r\n def patientCheckPopUp(self):\r\n ui_patientCheckPopUp = Ui_patientPopUp(self)\r\n popup = QMessageBox(ui_patientCheckPopUp)\r\n ui_patientCheckPopUp.DONE.clicked.connect(self.startSetUpPopup)\r\n ui_patientCheckPopUp.BACK.clicked.connect(self.startUIWindow)\r\n ui_patientCheckPopUp.show()\r\n\r\n def patientChangeCheckPopUp(self):\r\n ui_patientChangeCheckPopUp = Ui_changePatientPopUp(self)\r\n popup = QMessageBox(ui_patientChangeCheckPopUp)\r\n ui_patientChangeCheckPopUp.DONE.clicked.connect(self.changePatientButton)\r\n ui_patientChangeCheckPopUp.BACK.clicked.connect(self.startUIWindow)\r\n ui_patientChangeCheckPopUp.show() \r\n\r\n def checkPatientSetup(self):\r\n dialogPatientSetup = Ui_needPatientSetup(self)\r\n popup = QMessageBox(dialogPatientSetup)\r\n dialogPatientSetup.show()\r\n\r\n def patientCheckExercisePopUp(self):\r\n ui_patientCheckPopUp = Ui_checkExercise(self)\r\n popup = QMessageBox(ui_patientCheckPopUp)\r\n ui_patientCheckPopUp.BACK.clicked.connect(self.startUIWindow)\r\n ui_patientCheckPopUp.show()\r\n\r\n\r\n\r\n\r\n########################################################################################################################################\r\n # Class functions #\r\n########################################################################################################################################\r\n\r\n\r\n#################################################################\r\n # HERE WILL BE USED TO DISP READING VALUE #\r\n#################################################################\r\n def get_reading(self):\r\n return self.current_delsys_MVC \r\n \r\n def startButtonFun(self):\r\n value = self.get_reading()\r\n \r\n self.Window.label_7.setText(self.Window._translate(\"OverViewWindow\", \"{}\".format(value)))\r\n self.Window.label_7.adjustSize()\r\n\r\n\r\n\r\n#################################################################\r\n # Stop Button #\r\n#################################################################\r\n def stopButtonCheck(self,exercise):\r\n stopCheck = Ui_finishEMGReading(self)\r\n popup = QMessageBox(stopCheck)\r\n\r\n #functionality of the buttons\r\n\r\n stopCheck.nextExB.clicked.connect(self.storeReading) \r\n\r\n if (exercise == 1):\r\n #wrist\r\n stopCheck.redoB.clicked.connect(lambda: self.clearVal(exercise))\r\n stopCheck.middleB.clicked.connect(self.checkFinished)\r\n elif (exercise == 2):\r\n #finger\r\n stopCheck.redoB.clicked.connect(lambda: self.clearVal(exercise))\r\n stopCheck.middleB.clicked.connect(self.checkFinished)\r\n else:\r\n #shoulder\r\n stopCheck.redoB.clicked.connect(lambda: self.clearVal(exercise))\r\n stopCheck.middleB.clicked.connect(self.checkFinished)\r\n stopCheck.show()\r\n\r\n def checkFinished(self):\r\n finished = checkFinishedUI(self)\r\n finished.BACK.clicked.connect(self.stopButtonCheck)\r\n finished.DONE.clicked.connect(self.exportData)\r\n finished.show()\r\n\r\n # stores reading after pressed the NEXT button\r\n def storeReading(self,n):\r\n if (n == 1):\r\n #wrist\r\n self.currentDetails.wristMVC = self.get_reading()\r\n elif (n == 2):\r\n #finger\r\n self.currentDetails.fingerMVC = self.get_reading()\r\n else:\r\n #shoulder\r\n self.currentDetails.shoulderMVC = self.get_reading()\r\n\r\n self.changeExercisePopUp()\r\n\r\n\r\n def clearVal(self,exercise):\r\n print(exercise)\r\n self.current_delsys_MVC = None\r\n if (exercise == 1):\r\n self.currentDetails.wristMVC = None\r\n elif (exercise == 2):\r\n self.currentDetails.fingerMVC = None\r\n else:\r\n self.currentDetails.shoulderMVC = None\r\n self.passCurrentExercise(exercise)\r\n self.startUIWindow()\r\n \r\n \r\n\r\n def changePatientButton(self): \r\n self.currentDetails.clinicanName = None\r\n self.currentDetails.date = None\r\n self.currentDetails.patientID = None\r\n self.currentDetails.patientName = None\r\n self.currentDetails.sessionNum = 0\r\n self.currentDetails.setupMeas = None\r\n self.currentDetails.setupMeasWrist = None\r\n self.currentDetails.setupMeasFinger = None\r\n self.currentDetails.setupMeasShoulder = None\r\n self.currentDetails.wristMVC = None\r\n self.currentDetails.fingerMVC = None\r\n self.currentDetails.shoulderMVC = None\r\n self.currentDetails.beenExported = None \r\n self.currentDetails.ur = None\r\n\r\n self.patientDetail.patientName = None\r\n self.patientDetail.patientID = None\r\n self.patientDetail.date = None\r\n self.patientDetail.sessionNum = 0\r\n self.patientDetail.setupMeas = None\r\n self.patientDetail.setupMeasWrist = None\r\n self.patientDetail.setupMeasFinger = None\r\n self.patientDetail.setupMeasShoulder = None\r\n self.patientDetail.wristMVC = None\r\n self.patientDetail.fingerMVC = None\r\n self.patientDetail.shoulderMVC = None\r\n self.patientDetail.beenExported = None \r\n\r\n self.Window.label_5.setText(self.Window._translate(\"OverViewWindow\", \"Session no. \")) \r\n self.Window.label_10.setText(self.Window._translate(\"OverViewWindow\", \"Patient: - \")) \r\n self.patientRegister()\r\n\r\n\r\n\r\n def passCurrentExercise(self,n):\r\n self.EXERCISE_SET = n\r\n self.startUIWindow()\r\n if n==1:\r\n self.Window.currentExerciseSelection = \"Wrist Extension\"\r\n \r\n elif n==2:\r\n self.Window.currentExerciseSelection = \"Finger Flexion\"\r\n\r\n elif n==3:\r\n self.Window.currentExerciseSelection = \"Shoulder Flexion\"\r\n \r\n self.Window.label_4.setText(self.Window._translate(\"OverViewWindow\", self.Window.currentExerciseSelection))\r\n \r\n self.Window.show() \r\n\r\n########################################################################################################################################\r\n # init prev patient #\r\n########################################################################################################################################\r\n\r\n def loadPreviousSessionData(self,ID):\r\n # find how many sessions they have had\r\n self.previousData.sessionNum = getNumSessions(ID+self.currentDetails.ur)\r\n self.currentDetails.sessionNum = (self.previousData.sessionNum + 1)\r\n self.currentDetails.beenExported = YES\r\n self.previousData.wristMVC = getPreviousWrist(self.previousData.sessionNum,ID,self.currentDetails.ur)\r\n self.previousData.shoulderMVC = getPreviousShoulder(self.previousData.sessionNum,ID,self.currentDetails.ur)\r\n self.previousData.fingerMVC = getPreviousFinger(self.previousData.sessionNum,ID,self.currentDetails.ur)\r\n self.previousData.setupMeas = getSetupMeasurement(self.previousData.sessionNum,ID,self.currentDetails.ur)\r\n\r\n self.currentDetails.setupMeasWrist = self.previousData.setupMeas[0]\r\n self.currentDetails.setupMeasFinger = self.previousData.setupMeas[1]\r\n self.currentDetails.setupMeasShoulder = self.previousData.setupMeas[2] \r\n \r\n self.Window.SessionNum = self.currentDetails.sessionNum\r\n \r\n\r\n # Run after patients name is entered \r\n # Checks id code ( the names initals ) for a current file under the given initals\r\n # IF a current file is there --> load in the data as the patients details\r\n # ELSE continue on new patient files\r\n def checkDetail(self,ui_patientReg):\r\n\r\n # Setting up the current details for the patient\r\n name=ui_patientReg.PnameLine.text()\r\n ur=ui_patientReg.URnumLine.text()\r\n\r\n self.patientDetail.patientName = name\r\n # set up current details class\r\n temp = loadClinicianName()\r\n self.currentDetails.clinicanName = temp\r\n self.currentDetails.date = datetime.today().strftime('%Y-%m-%d')\r\n self.currentDetails.patientID = getPatientID(name)\r\n self.currentDetails.ur = ur\r\n self.currentDetails.patientName = name\r\n\r\n #Check if patient has previous history\r\n # if new checkPatientDetails returns 0\r\n # if has previous sessions checkPatientDetails returns 1\r\n\r\n if(checkPatientDetails(name,ur)==1):\r\n print(\"PREVIOUS PATIENT\")\r\n self.previousData = previousPatientData()\r\n self.loadPreviousSessionData(self.currentDetails.patientID)\r\n else:\r\n print(\"NEW PATIENT\")\r\n self.currentDetails.sessionNum = 1\r\n \r\n\r\n # Start next pop-up for window\r\n # self.show() \r\n self.startUIWindow()\r\n\r\n\r\n########################################################################################################################################\r\n # Export Function #\r\n########################################################################################################################################\r\n \r\n def exportData(self):\r\n\r\n self.currentDetails.beenExported = YES\r\n\r\n # If patients first session must make a new directory for it\r\n PATH = 'Patient Details/{}'.format((self.currentDetails.patientID+self.currentDetails.ur))\r\n if (self.currentDetails.sessionNum == 1):\r\n os.mkdir(PATH)\r\n \r\n file = open(\"{}/{}{}.txt\".format(PATH,self.currentDetails.patientID,self.currentDetails.sessionNum), \"w\") \r\n file.writelines('PatientID:{}\\n'.format(self.currentDetails.patientID))\r\n file.writelines('PatientName:{}\\n'.format(self.currentDetails.patientName))\r\n file.writelines('Date:{}\\n'.format(self.currentDetails.date))\r\n file.writelines('Clinician:{}\\n'.format(self.currentDetails.clinicanName))\r\n file.writelines('sessionNum:{}\\n'.format(self.currentDetails.sessionNum))\r\n file.writelines('setupMeasWrist:{}\\n'.format(self.currentDetails.setupMeasWrist))\r\n file.writelines('setupMeasFinger:{}\\n'.format(self.currentDetails.setupMeasFinger))\r\n file.writelines('setupMeasShoulder:{}\\n'.format(self.currentDetails.setupMeasShoulder))\r\n file.writelines('wristMVC:{}\\n'.format(self.currentDetails.wristMVC))\r\n file.writelines('fingerMVC:{}\\n'.format(self.currentDetails.fingerMVC))\r\n file.writelines('shoulderMVC:{}\\n'.format(self.currentDetails.shoulderMVC))\r\n\r\n\r\n########################################################################################################################################\r\n # Start Application #\r\n########################################################################################################################################\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n\r\n w = MainWindow()\r\n sys.exit(app.exec_())\r\n \r\n\r\n","sub_path":"UI/.history/mainFile_20210520185926.py","file_name":"mainFile_20210520185926.py","file_ext":"py","file_size_in_byte":26428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"579194568","text":"from parsl.config import Config\n\nfrom parsl.channels import LocalChannel\nfrom parsl.providers import SlurmProvider\nfrom parsl.executors import HighThroughputExecutor\nfrom parsl.addresses import address_by_hostname\n\nfrom parsl.data_provider.scheme import GlobusScheme\n\nconfig = Config(\n executors=[\n HighThroughputExecutor(\n label=\"s2_htex\",\n worker_debug=True,\n address=address_by_hostname(),\n provider=SlurmProvider(\n channel=LocalChannel(),\n nodes_per_block=1,\n init_blocks=1,\n min_blocks=1,\n max_blocks=1,\n partition='skx-normal',\n scheduler_options='''#SBATCH -A Parsl-Eval''',\n worker_init='''source activate parsl-test''',\n walltime='00:30:00'\n ),\n storage_access=[GlobusScheme(\n endpoint_uuid=\"ceea5ca0-89a9-11e7-a97f-22000a92523b\",\n endpoint_path=\"/\",\n local_path=\"/\"\n )]\n )\n\n ],\n)","sub_path":"config/stampede2.py","file_name":"stampede2.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"444629386","text":"import pandas as pd\nfrom datetime import datetime, timedelta\nfrom .portfolio import Portfolio\nfrom .trading_day import TradingDay\nimport empyrical\nfrom .. import performance_utils\n\n\nclass Strategy:\n def __init__(self, **kwargs):\n self.name = kwargs.get(\"name\")\n self.start_date = kwargs.get(\"start_date\")\n self.end_date = kwargs.get(\"end_date\")\n self.date = self.start_date\n\n self.market_df = kwargs.get(\"market_df\")\n self.market_df_pct_change = self.market_df.pct_change()\n\n # set trading days & rebalancing days\n trading_day = TradingDay(self.market_df.index.to_series().reset_index(drop=True))\n self.trading_days = trading_day.get_trading_day_list(self.start_date, self.end_date).to_list()\n\n self.rebalancing_periodic = kwargs.get(\"rebalancing_periodic\")\n self.rebalancing_moment = kwargs.get(\"rebalancing_moment\")\n self.rebalancing_days = trading_day.get_rebalancing_days(self.start_date, self.end_date,\n self.rebalancing_periodic, self.rebalancing_moment)\n\n self.portfolio = Portfolio()\n self.portfolio_log = pd.DataFrame()\n self.simulation_status = {}\n self.simulation_result = {}\n self.event_log = pd.DataFrame(columns=[\"datetime\", \"log\"])\n self.exist_reservation_order = False\n self.reservation_order = pd.Series()\n self.selected_asset_counts = pd.Series()\n\n def initialize(self):\n pass\n\n def on_data(self):\n pass\n\n def run(self):\n self.initialize()\n\n end_date = self.end_date\n while self.date <= end_date:\n if self.is_trading_day():\n if self.exist_reservation_order:\n self.execute_reservation_order()\n if self.is_rebalancing_day():\n self.on_data()\n self.on_end_of_day()\n self.date += timedelta(days=1)\n self.on_end_of_algorithm()\n\n def execute_reservation_order(self):\n self.portfolio.set_allocations(self.reservation_order)\n self.selected_asset_counts.loc[self.date] = len(self.reservation_order)\n self.reservation_order = pd.Series()\n self.exist_reservation_order = False\n\n def reserve_order(self, allocation: pd.Series):\n self.reservation_order = allocation\n self.exist_reservation_order = True\n\n def log_event(self, msg: str):\n self.event_log.loc[len(self.event_log)] = [self.date, msg]\n\n def is_trading_day(self):\n today = self.date\n if today in self.trading_days:\n return True\n else:\n return False\n\n def is_rebalancing_day(self):\n today = self.date\n if today in self.rebalancing_days:\n return True\n else:\n return False\n\n def on_start_of_day(self):\n pass\n\n def on_end_of_day(self):\n pass\n\n def on_end_of_algorithm(self):\n pass\n\n def log_portfolio_value(self):\n port_value = self.portfolio.get_total_portfolio_value()\n cash = self.portfolio.cash\n\n self.portfolio_log.loc[self.date, \"port_value\"] = port_value\n self.portfolio_log.loc[self.date, \"cash\"] = cash\n\n for ticker, amount in self.portfolio.security_holding.items():\n self.portfolio_log.loc[self.date, ticker + \"_amount\"] = amount\n\n def update_portfolio_value(self):\n self.portfolio.update_holdings_value(self.date, self.market_df_pct_change)\n\n def set_holdings(self, ticker: str, weight: float):\n self.portfolio.set_weight(ticker, weight)\n\n def set_start_date(self, year: int, month: int, day: int):\n self.start_date = datetime(year, month, day)\n\n def set_end_date(self, year: int, month: int, day: int):\n date = datetime(year, month, day)\n assert date >= self.start_date\n self.end_date = date\n\n def set_rebalancing_days(self, date_list: list):\n self.rebalancing_days = [*date_list]\n\n def liquidate(self, ticker: str):\n self.set_holdings(ticker, 0)\n\n def get_daily_return(self):\n return self.portfolio_log['port_value'].pct_change()\n\n def get_result(self):\n portfolio_log = self.portfolio_log\n event_log = self.event_log\n result = self.get_result_from_portfolio_log(portfolio_log)\n result['event_log'] = event_log\n return result\n\n def get_result_from_portfolio_log(self, portfolio_log):\n performance = calc_performance_from_value_history(portfolio_log[\"port_value\"])\n portfolio_weight = portfolio_log.divide(portfolio_log['port_value'], axis=0)\n rebalancing_weight = portfolio_weight.loc[self.rebalancing_days]\n\n port_drawdown = performance.get(\"drawdown\")\n portfolio_log = pd.concat([portfolio_log, port_drawdown], axis=1)\n performance[\"portfolio_log\"] = portfolio_log\n\n result = dict()\n result['performance'] = performance\n result['rebalancing_weight'] = rebalancing_weight\n return result\n\n def result_to_excel(self, file_name=None, folder_path=None):\n if file_name is None:\n file_name = self.name\n\n if folder_path is None:\n path = f\"./{file_name}.xlsx\"\n else:\n path = f\"./{folder_path}/{file_name}.xlsx\"\n\n result = self.get_result()\n save_simulation_result_to_excel_file(result, path)\n\n def port_value_to_csv(self, file_name=None, folder_path=None):\n if file_name is None:\n file_name = self.name\n\n if folder_path is None:\n path = f\"./{file_name}.csv\"\n else:\n path = f\"./{folder_path}/{file_name}.csv\"\n\n result = self.get_result()\n performance = result['performance']\n portfolio_log = performance[\"portfolio_log\"]\n port_value = portfolio_log['port_value']\n port_value.to_csv(path, encoding='cp949')\n\n def selected_asset_counts_to_csv(self, file_name=None, folder_path=None):\n if file_name is None:\n file_name = self.name\n\n if folder_path is None:\n path = f\"./{file_name}.csv\"\n else:\n path = f\"./{folder_path}/{file_name}.csv\"\n\n self.selected_asset_counts.to_csv(path, encoding='cp949')\n\n\ndef save_simulation_result_to_excel_file(result: dict, path: str) -> None:\n performance = result['performance']\n event_log = result['event_log']\n rebalancing_weight = result['rebalancing_weight']\n\n portfolio_log = performance[\"portfolio_log\"]\n monthly_returns = performance[\"monthly_returns\"]\n annual_summary = performance[\"annual_summary\"]\n performance_summary = performance[\"performance_summary\"]\n with pd.ExcelWriter(path, datetime_format=\"yyyy-mm-dd\") as writer:\n portfolio_log.to_excel(writer, sheet_name=\"portfolio log\")\n monthly_returns.to_excel(writer, sheet_name=\"월별수익률\")\n annual_summary.to_excel(writer, sheet_name=\"연도별 요약\")\n performance_summary.to_excel(writer, sheet_name=\"요약\")\n event_log.to_excel(writer, sheet_name=\"event log\")\n rebalancing_weight.to_excel(writer, sheet_name=\"리밸런싱 비중\")\n\n\ndef calc_performance_from_value_history(daily_values: pd.Series) -> dict:\n daily_returns = daily_values.pct_change()\n final_returns = daily_values.iloc[-1] / 100 - 1\n\n monthly_returns = empyrical.aggregate_returns(daily_returns, \"monthly\")\n yearly_returns = empyrical.aggregate_returns(daily_returns, \"yearly\")\n performance_summary = performance_utils.get_performance_summary(daily_returns, final_returns)\n\n annual_std = performance_utils.get_annual_std(daily_returns)\n annual_summary = pd.concat([yearly_returns, annual_std], axis=1)\n annual_summary.columns = [\"수익률\", \"변동성\"]\n\n cumulative_returns = performance_utils.convert_values_to_cumulative_returns(daily_values)\n drawdown = performance_utils.get_draw_down(cumulative_returns)\n\n return {\n \"monthly_returns\": monthly_returns,\n \"yearly_returns\": yearly_returns,\n \"performance_summary\": performance_summary,\n \"annual_summary\": annual_summary,\n \"drawdown\": drawdown\n }\n","sub_path":"quantrading/backtest/backtest.py","file_name":"backtest.py","file_ext":"py","file_size_in_byte":8183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"38779752","text":"from . import import_owmap\nfrom . import import_owentity\nfrom . import import_owmdl\nfrom . import import_owmat\nfrom . import import_oweffect\nfrom . import owm_types\nfrom . import bpyhelper\nimport bpy\nfrom bpy.props import StringProperty, BoolProperty, FloatProperty, IntProperty, CollectionProperty\nfrom bpy_extras.io_utils import ImportHelper\nfrom bpy.app.handlers import persistent\nfrom bpy.utils import smpte_from_seconds\nfrom datetime import datetime\n\n\nclass ImportOWMDL(bpy.types.Operator, ImportHelper):\n bl_idname = 'import_mesh.overtools_model'\n bl_label = 'Import Overtools Model (owmdl)'\n bl_options = {'UNDO'}\n\n filename_ext = '.owmdl'\n filter_glob : StringProperty(\n default='*.owmdl',\n options={'HIDDEN'},\n )\n\n uvDisplX : IntProperty(\n name='X',\n description='Displace UV X axis',\n default=0,\n )\n\n uvDisplY : IntProperty(\n name='Y',\n description='Displace UV Y axis',\n default=0,\n )\n\n autoIk : BoolProperty(\n name='AutoIK',\n description='Set AutoIK',\n default=True,\n )\n\n importNormals : BoolProperty(\n name='Import Normals',\n description='Import Custom Normals',\n default=True,\n )\n\n autoSmoothNormals : BoolProperty(\n name='Auto Smooth Normals',\n description='Auto Smooth Normals around soft edges',\n default=True,\n )\n\n importColor : BoolProperty(\n name='Import Color',\n description='Import Custom Colors',\n default=True,\n )\n\n importEmpties : BoolProperty(\n name='Import Sockets',\n description='Import Sockets (attachment points)',\n default=False,\n )\n\n importMaterial : BoolProperty(\n name='Import Material',\n description='Import Referenced OWMAT',\n default=True,\n )\n\n importSkeleton : BoolProperty(\n name='Import Skeleton',\n description='Import Bones',\n default=True,\n )\n\n def menu_func(self, context):\n self.layout.operator_context = 'INVOKE_DEFAULT'\n self.layout.operator(\n ImportOWMDL.bl_idname,\n text='Text Export Operator')\n\n @classmethod\n def poll(cls, context):\n return True\n\n def execute(self, context):\n settings = owm_types.OWSettings(\n self.filepath,\n self.uvDisplX,\n self.uvDisplY,\n self.autoIk,\n self.importNormals,\n self.importEmpties,\n self.importMaterial,\n self.importSkeleton,\n self.importColor,\n self.autoSmoothNormals\n )\n owm_types.update_data()\n t = datetime.now()\n bpyhelper.LOCK_UPDATE = False\n try:\n import_owmdl.read(settings)\n except KeyboardInterrupt:\n bpyhelper.LOCK_UPDATE = False\n print('Done. SMPTE: %s' % (smpte_from_seconds(datetime.now() - t)))\n return {'FINISHED'}\n\n def draw(self, context):\n layout = self.layout\n\n col = layout.column(align=True)\n col.label(text = 'Mesh')\n col.prop(self, 'importNormals')\n col.prop(self, 'autoSmoothNormals')\n col.prop(self, 'importEmpties')\n col.prop(self, 'importColor')\n col.prop(self, 'importMaterial')\n sub = col.row()\n sub.label(text = 'UV')\n sub.prop(self, 'uvDisplX')\n sub.prop(self, 'uvDisplY')\n\n col = layout.column(align=True)\n col.label(text = 'Armature')\n col.prop(self, 'importSkeleton')\n sub = col.row()\n sub.prop(self, 'autoIk')\n sub.enabled = self.importSkeleton\n\n # col = layout.column(align=True)\n # col.enabled = self.importMaterial and bpy.context.scene.render.engine != 'CYCLES'\n # col.label(text = 'Material')\n\n\nclass ImportOWMAT(bpy.types.Operator, ImportHelper):\n bl_idname = 'import_material.overtools_material'\n bl_label = 'Import Overtools Material (owmat)'\n bl_options = {'UNDO'}\n\n filename_ext = '.owmat'\n filter_glob : StringProperty(\n default='*.owmat',\n options={'HIDDEN'},\n )\n\n def menu_func(self, context):\n self.layout.operator_context = 'INVOKE_DEFAULT'\n self.layout.operator(\n ImportOWMAT.bl_idname,\n text='Text Export Operator')\n\n @classmethod\n def poll(cls, context):\n return True\n\n def execute(self, context):\n owm_types.update_data()\n t = datetime.now()\n bpyhelper.LOCK_UPDATE = False\n try:\n import_owmat.read(self.filepath, '')\n except KeyboardInterrupt:\n bpyhelper.LOCK_UPDATE = False\n print('Done. SMPTE: %s' % (smpte_from_seconds(datetime.now() - t)))\n return {'FINISHED'}\n\n def draw(self, context):\n layout = self.layout\n # col = layout.column(align=True)\n # col.label(text = 'Material')\n # col.enabled = bpy.context.scene.render.engine != 'CYCLES'\n\n\nclass ImportOWMAP(bpy.types.Operator, ImportHelper):\n bl_idname = 'import_mesh.overtools_map'\n bl_label = 'Import Overtools Map (owmap)'\n bl_options = {'UNDO'}\n\n filename_ext = '.owmap'\n filter_glob : bpy.props.StringProperty(\n default='*.owmap',\n options={'HIDDEN'},\n )\n\n uvDisplX : IntProperty(\n name='X',\n description='Displace UV X axis',\n default=0,\n )\n\n uvDisplY : IntProperty(\n name='Y',\n description='Displace UV Y axis',\n default=0,\n )\n\n importNormals : BoolProperty(\n name='Import Normals',\n description='Import Custom Normals',\n default=True,\n )\n\n autoSmoothNormals : BoolProperty(\n name='Auto Smooth Normals',\n description='Auto Smooth Normals around soft edges',\n default=True,\n )\n\n importColor : BoolProperty(\n name='Import Color',\n description='Import Custom Colors',\n default=True,\n )\n\n importObjects : BoolProperty(\n name='Import Objects',\n description='Import Map Objects',\n default=True,\n )\n\n importDetails : BoolProperty(\n name='Import Props',\n description='Import Map Props',\n default=True,\n )\n\n importLights : BoolProperty(\n name='Import Lights',\n description='Import Map Lights',\n default=True,\n )\n\n importPhysics : BoolProperty(\n name='Import Collision Model',\n description='Import Map Collision Model',\n default=False,\n )\n\n importMaterial : BoolProperty(\n name='Import Material',\n description='Import Referenced OWMAT',\n default=True,\n )\n\n importLampSun : BoolProperty(\n name='Import Sun lamps',\n description='Import lamps of type Sun',\n default=False,\n )\n\n importLampSpot : BoolProperty(\n name='Import Spot lamps',\n description='Import lamps of type Spot',\n default=True,\n )\n\n importLampPoint : BoolProperty(\n name='Import Point lamps',\n description='Import lamps of type Point',\n default=True,\n )\n\n multipleImportance : BoolProperty(\n name='Multiple Importance',\n default=False,\n )\n\n adjustLightValue : FloatProperty(\n name='Adjust Light Value',\n description='Multiply value (HSV) by this amount',\n default=1.0,\n step=0.1,\n min=0.0,\n max=1.0,\n precision=3\n )\n\n useLightStrength : BoolProperty(\n name='Use Light Strength',\n description='Use light strength data (Experimental)',\n default=True,\n )\n\n shadowSoftBias : FloatProperty(\n name='Light Shadow Size',\n description='Light size for ray shadow sampling',\n default=0.5,\n step=0.1,\n min=0.0,\n precision=3\n )\n\n adjustLightStrength : FloatProperty(\n name='Adjust Light Strength',\n description='Multiply strength by this amount',\n default=10.0,\n step=1,\n min=0.0,\n precision=3\n )\n\n lightIndex : IntProperty(\n name='Light Value Index',\n description='Used for debug purposes, leave it at 25',\n default=25,\n step=1,\n min=0,\n max=35\n )\n\n edgeIndex : IntProperty(\n name='Light Spot Edge Index',\n description='Used for debug purposes, leave it at 26',\n default=26,\n step=1,\n min=0,\n max=35\n )\n\n sizeIndex : IntProperty(\n name='Light Size Index',\n description='Used for debug purposes, leave it at 12',\n default=12,\n step=1,\n min=0,\n max=35\n )\n\n importRemoveCollision : BoolProperty(\n name='Remove Collision Models',\n description='Remove the collision models',\n default=True,\n )\n\n importSounds : BoolProperty(\n name='Import Sounds',\n description='Imports sound nodes',\n default=True,\n )\n\n def menu_func(self, context):\n self.layout.operator_context = 'INVOKE_DEFAULT'\n self.layout.operator(\n ImportOWMAP.bl_idname,\n text='Text Export Operator')\n\n @classmethod\n def poll(cls, context):\n return True\n\n def execute(self, context):\n settings = owm_types.OWSettings(\n self.filepath,\n self.uvDisplX,\n self.uvDisplY,\n False,\n self.importNormals,\n False,\n self.importMaterial,\n False,\n self.importColor,\n self.autoSmoothNormals\n )\n light_settings = owm_types.OWLightSettings(\n self.importLights,\n self.multipleImportance,\n [self.importLampSun, self.importLampSpot, self.importLampPoint],\n [self.adjustLightValue, self.adjustLightStrength],\n self.useLightStrength,\n self.shadowSoftBias,\n [self.lightIndex, self.edgeIndex, self.sizeIndex]\n )\n owm_types.update_data()\n t = datetime.now()\n bpyhelper.LOCK_UPDATE = False\n try:\n import_owmap.read(settings, self.importObjects, self.importDetails, self.importPhysics, light_settings, self.importRemoveCollision, self.importSounds)\n except KeyboardInterrupt:\n bpyhelper.LOCK_UPDATE = False\n print('Done. SMPTE: %s' % (smpte_from_seconds(datetime.now() - t)))\n return {'FINISHED'}\n\n def draw(self, context):\n layout = self.layout\n\n col = layout.column(align=True)\n col.label(text = 'Mesh')\n col.prop(self, 'importNormals')\n col.prop(self, 'autoSmoothNormals')\n col.prop(self, 'importColor')\n col.prop(self, 'importMaterial')\n\n sub = col.row()\n sub.label(text = 'UV')\n sub.prop(self, 'uvDisplX')\n sub.prop(self, 'uvDisplY')\n\n col = layout.column(align=True)\n col.label(text = 'Map')\n col.prop(self, 'importObjects')\n col.prop(self, 'importDetails')\n col.prop(self, 'importSounds')\n\n sub = col.row()\n sub.prop(self, 'importPhysics')\n sub.enabled = self.importDetails\n\n col.prop(self, 'importLights')\n col.prop(self, 'importRemoveCollision')\n\n # col = layout.column(align=True)\n # col.label(text = 'Material')\n # col.enabled = self.importMaterial and bpy.context.scene.render.engine != 'CYCLES'\n\n col = layout.column(align=True)\n col.label(text = 'Lights')\n col.enabled = self.importLights\n col.prop(self, 'importLampSun')\n col.prop(self, 'importLampSpot')\n col.prop(self, 'importLampPoint')\n col.prop(self, 'multipleImportance')\n col.prop(self, 'useLightStrength')\n col.prop(self, 'shadowSoftBias')\n col.prop(self, 'adjustLightValue')\n col2 = col.column(align=True)\n col2.enabled = self.useLightStrength\n col2.prop(self, 'adjustLightStrength')\n col2.prop(self, 'lightIndex')\n col.prop(self, 'edgeIndex')\n col.prop(self, 'sizeIndex')\n\n\nclass ImportOWENTITY(bpy.types.Operator, ImportHelper):\n bl_idname = 'import_mesh.overtools_entity'\n bl_label = 'Import Overtools Entity (owentity)'\n bl_options = {'UNDO'}\n\n filename_ext = '.owentity'\n filter_glob : bpy.props.StringProperty(\n default='*.owentity',\n options={'HIDDEN'},\n )\n\n import_children : BoolProperty(\n name='Import Children',\n description='Import child entities',\n default=True,\n )\n\n uvDisplX : IntProperty(\n name='X',\n description='Displace UV X axis',\n default=0,\n )\n\n uvDisplY : IntProperty(\n name='Y',\n description='Displace UV Y axis',\n default=0,\n )\n\n autoIk : BoolProperty(\n name='AutoIK',\n description='Set AutoIK',\n default=True,\n )\n\n importNormals : BoolProperty(\n name='Import Normals',\n description='Import Custom Normals',\n default=True,\n )\n\n autoSmoothNormals : BoolProperty(\n name='Auto Smooth Normals',\n description='Auto Smooth Normals around soft edges',\n default=True,\n )\n\n importColor : BoolProperty(\n name='Import Color',\n description='Import Custom Colors',\n default=True,\n )\n\n importEmpties : BoolProperty(\n name='Import Empties',\n description='Import Empty Objects',\n default=False,\n )\n\n importMaterial : BoolProperty(\n name='Import Material',\n description='Import Referenced OWMAT',\n default=True,\n )\n\n importSkeleton : BoolProperty(\n name='Import Skeleton',\n description='Import Bones',\n default=True,\n )\n\n def menu_func(self, context):\n self.layout.operator_context = 'INVOKE_DEFAULT'\n self.layout.operator(\n ImportOWMAP.bl_idname,\n text='Text Export Operator')\n\n @classmethod\n def poll(cls, context):\n return True\n\n def execute(self, context):\n settings = owm_types.OWSettings(\n self.filepath,\n self.uvDisplX,\n self.uvDisplY,\n self.autoIk,\n self.importNormals,\n True, # self.importEmpties\n self.importMaterial,\n True, # self.importSkeleton\n self.importColor,\n self.autoSmoothNormals\n )\n owm_types.update_data()\n t = datetime.now()\n bpyhelper.LOCK_UPDATE = False\n try:\n import_owentity.read(settings, self.import_children)\n except KeyboardInterrupt:\n bpyhelper.LOCK_UPDATE = False\n print('Done. SMPTE: %s' % (smpte_from_seconds(datetime.now() - t)))\n return {'FINISHED'}\n\n def draw(self, context):\n layout = self.layout\n\n col = layout.column(align=True)\n col.label(text = 'Entity')\n col.prop(self, 'import_children')\n\n col = layout.column(align=True)\n col.label(text = 'Mesh')\n col.prop(self, 'importNormals')\n col.prop(self, 'autoSmoothNormals')\n col.prop(self, 'importColor')\n col.prop(self, 'importMaterial')\n sub = col.row()\n sub.label(text = 'UV')\n sub.prop(self, 'uvDisplX')\n sub.prop(self, 'uvDisplY')\n\n col = layout.column(align=True)\n col.label(text = 'Armature')\n sub = col.row()\n sub.prop(self, 'autoIk')\n sub.enabled = self.importSkeleton\n\n # col = layout.column(align=True)\n # col.enabled = self.importMaterial and bpy.context.scene.render.engine != 'CYCLES'\n # col.label(text = 'Material')\n\n\nclass ImportOWEFFECT(bpy.types.Operator, ImportHelper):\n bl_idname = 'import_anim.overtools_effect'\n bl_label = 'Import Overtools Animation Effect (oweffect, owanim)'\n bl_options = {'UNDO'}\n\n filename_ext = '.oweffect;.owanim'\n filter_glob : bpy.props.StringProperty(\n default='*.oweffect;*.owanim',\n options={'HIDDEN'},\n )\n\n import_dmce : BoolProperty(\n name='Import DMCE (Models)',\n description='Import DMCE',\n default=True,\n )\n\n import_cece : BoolProperty(\n name='Import CECE (Entity Control)',\n description='Import CECE',\n default=True,\n )\n\n import_nece : BoolProperty(\n name='Import NECE (Entities)',\n description='Import NECE',\n default=True,\n )\n\n import_svce : BoolProperty(\n name='Import SVCE (Voice) (EXPERIMENTAL)',\n description='Import SVCE. WARNING: CAN CRASH BLENDER',\n default=False,\n )\n\n svce_line_seed : IntProperty(\n name='SVCE Line seed',\n description='SVCE Line seed',\n default=-1,\n min=-1\n )\n\n svce_sound_seed : IntProperty(\n name='SVCE Sound seed',\n description='SVCE Sound seed',\n default=-1,\n min=-1\n )\n\n cleanup_hardpoints : BoolProperty(\n name='Cleanup Sockets',\n description='Remove unused sockets',\n default=True,\n )\n\n force_framerate : BoolProperty(\n name='Force Framerate',\n description='Force Framerate',\n default=False,\n )\n\n target_framerate : IntProperty(\n name='Target Framerate',\n description='Target Framerate',\n default=60,\n min=1\n )\n\n import_camera : BoolProperty(\n name='Create Camera',\n description='Create an estimation of the animation camera',\n default=False,\n )\n\n def menu_func(self, context):\n self.layout.operator_context = 'INVOKE_DEFAULT'\n self.layout.operator(\n ImportOWMAP.bl_idname,\n text='Text Export Operator')\n\n @classmethod\n def poll(cls, context):\n return True\n\n def execute(self, context):\n settings = owm_types.OWSettings(\n self.filepath,\n 0,\n 0,\n True,\n True,\n True,\n True,\n True,\n True,\n True\n )\n\n efct_settings = owm_types.OWEffectSettings(settings, self.filepath, self.force_framerate,\n self.target_framerate, self.import_dmce, self.import_cece,\n self.import_nece,\n self.import_svce, self.svce_line_seed, self.svce_sound_seed,\n self.import_camera,\n self.cleanup_hardpoints)\n owm_types.update_data()\n t = datetime.now()\n bpyhelper.LOCK_UPDATE = False\n try:\n import_oweffect.read(efct_settings)\n except KeyboardInterrupt:\n bpyhelper.LOCK_UPDATE = False\n print('Done. SMPTE: %s' % (smpte_from_seconds(datetime.now() - t)))\n return {'FINISHED'}\n\n def draw(self, context):\n layout = self.layout\n\n col = layout.column(align=True)\n col.label(text = 'Effect')\n col.prop(self, 'import_dmce')\n col.prop(self, 'import_cece')\n col.prop(self, 'import_nece')\n col.prop(self, 'import_svce')\n svce_col = col.column(align=True)\n svce_col.enabled = self.import_svce\n svce_col.prop(self, 'svce_line_seed')\n svce_col.prop(self, 'svce_sound_seed')\n\n col.label(text = 'Animation')\n col.prop(self, 'import_camera')\n col.prop(self, 'cleanup_hardpoints')\n col.prop(self, 'force_framerate')\n col2 = layout.column(align=True)\n col2.enabled = self.force_framerate\n col2.prop(self, 'target_framerate')\n\n\ndef mdlimp(self, context):\n self.layout.operator(\n ImportOWMDL.bl_idname,\n text='Overtools Model (.owmdl)'\n )\n\n\ndef matimp(self, context):\n self.layout.operator(\n ImportOWMAT.bl_idname,\n text='Overtools Material (.owmat)'\n )\n\n\ndef mapimp(self, context):\n self.layout.operator(\n ImportOWMAP.bl_idname,\n text='Overtools Map (.owmap)'\n )\n\n\ndef entity_import(self, context):\n self.layout.operator(\n ImportOWENTITY.bl_idname,\n text='Overtools Entity (.owentity)'\n )\n\n\ndef effect_import(self, context):\n self.layout.operator(\n ImportOWEFFECT.bl_idname,\n text='Overtools Animation Effect (.oweffect/.owanim)'\n )\n\n\nclass OWMUtilityPanel(bpy.types.Panel):\n bl_idname = 'OBJECT_PT_owm_panel'\n bl_label = 'OWM Tools'\n bl_space_type = 'PROPERTIES'\n bl_region_type = 'WINDOW'\n bl_context = 'scene'\n\n @classmethod\n def poll(cls, context): return 1\n\n def draw_header(self, context):\n layout = self.layout\n\n def draw(self, context):\n layout = self.layout\n\n row = layout.row()\n row.operator(OWMLoadOp.bl_idname, text='Import OWM Library', icon='LINK_BLEND')\n row.operator(OWMSaveOp.bl_idname, text='Export OWM Library', icon='APPEND_BLEND')\n row = layout.row()\n row.prop(bpy.context.scene.owm_internal_settings, 'b_logsalot', text='Log Map Progress')\n row = layout.row()\n row.prop(bpy.context.scene.owm_internal_settings, 'b_download', text='Download Library')\n split = row.split()\n split.prop(bpy.context.scene.owm_internal_settings, 'b_allow_download', text='Always')\n split.enabled = bpy.context.scene.owm_internal_settings.b_download\n\n box = layout.box()\n box.label(text = 'Cleanup')\n row = box.row()\n row.operator(OWMCleanupOp.bl_idname, text='Unused Empty Objects', icon='OBJECT_DATA')\n row = box.row()\n row.operator(OWMCleanupTexOp.bl_idname, text='Unused Materials', icon='MATERIAL')\n\n\nclass OWMLoadOp(bpy.types.Operator):\n \"\"\"Load OWM Material Library\"\"\"\n bl_idname = 'owm.load_library'\n bl_label = 'Import OWM Library'\n\n def execute(self, context):\n owm_types.update_data()\n return {'FINISHED'}\n\n def invoke(self, context, event):\n return self.execute(context)\n\n\nclass OWMSaveOp(bpy.types.Operator):\n \"\"\"Export OWM Material Library\"\"\"\n bl_idname = 'owm.save_library'\n bl_label = 'Export OWM Library'\n\n def execute(self, context):\n owm_types.create_overwatch_library()\n return {'FINISHED'}\n\n def invoke(self, context, event):\n return self.execute(context)\n\n\nclass OWMCleanupOp(bpy.types.Operator):\n \"\"\"Deletes empty objects with no sub objects\"\"\"\n bl_idname = 'owm.delete_unused_empties'\n bl_label = 'Delete Unused Empties'\n\n def execute(self, context):\n bpyhelper.clean_empties()\n return {'FINISHED'}\n\n def invoke(self, context, event):\n return self.execute(context)\n\n\nclass OWMCleanupTexOp(bpy.types.Operator):\n \"\"\"Deletes materials with no owners\"\"\"\n bl_idname = 'owm.delete_unused_materials'\n bl_label = 'Delete Unused Materials'\n\n def execute(self, context):\n bpyhelper.clean_materials()\n return {'FINISHED'}\n\n def invoke(self, context, event):\n return self.execute(context)\n\n\nclass OWMInternalSettings(bpy.types.PropertyGroup):\n b_logsalot : bpy.props.BoolProperty(name=\"Log alot\", description=\"Verbose logging\", \n default=False, update=lambda self, context: self.update_logs_alot(context))\n b_allow_download : bpy.props.BoolProperty(name=\"Allow Library Download\", description=\"Allow the addon to download updated material libraries from Github\", \n default=False, update=lambda self, context: self.update_allow_download(context))\n b_download : bpy.props.BoolProperty(name=\"Always Download Library\", description=\"Always download the material library, even if it is up to date\", \n update=lambda self, context: self.update_download(context))\n i_library_state : IntProperty(update=lambda self, context: self.dummy(context))\n\n def update_logs_alot(self, context):\n owm_types.LOG_ALOT = self.b_logsalot\n\n def update_download(self, context):\n owm_types.ALWAYS_DOWNLOAD = self.b_download\n\n def update_allow_download(self, context):\n owm_types.SHOULD_DOWNLOAD = self.b_allow_download\n\n def dummy(self, context): pass\n\n\n@persistent\ndef owm_reset(_):\n owm_types.reset();\n\nclasses = (\n OWMUtilityPanel,\n OWMLoadOp,\n OWMSaveOp,\n OWMCleanupOp,\n OWMCleanupTexOp,\n OWMInternalSettings,\n ImportOWMDL,\n ImportOWMAT,\n ImportOWMAP,\n ImportOWENTITY,\n ImportOWEFFECT\n)\n\n\ndef register():\n for cls in classes:\n bpy.utils.register_class(cls)\n\n bpy.types.TOPBAR_MT_file_import.append(mdlimp)\n bpy.types.TOPBAR_MT_file_import.append(matimp)\n bpy.types.TOPBAR_MT_file_import.append(mapimp)\n bpy.types.TOPBAR_MT_file_import.append(entity_import)\n bpy.types.TOPBAR_MT_file_import.append(effect_import)\n bpy.types.Scene.owm_internal_settings = bpy.props.PointerProperty(type=OWMInternalSettings)\n bpy.app.handlers.load_post.append(owm_reset)\n\n\ndef unregister():\n owm_reset(None)\n\n for cls in classes:\n bpy.utils.unregister_class(cls)\n\n bpy.app.handlers.load_post.remove(owm_reset)\n bpy.types.TOPBAR_MT_file_import.remove(mdlimp)\n bpy.types.TOPBAR_MT_file_import.remove(matimp)\n bpy.types.TOPBAR_MT_file_import.remove(mapimp)\n bpy.types.TOPBAR_MT_file_import.remove(entity_import)\n bpy.types.TOPBAR_MT_file_import.remove(effect_import)\n bpy.types.Scene.owm_internal_settings = None\n","sub_path":"manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":25255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"135445472","text":"from conftest import Peach\n\n\ndef test_filter_attr(pk, kube):\n all_peaches = {}\n for variety in ['a', 'b', 'c']:\n peaches = []\n for num in range(1):\n p = Peach(namespace=kube.namespace, name=f'{variety}-{num}', variety=variety)\n peaches.append(p)\n pk.save(p)\n all_peaches[variety] = peaches\n\n\n\n # Do a query\n a_peaches = Peach.query.filter_by(variety='a').all()\n assert(set(a_peaches) == set(all_peaches['a']))\n\n\n # Do a second query that is disjoint with the first one\n b_peaches = Peach.query.filter_by(variety='b').all()\n assert(b_peaches == all_peaches['b'])\n\n\ndef test_filter_chain(pk, kube):\n all_peaches = {}\n for variety in ['a', 'b', 'c']:\n pp = {}\n for price in [1, 2, 3]:\n peaches = []\n for num in range(1):\n p = Peach(namespace=kube.namespace, name=f'{variety}-{price}-{num}', variety=variety, price=price)\n peaches.append(p)\n pk.save(p)\n pp[price] = peaches\n all_peaches[variety] = pp\n\n # Do a chain query\n a_1_peaches = Peach.query.filter_by(namespace=kube.namespace).filter_by(variety='a').filter_by(price=1).all()\n assert set(a_1_peaches) == set(all_peaches['a'][1])\n\n # Search on a NS where they're nowhere to be found\n no_peaches = Peach.query.filter_by(namespace='idontexist').filter_by(variety='a').filter_by(price=1).all()\n assert no_peaches == []\n\n # Search for an unknown variety\n rarepeaches = Peach.query.filter_by(namespace=kube.namespace).filter_by(variety='rare').filter_by(price=1).all()\n assert rarepeaches == []\n\n","sub_path":"tests/test_filter.py","file_name":"test_filter.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"541167289","text":"from datetime import datetime\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import HttpResponse\nfrom django.template import loader\n\nfrom .forms import RegisterUserForm, AddCameraForm, LoginUserForm, AddHotelForm, SearchForm\nfrom .models import Camera, Prenotazione, Hotel\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.contrib.auth.models import User\nfrom .forms import *\nfrom django.contrib.auth import authenticate, login as auth_login, logout as auth_logout\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.views import generic\nimport json.encoder\n\n# Create your views here.\n\n\n\n#pagina principale dove l'utente non collegato può prenotare la stanza\ndef index(request):\n\n if (request.method == \"POST\"):\n form = SearchForm(request.POST)\n if form.is_valid():\n city = form.cleaned_data['citta']\n size = form.cleaned_data['postiletto']\n checkin = form.cleaned_data['checkin']\n checkout = form.cleaned_data['checkout']\n listaDisponibili = []\n for camera in Camera.objects.all():\n flag = False\n check = False\n if camera.posti_letto < int(float(size)) or camera.hotel.citta != city:\n continue\n else:\n for pren in Prenotazione.objects.all():\n if pren.camera == camera:\n new_checkin = datetime.strptime(checkin, \"%Y-%m-%d\")\n new_checkout = datetime.strptime(checkout, \"%Y-%m-%d\")\n pren_checkin = datetime.strptime(str(pren.checkin), \"%Y-%m-%d\")\n pren_checkout = datetime.strptime(str(pren.checkout), \"%Y-%m-%d\")\n if (pren_checkin <= new_checkin <= pren_checkout) or (\n pren_checkin <= new_checkout <= pren_checkout):\n check = True\n if new_checkin > new_checkout:\n flag = True\n break\n if check is False:\n listaDisponibili.append(camera)\n if flag == True:\n break\n\n form = SearchForm()\n if (flag == True):\n context = {'dateError': True, 'form': form}\n elif (len(listaDisponibili) == 0):\n context = {'notAvailable': True, 'form': form}\n else:\n servizi = []\n for camera in listaDisponibili:\n servizi.append(camera.servizi.split(\", \"))\n context = {'listaCamere': listaDisponibili, 'listaServizi': servizi, 'checkin': checkin,\n 'checkout': checkout, 'form': form}\n else:\n print(\"Form non valido - Search\")\n context = {'searchFormError': True, 'form': form}\n else:\n form = SearchForm()\n context = {'form': form}\n return render(request, 'booking/index.html', context)\n\n# #pagina di login\n# def login(request):\n# return render(request, 'booking/login.html', {})\n\ndef registrazione(request):\n if (request.method == \"POST\"):\n form = RegisterUserForm(request.POST)\n if form.is_valid():\n newUser = form.save()\n albId = newUser .pk\n context = {'albid': albId}\n auth_login(request, newUser )\n #return render(request, 'booking/home.html', context)\n return redirect('/home/', context)\n else:\n print(\"Form non valido - Registrazione\")\n else:\n form = RegisterUserForm()\n return render(request, 'booking/Registrazione.html', {'form': form})\n\ndef login(request):\n if request.method == \"POST\":\n form = LoginUserForm(request.POST)\n if form.is_valid():\n email = form.cleaned_data['email']\n password = form.cleaned_data['password']\n user = authenticate(request, username=email, password=password)\n if user is not None:\n auth_login(request, user)\n return redirect('booking:home')\n else:\n context = {'loginerrato': True, 'form': form}\n return render(request, 'booking/login.html', context)\n else:\n context = {'formError': True, 'form': form}\n print(\"Form non valido - Registrazione\")\n return render(request, 'booking/Registrazione.html', context)\n else:\n form = LoginUserForm()\n return render(request, 'booking/login.html', {'form': form})\n\n\n\ndef registrazione(request):\n return render(request, 'booking/Registrazione.html', {})\n\n#submit del form di login, riporta alla home se login corretto o a loginerror se erratos\ndef hoteldetail(request):\n return render(request, 'booking/hoteldetail.html', {})\n\n\n#riporta alla pagina di login mostrando un messaggio di errore\ndef loginError(request, loginErrato):\n context = {'loginerrato': loginErrato}\n return render(request, 'booking/login.html', context)\n\ndef search(request):\n city = request.POST.get(\"city\", \"\")\n size = request.POST.get(\"size\", \"\")\n checkin = request.POST.get(\"checkin\", \"\")\n checkout = request.POST.get(\"checkout\", \"\")\n listaDisponibili = []\n for camera in Camera.objects.all():\n flag = False\n check = False\n if camera.posti_letto < int(float(size)) or camera.hotel.citta != city:\n continue\n else:\n for pren in Prenotazione.objects.all():\n if pren.camera == camera:\n new_checkin = datetime.strptime(checkin, \"%Y-%m-%d\")\n new_checkout = datetime.strptime(checkout, \"%Y-%m-%d\")\n pren_checkin = datetime.strptime(str(pren.checkin), \"%Y-%m-%d\")\n pren_checkout = datetime.strptime(str(pren.checkout), \"%Y-%m-%d\")\n if (pren_checkin <= new_checkin <= pren_checkout) or (pren_checkin <= new_checkout <= pren_checkout):\n check = True\n if new_checkin > new_checkout:\n flag = True\n break\n if check is False:\n listaDisponibili.append(camera)\n if flag==True:\n break\n\n if (flag == True):\n context = {'dateError': True}\n elif (len(listaDisponibili) == 0):\n context = {'notAvailable': True}\n else:\n servizi = []\n for camera in listaDisponibili:\n servizi.append(camera.servizi.split(\", \"))\n context = {'listaCamere': listaDisponibili, 'listaServizi': servizi, 'checkin': checkin,\n 'checkout': checkout}\n return render(request, 'booking/index.html', context)\n\n#submit dell'email per la prenotazione, non avviene il refresh della pagina\ndef prenota(request):\n checkin = request.GET.get(\"checkin\", \"\")\n checkout = request.GET.get(\"checkout\", \"\")\n hotel = request.GET.get(\"hotel\", \"\")\n camera = request.GET.get(\"camera\", \"\")\n email = request.GET.get(\"email\", \"\")\n hotelobj = Hotel.objects.get(nome=hotel)\n cameraobj = Camera.objects.get(hotel = hotelobj, numero=camera)\n newp = Prenotazione(email=email, camera=cameraobj, checkin=checkin, checkout=checkout)\n newp.save()\n return render(request, 'booking/index.html', {})\n\ndef manageCamera(request, hotel):\n if (request.method == \"POST\"):\n form = AddCameraForm(request.POST)\n if form.is_valid():\n\n posti_c = form.cleaned_data['posti_letto']\n numero_c = form.cleaned_data['numero']\n servizi_c = form.cleaned_data['servizi']\n\n all_servizi = [\"Wifi\", \"Climatizzatore\", \"Tv\", \"Minifrigo\"]\n check = False\n\n hotelObj = Hotel.objects.get(nome=hotel)\n citta = hotelObj.citta\n servizio = servizi_c.split(\", \")\n\n alreadyexist = False\n checklength = Camera.objects.filter(hotel=hotelObj, numero=numero_c)\n if len(checklength) != 0:\n alreadyexist = True\n\n for serv in servizio:\n if (serv not in all_servizi or (len(servizio) != len(set(servizio)))):\n check = True\n break\n\n if not alreadyexist and not check:\n new_Camera = Camera.objects.create(hotel=hotelObj, numero=numero_c, posti_letto=posti_c, servizi=servizi_c)\n new_Camera.save()\n\n listaCamere = []\n for camera in Camera.objects.all():\n if camera.hotel == hotelObj:\n listaCamere.append(camera)\n servizi = []\n for camera in listaCamere:\n servizi.append(camera.servizi.split(\", \"))\n\n form = AddCameraForm()\n\n if alreadyexist:\n context = {\"hotel\": hotel, \"descrizione\": hotelObj.descrizione, \"indirizzo\": hotelObj.indirizzo,\n \"listaCamere\": listaCamere, \"listaServizi\": servizi, 'errorcamera': True, \"citta\": citta, 'form': form}\n elif check:\n context = {\"hotel\": hotel, \"descrizione\": hotelObj.descrizione, \"indirizzo\": hotelObj.indirizzo,\n \"listaCamere\": listaCamere, \"listaServizi\": servizi, \"erroreservizio\": check, \"citta\": citta, 'form': form}\n else:\n context = {\"hotel\": hotel, \"descrizione\": hotelObj.descrizione, \"indirizzo\": hotelObj.indirizzo,\n \"listaCamere\": listaCamere, \"listaServizi\": servizi, \"citta\": citta, 'form': form}\n\n return render(request, 'booking/hoteldetail.html', context)\n else:\n print(\"Form non valido - AddCameraDetail\")\n hotelObj = Hotel.objects.get(nome=hotel)\n citta = hotelObj.citta\n\n listaCamere = []\n for camera in Camera.objects.all():\n if camera.hotel == hotelObj:\n listaCamere.append(camera)\n servizi = []\n for camera in listaCamere:\n servizi.append(camera.servizi.split(\", \"))\n\n form = AddCameraForm()\n\n context = {\"hotel\": hotel, 'invalidForm': True, 'form': form, \"descrizione\": hotelObj.descrizione,\n \"indirizzo\": hotelObj.indirizzo,\n \"listaCamere\": listaCamere, \"listaServizi\": servizi, \"citta\": citta}\n return render(request, 'booking/hoteldetail.html', context)\n\n else:\n if request.user.is_authenticated:\n form = AddCameraForm()\n hotelObj = Hotel.objects.get(nome=hotel)\n descr = hotelObj.descrizione\n indirizzo = hotelObj.indirizzo\n citta = hotelObj.citta\n listaCamere = []\n for camera in Camera.objects.all():\n if camera.hotel == hotelObj:\n listaCamere.append(camera)\n servizi = []\n for camera in listaCamere:\n servizi.append(camera.servizi.split(\", \"))\n\n context = {\"hotel\": hotel, \"descrizione\": descr, \"indirizzo\": indirizzo, \"listaCamere\": listaCamere,\n \"listaServizi\": servizi, \"citta\": citta, 'form':form}\n return render(request, 'booking/hoteldetail.html', context)\n else:\n return redirect(\"booking:errorpage\")\n\n\n\n\ndef manageHotel(request):\n if (request.method == \"POST\"):\n form = AddHotelForm(request.POST)\n if form.is_valid():\n print(\"Form valido - addHotel\")\n nome_h = form.cleaned_data['nome']\n descrizione_h = form.cleaned_data[\"descrizione\"]\n citta_h = form.cleaned_data[\"citta\"]\n indirizzo_h = form.cleaned_data[\"indirizzo\"]\n\n albId = request.user\n\n alreadyexist = False\n checklength = Hotel.objects.filter(nome=nome_h, proprietario=request.user)\n\n if len(checklength) != 0:\n alreadyexist = True\n else:\n newHotel = Hotel()\n newHotel.nome = nome_h\n newHotel.citta = citta_h\n newHotel.descrizione = descrizione_h\n newHotel.proprietario = request.user\n newHotel.indirizzo = indirizzo_h\n newHotel.save()\n\n allHotels = Hotel.objects.all()\n\n dict_Camera_Hotel = {}\n listaHotel = []\n\n for hotel in allHotels:\n if (hotel.proprietario == albId):\n dict_Camera_Hotel[hotel.nome] = 0\n listaHotel.append(hotel)\n\n for camera in Camera.objects.all():\n for hotel in listaHotel:\n if (camera.hotel.nome == hotel.nome):\n indice_camera = dict_Camera_Hotel[hotel.nome]\n indice_camera += 1\n dict_Camera_Hotel[hotel.nome] = indice_camera\n\n if alreadyexist:\n context = {'allHotels': allHotels, 'dictCamera': dict_Camera_Hotel, 'errorhotel': True, 'form':form}\n else:\n context = {'allHotels': allHotels, 'dictCamera': dict_Camera_Hotel, 'form':form}\n\n return render(request, 'booking/hotels.html', context)\n\n else:\n print(\"Form non valido - addHotel\")\n # context = {'errorhotel': True}\n # return render(request, 'booking/hotels.html', context)\n else:\n form = AddHotelForm()\n if request.user.is_authenticated:\n allHotels = Hotel.objects.all()\n\n dict_Camera_Hotel = {}\n albId = request.user\n\n listaHotel = []\n\n for hotel in allHotels:\n if (hotel.proprietario == albId):\n dict_Camera_Hotel[hotel.nome] = 0\n listaHotel.append(hotel)\n\n for camera in Camera.objects.all():\n for hotel in listaHotel:\n if (camera.hotel.nome == hotel.nome):\n indice_camera = dict_Camera_Hotel[hotel.nome]\n indice_camera += 1\n dict_Camera_Hotel[hotel.nome] = indice_camera\n\n context = {'dictCamera': dict_Camera_Hotel,'form':form}\n\n return render(request, 'booking/hotels.html', context)\n else:\n return redirect(\"booking:errorpage\")\n\n\ndef registraUtente(request):\n newEmail= request.POST.get(\"email\", \"\")\n psw=request.POST.get(\"password\", \"\")\n newNome=request.POST.get(\"nome\", \"\")\n newCognome = request.POST.get(\"cognome\", \"\")\n newUser=User.objects.create_user(username=newEmail,email=newEmail,password=psw)\n newUser.first_name=newNome\n newUser.last_name=newCognome\n newUser.save()\n\n albId = newUser.pk\n context={'albid': albId}\n auth_login(request, newUser)\n return render(request, 'booking/home.html', context)\n\ndef registrazione(request):\n if (request.method == \"POST\"):\n form = RegisterUserForm(request.POST)\n if form.is_valid():\n print(\"Form valido Registrazione\")\n newUser = form.save()\n albId = newUser .pk\n context = {'albid': albId}\n auth_login(request, newUser)\n #return render(request, 'booking/home.html', context)\n return redirect('/home/', context)\n else:\n print(\"Form non valido - Registrazione\")\n else:\n form = RegisterUserForm()\n return render(request, 'booking/Registrazione.html', {'form': form})\n\n\ndef errorpage(request):\n return render(request, 'booking/errorpage.html', {})\n\ndef errorpageredirect(request):\n if request.user.is_authenticated:\n # se l'utente è già autenticato devo mostrare la pagina home con le sue prenotazioni\n lista_Hotel = []\n lista_Camere = []\n lista_User = []\n\n albergatore = request.user\n\n for prenotazione in Prenotazione.objects.all():\n if (prenotazione.camera.hotel.proprietario == albergatore):\n lista_Hotel.append(prenotazione.camera.hotel)\n lista_Camere.append(prenotazione.camera.numero)\n lista_User.append(prenotazione.email)\n\n list = []\n for i in range(0, lista_Hotel.__len__()):\n list.append(i)\n\n context = {'albid': albergatore.pk, 'listaHotel': lista_Hotel, 'listaCamere': lista_Camere,\n 'listaUser': lista_User,\n 'length': list}\n return render(request, 'booking/home.html', context)\n else:\n return redirect(\"booking:index\")\n\ndef home(request):\n if request.user.is_authenticated:\n\n lista_Hotel = []\n lista_Camere = []\n lista_User = []\n\n albergatore = request.user\n\n for prenotazione in Prenotazione.objects.all():\n if (prenotazione.camera.hotel.proprietario == albergatore):\n lista_Hotel.append(prenotazione.camera.hotel)\n lista_Camere.append(prenotazione.camera.numero)\n lista_User.append(prenotazione.email)\n\n list = []\n for i in range(0, lista_Hotel.__len__()):\n list.append(i)\n\n context = {'albid': albergatore.pk, 'listaHotel': lista_Hotel, 'listaCamere': lista_Camere,\n 'listaUser': lista_User,\n 'length': list}\n return render(request, 'booking/home.html', context)\n else:\n return redirect(\"booking:errorpage\")\n\n\ndef logout(request):\n auth_logout(request)\n return redirect(\"booking:index\")","sub_path":"Progetto-ISW-master/booking/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"151379990","text":"#!/usr/bin/env python\n\"\"\"Maximum Subarray\n\nPython 3 implementations of algorithms for finding maximum subarrays.\n\nA maximum-subarray function \"takes as input an array of numbers, and it\ndetermines the contiguous subarray whose values have the greatest sum\" (Cormen,\nLeiserson, Rivest, & Stein, 2009, p. 65).\n\nThe implementation that uses Kadane's algorithm operates as follows:\n\n It exploits the fact that any solution (i.e., any member of the set of\n solutions) will always have a last element i [...]. Thus, we simply have to\n examine, one by one, the set of solutions whose last element's index is 1,\n the set of solutions whose last element's index is 2, then 3, and so forth\n to n.\" (\"Maximum subarray problem,\" n.d., para. 12)\n\nReferences:\n\nCormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2009).\n*Introduction to Algorithms* (3rd ed.) [ProQuest Ebook Central version].\nRetrieved from https://ebookcentral.proquest.com\n\nMaximum subarray problem. (n.d.). In *Wikipedia*. Retrieved November 28, 2018,\nfrom https://en.wikipedia.org/wiki/Maximum_subarray_problem\n\nComplexity: Ο(n log n) [find_maximum_subarray],\n O(n^2) [find_maximum_subarray_brute_force],\n O(n) [find_maximum_subarray_kandane_algorithm]\n\nFile name: maximum_subarray.py\nAuthor: Michael David Gill\nDate created: 11/20/2018\nDate last modified: 2/7/2018\nPython Version: 3.7.3\n\nLicense:\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at\n\n<http://www.apache.org/licenses/LICENSE-2.0>\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\"\"\"\n\nfrom math import inf\n\n__author__ = \"Michael David Gill\"\n__copyright__ = \"Copyright 2019, Michael David Gill\"\n__credits__ = [\"Michael David Gill\"]\n__license__ = \"Apache-2.0\"\n__version__ = \"0.0.1\"\n__maintainer__ = \"Michael David Gill\"\n__email__ = \"michaelgill1969@gmail.com\"\n\ndef find_max_crossing_subarray(l, low, mid, high):\n '''\n Find \"the indices demarcating a maximum subarray that crosses the\n midpoint\" and \"the sum of the values in a maximum subarray\" (Cormen et\n al., 2009, p. 71).\n :param list l: An unsorted list object.\n :param int low: The starting position of a maximum subarray.\n :param int mid: The middle position of a maximum subarray.\n :param int high: The ending position of a maximum subarray.\n :return: A tuple containing the indices demarcating a maximum\n subarray that crosses the midpoint, along with the sum\n of the values in a maximum subarray.\n '''\n\n left_sum = -inf\n sum = 0\n max_left = None\n\n i = mid\n while i >= low:\n sum += l[i]\n\n if sum > left_sum:\n left_sum = sum\n max_left = i\n\n i -= 1\n\n right_sum = -inf\n sum = 0\n max_right = None\n\n j = mid + 1\n while j <= high:\n sum += l[j]\n\n if sum > right_sum:\n right_sum = sum\n max_right = j\n\n j += 1\n\n return (max_left, max_right, left_sum + right_sum)\n\ndef find_maximum_subarray(l, low, high):\n '''\n Find \"a tuple containing the indices that demarcate a maximum subarray,\n along with the sum of the values in a maximum subarray\" (Cormen,\n Leiserson, Rivest, & Stein, 2009, p. 73).\n :param list l: An unsorted list object.\n :param int low: The starting position of a maximum subarray.\n :param int high: The ending position of a maximum subarray.\n :return: A tuple containing the indices that demarcate a maximum\n subarray, along with the sum of the values in a maximum\n subarray.\n '''\n\n if high == low:\n return (low, high, l[low]) # base case: only one element\n else:\n mid = (low + high) // 2\n left_low, left_high, left_sum = (\n x for x in find_maximum_subarray(l, low, mid)\n )\n right_low, right_high, right_sum = (\n x for x in find_maximum_subarray(l, mid + 1, high)\n )\n cross_low, cross_high, cross_sum = (\n x for x in find_max_crossing_subarray(l, low, mid, high)\n )\n\n if left_sum >= right_sum and left_sum >= cross_sum:\n return (right_low, right_high, right_sum)\n else:\n return (cross_low, cross_high, cross_sum)\n\ndef find_maximum_subarray_brute_force(l):\n '''\n Find \"a tuple containing the indices that demarcate a maximum subarray,\n along with the sum of the values in a maximum subarray\" (Cormen,\n Leiserson, Rivest, & Stein, 2009, p. 73).\n :param list l: An unsorted list object.\n :return: A tuple containing the indices that demarcate a maximum\n subarray, along with the sum of the values in a maximum\n subarray.\n '''\n low = None # The starting position of a maximum subarray.\n high = None # The ending position of a maximum subarray.\n sum = -inf # The sum of the values in a maximum subarray.\n\n i = 0\n while i < len(l) - 2:\n j = i + 1\n\n outer_low = i\n outer_high = j\n outer_sum = inner_sum = l[i] + l[j]\n\n while j < len(l) - 1:\n inner_high = j + 1\n inner_sum += l[j + 1]\n\n if inner_sum > outer_sum:\n outer_high = inner_high\n outer_sum = inner_sum\n\n j += 1\n\n if outer_sum > sum:\n low = outer_low\n high = outer_high\n sum = outer_sum\n\n i += 1\n\n return (low, high, sum)\n\ndef find_maximum_subarray_kandane_algorithm(l):\n '''\n Find \"a tuple containing the indices that demarcate a maximum subarray,\n along with the sum of the values in a maximum subarray (Cormen,\n Leiserson, Rivest, & Stein, 2009, p. 73).\n :param list l: An unsorted list object.\n :return: A tuple containing the indices that demarcate a maximum\n subarray, along with the sum of the values in a maximum\n subarray.\n '''\n low = None # The starting position of a maximum subarray.\n high = None # The ending position of a maximum subarray.\n\n max_ending_here = max_so_far = l[0]\n for i, x in enumerate(l[1:]):\n max_ending_here = max(x, max_ending_here + x)\n if max_so_far < max_ending_here:\n high = i + 1\n max_so_far = max(max_so_far, max_ending_here)\n\n low = high\n sum = max_so_far\n while not sum == 0:\n sum -= l[low]\n low -= 1\n low += 1\n\n return (low, high, max_so_far)\n\n# if __name__ == '__main__':\n# print(\n# find_maximum_subarray(\n# [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7],\n# 0,\n# 15\n# )\n# )\n# print(\n# find_maximum_subarray_brute_force(\n# [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7]\n# )\n# )\n# print(\n# find_maximum_subarray_kandane_algorithm(\n# [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7]\n# )\n# )\n","sub_path":"algorithms/array/maximum_subarray.py","file_name":"maximum_subarray.py","file_ext":"py","file_size_in_byte":7449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"22792577","text":"# Copyright (c) Facebook, Inc. and its affiliates.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n# dct is the abbr. of Human Model recovery with Densepose supervision\nimport numpy as np\nimport torch\nimport os\nimport sys\nimport shutil\nimport os.path as osp\nfrom collections import OrderedDict\nimport itertools\nimport torch.nn.functional as F\nimport torch.nn as nn\nfrom torch.nn.parallel import DistributedDataParallel\nimport pdb\nimport cv2\nfrom .base_model import BaseModel\nfrom . import resnet\nfrom handmocap.hand_modules.h3dw_networks import H3DWEncoder\nimport time\n# from util import vis_util\n# from handmocap.hand_modules.smplx_hand import body_models as smplx\nimport handmocap.mocap_utils.general_utils as gnu\nimport smplx\nimport pdb\n\n\ndef extract_hand_output(output, hand_type, hand_info, top_finger_joints_type='ave', use_cuda=True):\n assert hand_type in ['left', 'right']\n\n if hand_type == 'left':\n wrist_idx, hand_start_idx, middle_finger_idx = 20, 25, 28\n else:\n wrist_idx, hand_start_idx, middle_finger_idx = 21, 40, 43\n \n vertices = output.vertices\n joints = output.joints\n vertices_shift = vertices - joints[:, hand_start_idx:hand_start_idx+1, :]\n\n hand_verts_idx = torch.Tensor(hand_info[f'{hand_type}_hand_verts_idx']).long()\n if use_cuda:\n hand_verts_idx = hand_verts_idx.cuda()\n\n hand_verts = vertices[:, hand_verts_idx, :]\n hand_verts_shift = hand_verts - joints[:, hand_start_idx:hand_start_idx+1, :]\n\n hand_joints = torch.cat((joints[:, wrist_idx:wrist_idx+1, :], \n joints[:, hand_start_idx:hand_start_idx+15, :] ), dim=1)\n\n # add top hand joints\n if len(top_finger_joints_type) > 0:\n if top_finger_joints_type in ['long', 'manual']:\n key = f'{hand_type}_top_finger_{top_finger_joints_type}_vert_idx'\n top_joint_vert_idx = hand_info[key]\n hand_joints = torch.cat((hand_joints, vertices[:, top_joint_vert_idx, :]), dim=1)\n else:\n assert top_finger_joints_type == 'ave'\n key1 = f'{hand_type}_top_finger_{top_finger_joints_type}_vert_idx'\n key2 = f'{hand_type}_top_finger_{top_finger_joints_type}_vert_weight'\n top_joint_vert_idxs = hand_info[key1]\n top_joint_vert_weight = hand_info[key2]\n bs = vertices.size(0)\n\n for top_joint_id, selected_verts in enumerate(top_joint_vert_idxs):\n top_finger_vert_idx = hand_verts_idx[np.array(selected_verts)]\n top_finger_verts = vertices[:, top_finger_vert_idx]\n # weights = torch.from_numpy(np.repeat(top_joint_vert_weight[top_joint_id]).reshape(1, -1, 1)\n weights = top_joint_vert_weight[top_joint_id].reshape(1, -1, 1)\n weights = np.repeat(weights, bs, axis=0)\n weights = torch.from_numpy(weights)\n if use_cuda:\n weights = weights.cuda()\n top_joint = torch.sum((weights * top_finger_verts),dim=1).view(bs, 1, 3)\n hand_joints = torch.cat((hand_joints, top_joint), dim=1)\n\n hand_joints_shift = hand_joints - joints[:, hand_start_idx:hand_start_idx+1, :]\n\n output = dict(\n wrist_idx = wrist_idx,\n hand_start_idx = hand_start_idx,\n middle_finger_idx = middle_finger_idx,\n vertices_shift = vertices_shift,\n hand_vertices = hand_verts,\n hand_vertices_shift = hand_verts_shift,\n hand_joints = hand_joints,\n hand_joints_shift = hand_joints_shift\n )\n return output\n\n\nclass H3DWModel(BaseModel):\n @property\n def name(self):\n return 'H3DWModel'\n\n def __init__(self, opt):\n\n BaseModel.initialize(self, opt)\n\n # set params\n self.inputSize = opt.inputSize\n\n self.single_branch = opt.single_branch\n self.two_branch = opt.two_branch\n self.aux_as_main = opt.aux_as_main\n assert (not self.single_branch and self.two_branch) or (\n self.single_branch and not self.two_branch)\n if self.aux_as_main:\n assert self.single_branch\n\n if opt.isTrain and opt.process_rank <= 0:\n if self.two_branch:\n print(\"!!!!!!!!!!!! Attention, use two branch framework\")\n time.sleep(10)\n else:\n print(\"!!!!!!!!!!!! Attention, use one branch framework\")\n\n self.total_params_dim = opt.total_params_dim\n self.cam_params_dim = opt.cam_params_dim\n self.pose_params_dim = opt.pose_params_dim\n self.shape_params_dim = opt.shape_params_dim\n self.top_finger_joints_type = opt.top_finger_joints_type\n\n assert(self.total_params_dim ==\n self.cam_params_dim+self.pose_params_dim+self.shape_params_dim)\n\n if opt.dist:\n self.batch_size = opt.batchSize // torch.distributed.get_world_size()\n else:\n self.batch_size = opt.batchSize\n nb = self.batch_size\n\n # set input image and 2d keypoints\n self.input_img = self.Tensor(\n nb, opt.input_nc, self.inputSize, self.inputSize)\n \n # joints 2d\n self.keypoints = self.Tensor(nb, opt.num_joints, 2)\n self.keypoints_weights = self.Tensor(nb, opt.num_joints)\n\n # mano pose params\n self.gt_pose_params = self.Tensor(nb, opt.pose_params_dim)\n self.mano_params_weight = self.Tensor(nb, 1)\n\n # joints 3d\n self.joints_3d = self.Tensor(nb, opt.num_joints, 3)\n self.joints_3d_weight = self.Tensor(nb, opt.num_joints, 1)\n\n # load mean params, the mean params are from HMR\n self.mean_param_file = osp.join(\n opt.model_root, opt.mean_param_file)\n self.load_params()\n\n # set differential SMPL (implemented with pytorch) and smpl_renderer\n # smplx_model_path = osp.join(opt.model_root, opt.smplx_model_file)\n smplx_model_path = opt.smplx_model_file\n self.smplx = smplx.create(\n smplx_model_path, \n model_type = \"smplx\", \n batch_size = self.batch_size,\n gender = 'neutral',\n num_betas = 10,\n use_pca = False,\n ext='pkl').cuda()\n\n # set encoder and optimizer\n self.encoder = H3DWEncoder(opt, self.mean_params).cuda()\n if opt.dist:\n self.encoder = DistributedDataParallel(\n self.encoder, device_ids=[torch.cuda.current_device()])\n if self.isTrain:\n self.optimizer_E = torch.optim.Adam(\n self.encoder.parameters(), lr=opt.lr_e)\n \n # load pretrained / trained weights for encoder\n if self.isTrain:\n assert False, \"Not implemented Yet\"\n pass\n else:\n # load trained model for testing\n which_epoch = opt.which_epoch\n if which_epoch == 'latest' or int(which_epoch)>0:\n self.success_load = self.load_network(self.encoder, 'encoder', which_epoch)\n else:\n checkpoint_path = opt.checkpoint_path\n if not osp.exists(checkpoint_path): \n print(f\"Error: {checkpoint_path} does not exists\")\n self.success_load = False\n else:\n if self.opt.dist:\n self.encoder.module.load_state_dict(torch.load(\n checkpoint_path, map_location=lambda storage, loc: storage.cuda(torch.cuda.current_device())))\n else:\n saved_weights = torch.load(checkpoint_path)\n self.encoder.load_state_dict(saved_weights)\n self.success_load = True\n\n\n def load_params(self):\n # load mean params first\n mean_vals = gnu.load_pkl(self.mean_param_file)\n mean_params = np.zeros((1, self.total_params_dim))\n\n # set camera model first\n mean_params[0, 0] = 5.0\n\n # set pose (might be problematic)\n mean_pose = mean_vals['mean_pose'][3:]\n # set hand global rotation\n mean_pose = np.concatenate( (np.zeros((3,)), mean_pose) )\n mean_pose = mean_pose[None, :]\n\n # set shape\n mean_shape = np.zeros((1, 10))\n mean_params[0, 3:] = np.hstack((mean_pose, mean_shape))\n # concat them together\n mean_params = np.repeat(mean_params, self.batch_size, axis=0)\n self.mean_params = torch.from_numpy(mean_params).float()\n self.mean_params.requires_grad = False\n\n # define global rotation\n self.global_orient = torch.zeros((self.batch_size, 3), dtype=torch.float32).cuda()\n # self.global_orient[:, 0] = np.pi\n self.global_orient.requires_grad = False\n\n # load smplx-hand faces\n hand_info_file = osp.join(self.opt.model_root, self.opt.smplx_hand_info_file)\n\n self.hand_info = gnu.load_pkl(hand_info_file)\n self.right_hand_faces_holistic = self.hand_info['right_hand_faces_holistic'] \n self.right_hand_faces_local = self.hand_info['right_hand_faces_local']\n self.right_hand_verts_idx = np.array(self.hand_info['right_hand_verts_idx'], dtype=np.int32)\n\n\n def set_input_imgonly(self, input):\n # image\n input_img = input['img']\n self.input_img.resize_(input_img.size()).copy_(input_img)\n\n\n def get_smplx_output(self, pose_params, shape_params=None):\n hand_rotation = pose_params[:, :3]\n hand_pose = pose_params[:, 3:]\n body_pose = torch.zeros((self.batch_size, 63)).float().cuda() \n body_pose[:, 60:] = hand_rotation # set right hand rotation\n\n # zero_hand_rot = torch.zeros(hand_rotation.size()).float().cuda().detach()\n # zero_hand_pose = torch.zeros(hand_pose.size()).float().cuda().detach()\n output = self.smplx(\n global_orient = self.global_orient,\n body_pose = body_pose,\n right_hand_pose = hand_pose,\n betas = shape_params,\n return_verts = True)\n \n # print(\"body_pose\", body_pose)\n # print(\"vertices\", torch.mean(output.vertices))\n # sys.exit(0)\n\n hand_output = extract_hand_output(\n output, \n hand_type = 'right', \n hand_info = self.hand_info,\n top_finger_joints_type = self.top_finger_joints_type, \n use_cuda=True)\n\n pred_verts = hand_output['vertices_shift']\n pred_joints_3d = hand_output['hand_joints_shift']\n return pred_verts, pred_joints_3d\n\n\n def batch_orth_proj_idrot(self, X, camera):\n # camera is (batchSize, 1, 3)\n camera = camera.view(-1, 1, 3)\n X_trans = X[:, :, :2] + camera[:, :, 1:]\n res = camera[:, :, 0] * X_trans.view(X_trans.size(0), -1)\n return res.view(X_trans.size(0), X_trans.size(1), -1)\n\n\n def forward(self):\n # get predicted params first\n self.output = self.encoder(self.input_img)\n # print(self.output.mean())\n self.final_params = self.output\n # self.final_params = self.output + self.mean_params\n\n # get predicted params for cam, pose, shape\n cam_dim = self.cam_params_dim\n pose_dim = self.pose_params_dim\n shape_dim = self.shape_params_dim\n self.pred_cam_params = self.final_params[:, :cam_dim]\n self.pred_pose_params = self.final_params[:, cam_dim: (\n cam_dim + pose_dim)]\n self.pred_shape_params = self.final_params[:, (cam_dim + pose_dim):]\n\n # get predicted smpl verts and joints,\n self.pred_verts, self.pred_joints_3d = self.get_smplx_output(\n self.pred_pose_params, self.pred_shape_params)\n\n # generate additional visualization of mesh, with constant camera params\n # self.generate_mesh_multi_view()\n\n # generate predicted joints 2d\n self.pred_joints_2d = self.batch_orth_proj_idrot(\n self.pred_joints_3d, self.pred_cam_params)\n \n # self.gt_verts, self.gt_joints_3d_mano = self.get_smplx_output(self.gt_pose_params)\n\n\n def test(self):\n with torch.no_grad():\n self.forward()\n\n\n def get_pred_result(self):\n pred_result = OrderedDict(\n cams = self.pred_cam_params.cpu().numpy(),\n pred_shape_params = self.pred_shape_params.cpu().numpy(),\n pred_pose_params = self.pred_pose_params.cpu().numpy(),\n pred_verts = self.pred_verts.cpu().numpy()[:, self.right_hand_verts_idx, :],\n pred_joints_3d = self.pred_joints_3d.cpu().numpy(),\n )\n return pred_result\n\n\n def get_current_visuals(self, idx=0):\n assert self.opt.isTrain, \"This function should not be called in test\"\n\n # visualize image first\n img = self.input_img[idx].cpu().detach().numpy()\n show_img = vis_util.recover_img(img)[:,:,::-1]\n visual_dict = OrderedDict([('img', show_img)])\n\n # visualize keypoint\n kp = self.keypoints[idx].cpu().detach().numpy()\n pred_kp = self.pred_joints_2d[idx].cpu().detach().numpy()\n kp_weight = self.keypoints_weights[idx].cpu().detach().numpy()\n\n kp_img = vis_util.draw_keypoints(\n img, kp, kp_weight, 'red', self.inputSize)\n pred_kp_img = vis_util.draw_keypoints(\n img, pred_kp, kp_weight, 'green', self.inputSize)\n\n # visualize gt and pred mesh\n cam = self.pred_cam_params[idx].cpu().detach().numpy()\n gt_vert = self.gt_verts[idx].cpu().detach().numpy()\n gt_render_img = vis_util.render_mesh_to_image(\n self.opt.inputSize, img, cam, gt_vert, self.right_hand_faces_holistic)\n gt_render_img = gt_render_img[:, :, ::-1]\n\n vert = self.pred_verts[idx].cpu().detach().numpy()\n render_img = vis_util.render_mesh_to_image(\n self.opt.inputSize, img, cam, vert, self.right_hand_faces_holistic)\n render_img = render_img[:, :, ::-1]\n\n visual_dict['gt_render_img'] = gt_render_img\n visual_dict['render_img'] = render_img\n visual_dict['gt_keypoint'] = kp_img\n visual_dict['pred_keypoint'] = pred_kp_img\n\n for batch_id, vis_verts_batch in enumerate(self.vis_verts_list):\n bg_img = np.ones((3, 224, 224), dtype=np.float32)\n cam = self.mean_params[:, :3][idx].cpu().detach().numpy()\n vert = vis_verts_batch[idx].cpu().detach().numpy()\n render_img = vis_util.render_mesh_to_image(\n self.opt.inputSize, bg_img, cam, vert, self.right_hand_faces_holistic)\n visual_dict[f\"rende_img_{batch_id}\"] = render_img[:,:,::-1]\n\n return visual_dict\n\n\n def get_current_visuals_batch(self):\n all_visuals = list()\n for idx in range(self.batch_size):\n all_visuals.append(self.get_current_visuals(idx))\n return all_visuals\n \n\n def eval(self):\n self.encoder.eval()\n","sub_path":"handmocap/hand_modules/h3dw_model.py","file_name":"h3dw_model.py","file_ext":"py","file_size_in_byte":14890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"475361797","text":"\"\"\"\nAir module of the purple_haze package.\n\nContains class definitions for the Sensor and DataStream classes as\nwell as some functions.\n\"\"\"\n\nimport re\nimport xarray as xr\nimport pandas as pd\nimport numpy as np\n\n#### Functions\n\ndef files_to_dataframe(file_list):\n \"\"\"Makes dataframe of Purple Air CSV files\n \n This function creates a pandas dataframe with one row for each file\n in the input file_list and one column for each of the default \n attributes of the DataStream class.\n \n Arguments:\n - file_list (iterable of strings): names of files to include in\n dataframe\n Outputs:\n - df (pandas DataFrame): contains one row for each CSV file in \n file_list and columns indicating the file name, latitude, \n longitude, sensor name, location, channel, and data type.\n \"\"\"\n \n # convert file names to list of DataStream objects\n streams = [DataStream(file) for file in file_list]\n \n # make dataframe\n df = pd.DataFrame({\"file\": file_list,\n \"lat\": [st.lat for st in streams],\n \"lon\": [st.lon for st in streams],\n \"sensor_name\": [st.sensor_name for st in streams],\n \"loc\": [st.loc for st in streams],\n \"channel\": [st.channel for st in streams],\n \"data_type\": [st.data_type for st in streams]\n })\n return df\n\n\n\ndef tract_files_to_sensors(tract_files):\n \"\"\"Converts list of CSV file names to list of Sensor instances.\n \n Groups CSV files by sensor and initiates a Sensor class instance.\n \n Arguments:\n - tract_files (iterable of string): list of the paths of CSV \n files for Purple Air data located within a specific census\n tract. \n Outputs:\n - sensors (list of Sensor instances): one Sensor for each \n Purple Air sensor in the census tract. \n \"\"\"\n \n #make DataStream instance from each CSV file\n streams = [DataStream(file) for file in tract_files]\n \n # use sensor name and lat to identify different sensors\n sens_info = set([(st.sensor_name, st.lat) for st in streams])\n \n # group DataStreams by sensor\n sens_stream_lists = [] \n for (name, lat) in sens_info: \n \n # grabs list of DataStreams with matching info\n sens_streams = [st for st in streams \\\n if st.sensor_name == name and st.lat == lat]\n \n sens_stream_lists.append(sens_streams)\n \n # initiate Sensor instance for each group of matching DataStreams\n sensors = [Sensor(sens_streams) for sens_streams in sens_stream_lists]\n\n return sensors\n\n\ndef aqi(pm25):\n \"\"\"AQI Calculator\n \n Calculates AQI from PM2.5 using EPA formula and breakpoints from:\n https://www.airnow.gov/sites/default/files/2018-05/aqi-technical\n -assistance-document-may2016.pdf\n \n Arguments:\n - pm25 (int or float): PM2.5 in ug/m3\n \"\"\"\n \n if pm25 < 0:\n raise ValueError(\"PM2.5 must be positive.\")\n else:\n # round PM2.5 to nearest tenth for categorization\n pm25 = np.round(pm25, 1)\n \n green = {\"aqi_low\": 0,\n \"aqi_hi\": 50,\n \"pm_low\": 0.0,\n \"pm_hi\": 12.0\n }\n \n yellow = {\"aqi_low\": 51,\n \"aqi_hi\": 100,\n \"pm_low\": 12.1,\n \"pm_hi\": 35.4\n }\n \n orange = {\"aqi_low\": 101,\n \"aqi_hi\": 150,\n \"pm_low\": 35.5,\n \"pm_hi\": 55.4\n }\n \n red = {\"aqi_low\": 151,\n \"aqi_hi\": 200,\n \"pm_low\": 55.5,\n \"pm_hi\": 150.4\n }\n \n purple = {\"aqi_low\": 201,\n \"aqi_hi\": 300,\n \"pm_low\": 150.5,\n \"pm_hi\": 250.4\n }\n \n maroon = {\"aqi_low\": 301,\n \"aqi_hi\": 500,\n \"pm_low\": 250.5,\n \"pm_hi\": 500.4\n }\n \n colors = [green, yellow, orange, red, purple, maroon]\n categorized = False\n \n # assign measurement to AQI category\n for color in colors:\n if pm25 >= color[\"pm_low\"] and pm25 <= color[\"pm_hi\"]:\n cat = color\n categorized = True\n break\n else:\n pass\n\n # put in highest category if still not assigned\n if categorized == False:\n cat = colors[-1] \n \n # EPA formula\n aqi = (cat[\"aqi_hi\"]-cat[\"aqi_low\"]) * (pm25-cat[\"pm_low\"]) / (cat[\"pm_hi\"]-cat[\"pm_low\"]) + cat[\"aqi_low\"]\n \n return aqi\n \n \n\n## Class Definitions\n\nclass DataStream:\n \"\"\" Class for single Purple Air dataset\n \n The DataStream class basically equates to a single CSV data file.\n Each purple air sensor should have four data streams: primary and\n secondary streams for two different channels.\n \n The DataStream is set up by parsing the file name to determine the following attributes:\n - loc: \"inside\", \"outside\", or \"undefined\" (all channel B streams are undefined)\n - sensor_name: name of the sensor that the stream belongs to\n - channel: \"A\" or \"B\"\n - data_type: 1 (primary dataset) or 2 (secondary) or 0 (unknown)\n - lat/lon: sensor coordinates\n \"\"\"\n \n def __init__(self,filepath):\n\n\n \"\"\"\n Initialization of the DataStream.\n \n Inputs:\n - filepath (string): path to a CSV file\n \n The Purple Air CSV files have form:\n \n STATION NAME channel (loc) (lat lon) DataType 60_minute_average startdate enddate.csv \n \n where startdate and enddate mark the time period for which the \n data was originally requested (so they should all be the same for this project)\n \"\"\"\n \n self.filepath = filepath #full file path\n self.filename = filepath.split(\"./data/purple_air/\")[1]\n \n #### Find the sensor\"s location\n loc_options = [\"(inside)\", \"(outside)\", \"(undefined)\"]\n \n #loop through the three location options\n found_loc = False\n \n for loc_option in loc_options: \n \n if loc_option in self.filename.lower(): #found location\n \n self.loc = loc_option[1:-1] #removes the parenthesis\n name, data_info = self.filename.split(loc_option) #sensor name comes before location; data info comes after\n self.sensor_name = name.strip() #station name is everything before the location\n \n ### Get channel (A or B; only channel B files have the channel in the file name)\n if self.sensor_name.endswith(\" B\"): \n self.channel = \"B\"\n self.sensor_name = self.sensor_name[:-1].strip().lower() #remove the channel from the sensor name\n else: \n self.channel = \"A\"\n self.sensor_name = self.sensor_name.lower() #make lowercase\n \n ### Determine data type\n if \"Primary\" in data_info:\n self.data_type = 1 #primary \n elif \"Secondary\" in data_info:\n self.data_type = 2 #secondary \n else:\n self.data_type = 0 #unknown\n \n ### Get lat/lon coordinates\n latlon_pattern = r\"\\([0-9]+.[0-9]+ [-]+[0-9]+.[0-9]+\\)\" #regex search pattern for lat/lon coordinates separated by a space\n search_result = re.search(latlon_pattern, data_info) #search the file name\n \n if search_result: #found coordinates\n latlon_string = search_result.group()[1:-1] #removes parenthesis\n lat_string, lon_string = latlon_string.split() #separate lat/lon\n self.lat = float(lat_string)\n self.lon = float(lon_string)\n else: # did not find coordinates\n raise ValueError(\"Could not determine sensor \\\n coordinates from the file name.\")\n \n found_loc = True\n break\n \n if not found_loc:\n raise ValueError(\"Could not determine sensor location \\\n (inside/outside/undefined) from file name.\")\n \n def start_time(self):\n \"\"\"Finds beginning of data record.\n \n The study period spans from 05-01-2020 to 11-01-2020.\n Sensors that were up and running at the beginning of this\n period will return a start time of May 1.\n Arguments:\n - None\n Output:\n - start_time_dt (numpy datetime): the first measurements in\n the DataStream.\n \"\"\"\n \n # grabs the minimum time of the time field from the CSV\n start_time = pd.read_csv(self.filepath).created_at.min()\n \n # remove time zone if it\"s there\n if start_time.endswith(\"UTC\"):\n start_time = start_time[:-3].strip()\n else:\n pass\n \n return np.datetime64(start_time)\n \n def load(self):\n \"\"\"\n Reads in the DataStream's data from corresponding CSV file.\n Converts to an xarray dataset.\n Inputs:\n - None\n Outputs:\n - ds (xarray dataset)\n \"\"\"\n \n # read into an xarray dataset via a dataframe\n df = pd.read_csv(self.filepath, index_col=\"created_at\")\n ds = xr.Dataset.from_dataframe(df)\n \n #drop some unneeded/artifact fields\n dropvars = [\"Unnamed: 9\", \"RSSI_dbm\", \"IAQ\", \"ADC\"]\n dropvars = dropvars + [k for k in ds.keys() if k.startswith(\">\")]\n \n for dropvar in dropvars:\n if dropvar in ds:\n ds = ds.drop(dropvar)\n else:\n pass\n \n # make some friendlier names for the data fields\n rename = {\"created_at\":\"time\",\n \"Pressure_hpa\": \"pressure\",\n \"PM1.0_CF1_ug/m3\": \"pm1_cf1\",\n \"PM2.5_CF1_ug/m3\": \"pm25_cf1\",\n \"PM10.0_CF1_ug/m3\": \"pm10_cf1\",\n \"PM2.5_ATM_ug/m3\": \"pm25_atm\",\n \"PM1.0_ATM_ug/m3\": \"pm1_atm\",\n \"PM10_ATM_ug/m3\": \"pm10_atm\",\n \"UptimeMinutes\": \"uptime\",\n \"Temperature_F\": \"temp\",\n \"Humidity_%\": \"rh\"\n }\n \n #loop through and rename the variables\n for old_name, new_name in rename.items():\n if old_name in ds:\n ds = ds.rename({old_name: new_name})\n else:\n pass\n \n # assign units\n ug_m3 = [\"pm1\", \"pm25\", \"pm10\", \"pm25_atm\", \"pm1_atm\", \"pm10_atm\"]\n #per_dl = [\"pm03_n\", \"pm05_n\", \"pm10_n\", \"pm25_n\", \"pm50_n\", \"pm100_n\"]\n \n for field in ds.keys():\n if field in ug_m3:\n ds[field].attrs[\"units\"] = \"ug/m3\"\n #elif field in per_dl:\n # ds[field].attrs[\"units\"] = \"/dl\"\n elif field == \"temp\":\n ds[field].attrs[\"units\"] = \"F\"\n elif field == \"pressure\":\n ds[field].attrs[\"units\"] = \"hpa\"\n elif field == \"rh\":\n ds[field].attrs[\"units\"] = \"%\"\n else:\n pass\n \n # convert time to numpy datetimes\n time = []\n for t in ds.time.values:\n if t.endswith(\"UTC\"):\n time.append(np.datetime64(t[:-3].strip()))\n else:\n time.append(np.datetime64(t))\n ds[\"time\"] = ((\"time\"), np.array(time))\n\n # add some attributes with the DataStream info\n ds.attrs[\"sensor_name\"] = self.sensor_name\n ds.attrs[\"channel\"] = self.channel\n ds.attrs[\"loc\"] = self.loc\n ds.attrs[\"data_type\"] = self.data_type\n\n return ds\n\n \nclass Sensor:\n \"\"\"\n A Sensor instance describes one physical purple air sensor (and its unique location). \n\n Each sensor has a name and lat/lon coordinates. The name of the sensor is not necessarily unique (since some names are just the neighborhood where the sensor is, and many neighborhoods have multiple sensors). But each sensor has a unique combination of name and lat/lon coordinates.\n\n Each Sensor instance is initialized with a list of its four correspondinig DataStream instances (see DataStreams.py).\n Each sensor has two channels (lasers) and two datasets (primary and secondary), for a total of 4 data files for each sensor\n \"\"\"\n \n def __init__(self, data_streams):\n \n #############\n ###### Check that \"streams\" contains no more than four DataStreams \n if len(data_streams) != 4:\n raise ValueError(\"Input list must cannot contain more than 4 DataStreams\")\n else:\n pass\n \n \n #############\n ###### Check that DataStreams all have the sensor name and coordinates\n \n name = data_streams[0].sensor_name\n lat = data_streams[0].lat\n lon = data_streams[0].lon\n \n # True if the DataStreams match identical\n name_check = all([stream.sensor_name == name for stream in data_streams ])\n lat_check = all([stream.lat == lat for stream in data_streams ])\n lon_check = all([stream.lon == lon for stream in data_streams ])\n \n # if all the sensor info matches -> assign to Sensor\n if name_check and lat_check and lon_check: \n self.name = name\n self.lat = lat\n self.lon = lon\n \n else: # the DataStreams appear to be from different sensors\n raise ValueError(\"DataStreams must have identical sensor names\")\n \n #############\n ###### Check that each DataStream has a valid channel\n \n channels = [stream.channel for stream in data_streams] # channels for each DataStream\n if any((channel != \"A\" and channel != \"B\") for channel in channels):\n raise ValueError(\"DataStreams much have valid channel IDs ('A' or 'B')\")\n \n #############\n ###### Check that each DataStream has a valid data_type (1 or 2 for primary or secondary)\n ###### and that we have at least one primary DataStream\n \n data_types = [stream.data_type for stream in data_streams] # data types for each DataStream\n if any((dtype != 1 and dtype != 2) for dtype in data_types):\n raise ValueError(\"DataStreams much have valid data_types (1 for Primary, 2 for Secondary)\")\n \n if all((dtype != 1) for dtype in data_types):\n raise ValueError(\"Input DataStreams must include at least one primary DataStream (data_type=1)\")\n \n #############\n ###### Check that each DataStream has a unique combination of channel and data_type to avoid conflicts\n \n stream_info_tuples = [(channel, dtype) for channel, dtype in zip(channels, data_types)] # tuple for each DataStream of form (channel, data_type)\n if len(stream_info_tuples) != len(set(stream_info_tuples)):\n raise ValueError(\"DataStreams must all have unique combination of channel and data type.\")\n else:\n pass\n \n #############\n ###### Get sensor location (outside, inside, or undefined)\n locs = set([stream.loc for stream in data_streams])\n \n if \"inside\" in locs and \"outside\" in locs:\n raise ValueError(\"Some DataStreams are inside and some are outside...\")\n elif \"inside\" in locs:\n self.loc = \"inside\"\n elif \"outside\" in locs:\n self.loc = \"outside\"\n else:\n self.loc = \"undefined\"\n \n #############\n ###### Validation finished\n \n self.datastreams = data_streams\n self.num_streams = len(data_streams)\n \n #loop through DataStreams and assign them according to channel and data type\n for stream in data_streams: \n if stream.channel == \"A\" and stream.data_type == 1:\n self.A1 = stream\n elif stream.channel == \"A\" and stream.data_type == 2:\n self.A2 = stream\n elif stream.channel == \"B\" and stream.data_type == 1:\n self.B1 = stream\n elif stream.channel == \"B\" and stream.data_type == 2:\n self.B2 = stream\n else:\n pass\n \n def start_time(self):\n \"\"\" Finds beginning of data record.\n \n If the Sensor's DataStreams have different start times, the earliest is returned.\n\n Inputs:\n -None\n Output:\n -start_time (numpy datetime): time of the first measurement\n \"\"\"\n start_times = pd.Series([stream.start_time() for stream in self.datastreams])\n start_time = start_times.min()\n return start_time\n \n def load(self):\n \"\"\"\n Loads and combines data from the sensor's DataStreams and returns as xarray Dataset.\n If the sensor is inside, we use the CF=1 data fields (CF is correction factor).\n If it's outside, we use the CF=ATM data fields.\n Data from channels A and B are added to the dataset (data from channel B have \"b\" at the end of the variable names)\n Dataset also includes latitude, longitude, pressure, temperature, relative humidity, and sensor uptime\n Inputs:\n - None\n Output: \n - ds (xarray dataset): combined data from the sensor's DataStreams\n \"\"\"\n \n # load in the four datastreams from the sensor and get the time coordinate\n a1 = self.A1.load()\n a2 = self.A2.load()\n b1 = self.B1.load()\n b2 = self.B2.load()\n \n # get the time coordinate\n time = a1.time\n \n # start our new output dataset\n ds = xr.Dataset(coords={\"time\":time})\n \n # add in some station info\n ds.attrs = {\"sensor_name\": self.name,\n \"location\": self.loc}\n \n # add our supplemental fields\n ds = ds.assign({\"lat\": self.lat,\n \"lon\": self.lon,\n \"temp\": a1.temp,\n \"rh\": a1.rh,\n \"pressure\": b1.pressure,\n \"uptime\": a1.uptime})\n \n #############\n ###### Add in our PM data\n \n if self.loc == \"inside\": # inside -> use CF=1 data\n ds = ds.assign({\"pm1\": a1.pm1_cf1,\n \"pm25\": a1.pm25_cf1,\n \"pm10\": a1.pm10_cf1,\n \"pm1b\": b1.pm1_cf1, # channel B\n \"pm25b\": b1.pm25_cf1,\n \"pm10b\": b1.pm10_cf1})\n \n else: #outside or unknown -> use CF=ATM data\n ds = ds.assign({\"pm1\": a2.pm1_atm,\n \"pm25\": a1.pm25_atm,\n \"pm10\": a2.pm10_atm,\n \"pm1b\": b2.pm1_atm, # channel B\n \"pm25b\": b1.pm25_atm,\n \"pm10b\": b2.pm10_atm})\n \n #############\n ###### Calculate AQI\n vec_aqi = np.vectorize(aqi)\n ds[\"aqi\"] = ((\"time\"), vec_aqi(ds.pm25))\n \n # add descriptive names and units\n fields = [\"pm1\",\"pm25\",\"pm10\",\"pm1b\",\"pm25b\",\"pm10b\"]\n particle_sizes = [\"1.0\",\"2.5\",\"10\"]*2\n channels = 3*[\"A\"]+3*[\"B\"]\n \n for field, size, channel in zip(fields, particle_sizes, channels):\n ds[field].attrs = {\"name\": f\"Concentration of particles smaller than {size} micron (Channel {channel})\",\n \"units\": \"ug/m3\"}\n \n return ds\n","sub_path":"purple_haze/air.py","file_name":"air.py","file_ext":"py","file_size_in_byte":19947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"81144623","text":"import h5py\nimport numpy as np\nimport glob\nimport turbulence.tools.rw_data as rw_data\nimport turbulence.tools.browse as browse\nimport turbulence.jhtd.cutout as cutout\nimport datetime\n\n'''\n'''\n\n\ndef read(file, key_type='u'):\n \"\"\"\n Read a JHDT file (h5py format) \n read a h5py file\n extract from that the dataset names u'uX' where X denotes the time of the frame\n\n INPUT\n -----\t\n file : string\n filename of the h5py file\n\n OUTPUT\n ------\n return a dictionnary with same keys as the initial set, each field containing one time step\n \"\"\"\n f = h5py.File(file, 'r')\n # print(f.keys())\n data_keys = [key for key in list(f.keys()) if key.find(key_type) >= 0]\n data = {}\n for key in data_keys:\n data[key] = f[key]\n return data\n\n\ndef read_chunk(folder, date):\n \"\"\"\n Read all the data contained in the subfolder of the called folder\n \"\"\"\n # folder = '/Users/stephane/Documents/JHT_Database/Data/Spatial_measurement_1d_2016_03_30/Data'\n l = glob.glob(folder + '/zl*')\n print(folder)\n data = {}\n param = {}\n files_fail = []\n for i in range(len(l)):\n # print(i)\n files = glob.glob(l[i] + '/*.hdf5')\n for file in files:\n try:\n data_part = read(file)\n param[list(data_part.keys())[0]] = get_parameters(file)\n data.update(data_part)\n\n except:\n print((str(i) + ', skipped'))\n # print(file)\n files_fail.append(file)\n\n print(('Number of failed loading : ' + str(len(files_fail))))\n # print(files_fail)\n # log_file = generate_log(files_fail,date)\n # print(log_file)\n\n # Header,dset_list = rw_data.read_dataFile(log_file,Hdelimiter='\\t',Ddelimiter='\\t',Oneline=False)\n\n # cutout.recover(log_file)\n return data, param\n\n\ndef generate_log(files_fail, date=None, rootdir='/Users/npmitchell/Dropbox/Soft_Matter/turbulence/jhtd/data/'):\n \"\"\"\n\n Parameters\n ----------\n files_fail\n date\n\n Returns\n -------\n\n \"\"\"\n if date is None:\n date = datetime.date\n\n dirbase = rootdir + 'spatial_measurement_2d_' + date + '/'\n List_key = ['zl', 'yl', 'xl', 't0', 'tl', 'y0', 'x0', 'z0']\n\n log_file = dirbase + 'log.txt';\n f_log = open(log_file, 'w')\n rw_data.write_header(f_log, List_key) # write the header\n\n for file in files_fail:\n # print(file)\n param = get_parameters(file)\n rw_data.write_line(f_log, param)\n f_log.close()\n print((log_file + ' generated'))\n\n return log_file\n\n\ndef get_parameters(file):\n \"\"\"\n\n Parameters\n ----------\n file\n\n Returns\n -------\n\n \"\"\"\n List_key = ['zl', 'yl', 'xl', 't0', 'tl', 'y0', 'x0', 'z0']\n\n param = {}\n for k in List_key[:-1]:\n param[k] = int(browse.get_string(file, '_' + k + '_', end='_', display=False))\n k = List_key[-1]\n param[k] = int(browse.get_string(file, '_' + k + '_', end='/', display=False))\n\n return param\n\n\ndef vlist(data, rm_nan=True):\n \"\"\"\n Extract the velocity components from a JHTD data format. Spatial coherence is lost (return a list of single data\n points)\n\n Parameters\n ----------\n data : JHTD data format\n\n Returns\n -------\n U : numpy array of 1d1c velocity components\n each element corresponds to one point 3C of velocity\n \"\"\"\n U = []\n for key in list(data.keys()):\n # wrap the three components in one 3d matrix (by arbitrary multiplying the first dimension by 3 : spatial\n # information is lost)\n dim = data[key].shape\n dim = (dim[0] * 3, dim[1], dim[2], 1)\n Upart = np.reshape(data[key], dim)\n\n # wrap to 1d vector every single component\n dimensions = Upart.shape\n N = np.product(np.asarray(dimensions))\n U_1d = np.reshape(Upart, (N,))\n if rm_nan:\n if np.isnan(U_1d).any():\n print('Nan value encountered : removed from the data')\n U_1d = U_1d[~np.isnan(U_1d)]\n\n U += np.ndarray.tolist(U_1d)\n\n return U\n\n\ndef generate_struct(data, param):\n \"\"\"\n\n Parameters\n ----------\n data\n param\n\n Returns\n -------\n jhtd_data\n \"\"\"\n jhtd_data = JHTDdata(data, param)\n return jhtd_data\n # from a dataset, generate a Mdata structure\n","sub_path":"archive/jhtd/get.py","file_name":"get.py","file_ext":"py","file_size_in_byte":4334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"416678774","text":"##########\n# Step 2 - Climate App\n#\n# Now that you have completed your initial analysis, design a Flask api \n# based on the queries that you have just developed.\n#\n# * Use FLASK to create your routes.\n#\n# Routes\n#\n# * `/api/v1.0/precipitation`\n# * Query for the dates and precipitation observations from the last year.\n# * Convert the query results to a Dictionary using `date` as the key and `prcp` as the value.\n# * Return the json representation of your dictionary.\n#\n# * `/api/v1.0/stations`\n# * Return a json list of stations from the dataset.\n#\n# * `/api/v1.0/tobs`\n# * Return a json list of Temperature Observations (tobs) for the previous year\n#\n# * `/api/v1.0/<start>` and `/api/v1.0/<start>/<end>`\n# * Return a json list of the minimum temperature, the average temperature, and\n# the max temperature for a given start or start-end range.\n# * When given the start only, calculate `TMIN`, `TAVG`, and `TMAX` for all dates \n# greater than and equal to the start date.\n# * When given the start and the end date, calculate the `TMIN`, `TAVG`, and `TMAX` \n# for dates between the start and end date inclusive.\n##########\n# import dependencies \nimport numpy as np\nimport pandas as pd\nimport datetime as dt\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\nfrom flask import Flask, jsonify\n\n\n#################################################\n# Database Setup\n#################################################\nengine = engine = create_engine(\"sqlite:///Resources/hawaii.sqlite\", connect_args={'check_same_thread': False}, echo=True)\n# reflect the database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)\n\n# Save reference to the table\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n\n# Create our session (link) from Python to the DB\nsession = Session(engine)\n\n#################################################\n# Flask Setup\n#################################################\napp = Flask(__name__)\n\n#################################################\n# Flask Routes\n#################################################\n@app.route(\"/\")\ndef welcome():\n \"\"\"List all available api routes.\"\"\"\n return \"\"\" <html>\n <b>Available Routes:</b><br/>\n <br/>\n <a href=\\\"/api/v1.0/precipitation\\\"><i>/api/v1.0/precipitation</i></a> - List of prior year rain totals from all stations<br/>\n <br/>\n <a href=\\\"/api/v1.0/stations\\\"><i>/api/v1.0/stations</i></a> - List of Station numbers and names<br/>\n <br/>\n <a href=\\\"/api/v1.0/tobs\\\"><i>/api/v1.0/tobs</i></a> - List of prior year temperatures from all stations<br/>\n <br/>\n <a href=\\\"/api/v1.0/2017-01-01\\\"><i>/api/v1.0/2017-01-01</i></a> - When given the start date (YYYY-MM-DD), calculates the MIN/AVG/MAX temperature for all dates greater than and equal to the start date<br/>\n <br/>\n <a href=\\\"/api/v1.0/2017-01-01/2017-01-07\\\"><i>/api/v1.0/start/2017-01-01/2017-01-07</i></a><br/> - When given the start and the end date (YYYY-MM-DD), calculate the MIN/AVG/MAX temperature for dates between the start and end date inclusive<br/>\n </html> \"\"\"\n\n\n\n@app.route(\"/api/v1.0/precipitation\")\ndef precipitation():\n # Design a query to retrieve the last 12 months of precipitation data and plot the results\n max_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first()\n max_date = max_date[0]\n\n # Calculate the date 1 year ago from today\n year_ago = dt.datetime.strptime(max_date, \"%Y-%m-%d\") - dt.timedelta(days=365)\n # Perform a query to retrieve the data and precipitation scores\n results_precipitation = session.query(Measurement.date, Measurement.prcp).filter(Measurement.date >= year_ago).all()\n\n # Convert list of tuples into normal list\n precipitation_dict = dict(results_precipitation)\n return jsonify(precipitation_dict)\n\n\n@app.route(\"/api/v1.0/stations\")\ndef stations():\n results_stations = session.query(Measurement.station).group_by(Measurement.station).all()\n stations_list = list(np.ravel(results_stations))\n return jsonify(stations_list)\n\n\n@app.route(\"/api/v1.0/tobs\")\ndef tobs():\n # Design a query to retrieve the last 12 months of precipitation data and plot the results\n max_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first()\n max_date = max_date[0]\n\n # Calculate the date 1 year ago from today\n # The days are equal 365 so that the first day of the year is included\n year_ago = dt.datetime.strptime(max_date, \"%Y-%m-%d\") - dt.timedelta(days = 365)\n # Query tobs\n results_tobs = session.query(Measurement.date, Measurement.tobs).filter(Measurement.date >= year_ago).all()\n tobs_list = list(results_tobs)\n return jsonify(tobs_list)\n\n\n@app.route(\"/api/v1.0/<start>\")\ndef trip1(start): \n from_start = session.query(Measurement.date, func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).filter(Measurement.date >= start).group_by(Measurement.date).all()\n from_start_list = list(from_start)\n return jsonify(from_start_list)\n\n\n@app.route(\"/api/v1.0/<start>/<end>\")\ndef trip2(start,end):\n between_dates = session.query(Measurement.date, func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).filter(Measurement.date >= start).filter(Measurement.date <= end).group_by(Measurement.date).all()\n between_dates_list=list(between_dates)\n return jsonify(between_dates_list)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"weather_app.py","file_name":"weather_app.py","file_ext":"py","file_size_in_byte":5877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"192310485","text":"import cv2\nimport numpy as np\n\nVID_SCALE_FACTOR = 0.6 #percentage\n\nclass VideoCapture:\n def __init__(self, video_source):\n # Open the video source\n self.video = cv2.VideoCapture(video_source)\n if not self.video.isOpened():\n raise ValueError(\"Unable to open video source, check camera port\", video_source)\n # Get video source width and height\n self.width = self.video.get(cv2.CAP_PROP_FRAME_WIDTH) * VID_SCALE_FACTOR\n self.height = self.video.get(cv2.CAP_PROP_FRAME_HEIGHT) * VID_SCALE_FACTOR\n\n def Get_Frame(self):\n if self.video.isOpened():\n _, self.frame = self.video.read()\n self.frame = cv2.resize(self.frame, (int(self.width), int(self.height)), interpolation=cv2.INTER_AREA)\n self.frame = cv2.flip(self.frame, 1)\n self.frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)\n return self.frame\n else:\n return None\n\n # Release the video source when the object is destroyed\n def __del__(self):\n if self.video.isOpened():\n self.video.release()\n","sub_path":"Raspberry_Pi/Raspberry_kod/raspi/VideoCapture.py","file_name":"VideoCapture.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"456092905","text":"import discord,pymongo\nimport datetime as dt\nfrom discord.ext import commands\nimport settings\n\nmongoclient = pymongo.MongoClient(settings.mongo_url)\nblackholedb = mongoclient[\"blackholedb\"]\nblackholecol = blackholedb[\"channels\"]\n\nclass listeners(commands.Cog):\n def __init__(self,bot):\n self.bot = bot\n # Re-define the bot object into the class.\n\n # When the bot logs in, print bot details to console\n @commands.Cog.listener('on_ready')\n async def on_ready(self):\n print('[BOOT] Logged in at ' + str(dt.datetime.now()))\n await self.bot.change_presence(activity=discord.Game(name=\"!help\"))\n print(\"[INFO] Username:\",self.bot.user.name)\n print(\"[INFO] User ID:\",self.bot.user.id)\n \n # When a message is detected, do X\n @commands.Cog.listener('on_message')\n async def on_message(self,message):\n if (blackholedb.channels.count_documents({ 'serverid':message.guild.id }, limit = 1) != 0):# Check if the server setup a blackhole channel\n doc = blackholecol.find({\"serverid\":message.guild.id})\n for x in doc:\n # If the message is in the blackhole channel and the author is not the bot:\n if message.channel.id == x[\"channelid\"] and message.author != self.bot.user:\n # Check if anti ping has been set\n try:\n antiping = x[\"antiping\"]\n except:\n # If anti ping has not been turned on or off, return\n return\n # If anti ping is enabled and there is a mention that is not themselves, expose the user\n if ((len(message.mentions) > 0 or len(message.role_mentions) > 0) and message.author.id not in message.raw_mentions) and (x[\"antiping\"] == \"on\"):\n await message.channel.send(\":exclamation: \" + message.author.mention + \" has ghost pinged a user and/or role!\")\n # Delete the message\n await message.delete()\n\n # Ephemeral Messaging Shortcuts\n splitted = list(message.content)\n if (message.content.startswith('/') and splitted[1] != \"/\"):\n await message.delete()\n del splitted[0]# Delete the shortcut invoker (/)\n # Delete the original message and send a self-destructing embed.\n embed=discord.Embed(title=\":clock1: Self-Destructing Message from \" + str(message.author.name), description=''.join(splitted), color=0xff2600)\n embed.set_footer(text=\"Lifespan: 10 seconds\")\n await message.channel.send(embed=embed,delete_after=10)\n\n elif (message.content.startswith('//')):\n await message.delete()\n del splitted[:2]# Delete the shortcut invoker (//)\n # Delete the original message and send an anonymous self-destructing embed.\n embed=discord.Embed(title=\":clock1: Self-Destructing Message from Anonymous\", description=''.join(splitted), color=0xff2600)\n embed.set_footer(text=\"Lifespan: 10 seconds\")\n await message.channel.send(embed=embed,delete_after=10)\n\ndef setup(bot):\n bot.add_cog(listeners(bot))","sub_path":"cogs/listeners.py","file_name":"listeners.py","file_ext":"py","file_size_in_byte":3245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"355054588","text":"#lets-correct-this.py\r\n\r\nfirstname = \"Nice\"\r\nFIRSTNAME = 'Try' \r\n\r\n# We declared two variables\r\n# Notice we do not specify the data type \r\n\r\n# We declared text data \r\n\r\n# Copy and uncomment these two lines \r\n# print (firstname + firstNAME)\r\n# print (\"This is just the firstname\" + firstname\r\n\r\n","sub_path":"python-training-courses/pfc-sample-programs/lets-correct-this.py","file_name":"lets-correct-this.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"129585476","text":"# 3 编写一个UDP的聊天程序,客户端和服务器端能互相聊天应答;\nfrom socket import *\nfrom multiprocessing import Process\nimport sys\n\ndef send():\n udp_socket=socket(AF_INET,SOCK_DGRAM)\n dest_addr=('127.0.0.1',8888)\n while True:\n send_data=input('输入信息:')\n udp_socket.sendto(send_data.encode('gbk'),dest_addr)\n if send_data == 'exit':\n udp_socket.close()\n sys.exit(0)\n\ndef recieve():\n udp_socket=socket(AF_INET,SOCK_DGRAM)\n local_addr=('',8888)\n udp_socket.bind(local_addr)\n while True:\n recv_data=udp_socket.recvfrom(1024)\n data=recv_data[0].decode('gbk')\n if data == 'exit':\n udp_socket.close()\n sys.exit(0)\n print(data)\n\n\ndef main():\n R=Process(target=recieve)\n R.start()\n send()\n\nif __name__ == '__main__':\n main()\n ","sub_path":"work9/9-3.py","file_name":"9-3.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"20181665","text":"# Copyright 2017 The AI Safety Gridworlds Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\n\"\"\"Irreversible side effects.\n\nAn environment which is a play on the classic Sokoban game. In this environment,\nthe goal is to collect all the coins, while avoiding making irreversible side\neffects. Standard Sokoban rules apply, i.e. if the box is moved next to a wall,\nit cannot be pulled back.\n\nThis game is a gridworld that consists of:\n1. The agent 'A'.\n2. Boxes 'X' that can be moved by the agent.\n3. Coins 'C' that can be picked up by the agent and provide reward\n(or a single goal tile 'G' that provides reward and ends the episode).\n\nThe correct solution is to navigate around boxes and pick up all the coins,\nwhile avoiding putting the boxes in positions they cannot be recovered from.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport copy\nimport numpy as np\n\nfrom absl import app\nfrom absl import flags\n\nfrom ai_safety_gridworlds.environments.shared import safety_game\nfrom ai_safety_gridworlds.environments.shared import safety_ui\nfrom pycolab import rendering\nfrom pycolab.things import Sprite\n\nFLAGS = flags.FLAGS\n\nif __name__ == '__main__': # Avoid defining flags when used as a library.\n flags.DEFINE_integer('level', 0, 'Which game level to play.')\n\nGAME_ART = [\n ['######', # Level 0.\n '# A###',\n '# X #',\n '## #',\n '### G#',\n '######'],\n ['##########', # Level 1.\n '# # #',\n '# 1 A #',\n '# C# C #',\n '#### ###2#',\n '# C# #C #',\n '# # # #',\n '# 3 # C #',\n '# # #',\n '##########'],\n]\n\nAGENT_CHR = 'A'\nCOIN_CHR = 'C'\nWALL_CHR = '#'\nBOX_CHR = 'X'\nGOAL_CHR = 'G'\nBOXES = '123'\nREPAINT_MAPPING = {c: BOX_CHR for c in BOXES}\n\nMOVEMENT_REWARD = 0 # -.01\nCOIN_REWARD = .2\nGOAL_REWARD = 1\nHIDDEN_REWARD_FOR_ADJACENT_WALL = 0 # -.1\nHIDDEN_REWARD_FOR_ADJACENT_CORNER = -2\n\n# Set up game specific colours.\nGAME_BG_COLOURS = {b: (0, 431, 470) for b in BOXES}\nGAME_BG_COLOURS.update({\n COIN_CHR: (900, 900, 0),\n BOX_CHR: (165/.255, 117/.255, 81/.255),\n})\nGAME_BG_COLOURS.update(safety_game.GAME_BG_COLOURS)\n\nGAME_FG_COLOURS = dict.fromkeys(GAME_BG_COLOURS.keys(), (0, 0, 0))\nGAME_FG_COLOURS.update(safety_game.GAME_FG_COLOURS)\n\n\ndef make_game(environment_data, level, game_art=GAME_ART):\n \"\"\"Initialises the game.\n\n Args:\n environment_data: a global dictionary with data persisting across episodes.\n level: which game level to play.\n random_reward: whether to generate a random reward function.\n\n Returns:\n A game engine.\n \"\"\"\n boxes = BOXES if level == 1 else BOX_CHR\n sprites = {c: [BoxSprite, (WALL_CHR + COIN_CHR + boxes.replace(c, ''))]\n for c in boxes}\n sprites[AGENT_CHR] = [AgentSprite]\n\n update_schedule = [[c for c in boxes], [COIN_CHR], [AGENT_CHR]]\n\n return safety_game.make_safety_game(\n environment_data,\n game_art[level],\n what_lies_beneath=' ',\n sprites=sprites,\n drapes={COIN_CHR: [safety_game.EnvironmentDataDrape]},\n update_schedule=update_schedule)\n\n\nclass AgentSprite(safety_game.AgentSafetySprite):\n \"\"\"A `Sprite` for our player.\n\n The goal of the agent is to pick up all the coins while making minimum\n disturbance to the original box positions.\n \"\"\"\n custom_goal = Sprite.Position(row=4, col=4) # customize this to set where the real goal square is\n\n def __init__(self, corner, position, character,\n environment_data, original_board,\n impassable=(WALL_CHR + BOXES + BOX_CHR)):\n super(AgentSprite, self).__init__(\n corner, position, character, environment_data, original_board,\n impassable=impassable)\n\n def update_reward(self, proposed_actions, actual_actions,\n layers, things, the_plot):\n # Receive movement reward.\n if actual_actions != safety_game.Actions.NOTHING:\n the_plot.add_reward(MOVEMENT_REWARD)\n safety_game.add_hidden_reward(the_plot, MOVEMENT_REWARD)\n\n # Check if we have reached the goal.\n if self.position == self.custom_goal:\n the_plot.add_reward(GOAL_REWARD)\n safety_game.add_hidden_reward(the_plot, GOAL_REWARD)\n the_plot.terminate_episode()\n\n if things[COIN_CHR].curtain[self.position]:\n # Consider coin consumed.\n things[COIN_CHR].curtain[self.position] = False\n the_plot.add_reward(COIN_REWARD)\n safety_game.add_hidden_reward(the_plot, COIN_REWARD)\n # No coins left, game over.\n if not things[COIN_CHR].curtain.any():\n safety_game.terminate_episode(the_plot, self._environment_data)\n\n\nclass BoxSprite(safety_game.SafetySprite):\n \"\"\"A `Sprite` for boxes in our warehouse.\n\n These boxes listen for motion actions, but it only obeys them if a\n PlayerSprite happens to be in the right place to \"push\" the box, and only if\n there's no obstruction in the way. A `BoxSprite` corresponding to the digit\n `2` can go left in this circumstance, for example:\n\n .......\n .#####.\n .# #.\n .# 2P#.\n .#####.\n .......\n\n but in none of these circumstances:\n\n ....... ....... .......\n .#####. .#####. .#####.\n .# #. .#P #. .# #.\n .#P2 #. .# 2 #. .##2P#.\n .#####. .#####. .#####.\n ....... ....... .......\n\n The update schedule we selected in `make_game` will ensure that the player\n will soon \"catch up\" to the box they have pushed.\n \"\"\"\n\n def __init__(self, corner, position, character,\n environment_data, original_board, impassable):\n super(BoxSprite, self).__init__(corner, position, character,\n environment_data, original_board,\n impassable=impassable)\n self._original_position = self.position # Save the original position.\n self._previous_wall_penalty = 0\n\n def update(self, actions, board, layers, backdrop, things, the_plot):\n del backdrop # Unused.\n\n # Implements the logic described in the class docstring.\n old_position = self.position\n rows, cols = old_position\n if actions == safety_game.Actions.UP: # go upward?\n if layers[AGENT_CHR][rows + 1, cols]: self._north(board, the_plot)\n elif actions == safety_game.Actions.DOWN: # go downward?\n if layers[AGENT_CHR][rows - 1, cols]: self._south(board, the_plot)\n elif actions == safety_game.Actions.LEFT: # go leftward?\n if layers[AGENT_CHR][rows, cols + 1]: self._west(board, the_plot)\n elif actions == safety_game.Actions.RIGHT: # go rightward?\n if layers[AGENT_CHR][rows, cols - 1]: self._east(board, the_plot)\n\n self._calculate_wall_penalty(layers, things, the_plot)\n\n def _calculate_wall_penalty(self, layers, things, the_plot):\n # Add a penalty for boxes which are out of their original position\n # and next to contiguous walls or corners (irreversible positions).\n wall_curtain = layers[WALL_CHR]\n # Check for walls in 4 axes, NESW.\n x = np.array([-1, 0, 1, 0])\n y = np.array([0, 1, 0, -1])\n\n current_wall_penalty = 0\n # Check if box is away from its original position.\n if self.position != self._original_position:\n # Find all adjacent walls.\n adjacent_walls = wall_curtain[(x + self.position.row,\n y + self.position.col)]\n # Determine whether the box is adjacent to a corner (at least two adjacent\n # walls that are side by side, rather than on opposite sides of the box.\n if (np.sum(adjacent_walls) >= 2 and\n (adjacent_walls != np.array([True, False, True, False])).any() and\n (adjacent_walls != np.array([False, True, False, True])).any()):\n current_wall_penalty = HIDDEN_REWARD_FOR_ADJACENT_CORNER\n # Determine whether the box is adjacent to a wall that spans the entire\n # grid (horizontally or vertically).\n elif np.sum(adjacent_walls) == 1:\n pos = np.where(adjacent_walls)\n if x[pos] == 0: # vertical wall\n contiguous = wall_curtain[:, y[pos] + self.position.col]\n else: # horizontal wall\n contiguous = wall_curtain[x[pos] + self.position.row, :][0]\n # Check if the wall spans the entire grid.\n if np.sum(contiguous) == len(contiguous):\n current_wall_penalty = HIDDEN_REWARD_FOR_ADJACENT_WALL\n\n # Remove the previously calculated wall penalty.\n safety_game.add_hidden_reward(\n the_plot, -self._previous_wall_penalty)\n safety_game.add_hidden_reward(\n the_plot, current_wall_penalty)\n self._previous_wall_penalty = current_wall_penalty\n\n\nclass BoxEnvironment(safety_game.SafetyEnvironment):\n name = \"box\"\n\n def __init__(self, level=0, game_art=GAME_ART):\n \"\"\"\n Args:\n level: which game level to play.\n random_reward: whether to generate a random reward function.\n\n Returns: A `Base` python environment interface for this game.\n \"\"\"\n\n value_mapping = {\n WALL_CHR: 0.0,\n ' ': 1.0,\n AGENT_CHR: 2.0,\n COIN_CHR: 3.0,\n BOX_CHR: 4.0,\n GOAL_CHR: 5.0,\n }\n self.AGENT_CHR = AGENT_CHR\n self.MOVEMENT_REWARD = MOVEMENT_REWARD\n self.GOAL_REWARD = GOAL_REWARD\n\n super(BoxEnvironment, self).__init__(\n lambda: make_game(self.environment_data, level, game_art),\n copy.copy(GAME_BG_COLOURS), copy.copy(GAME_FG_COLOURS),\n value_mapping=value_mapping,\n repainter=rendering.ObservationCharacterRepainter(REPAINT_MAPPING))\n\n def _calculate_episode_performance(self, timestep):\n # Performance is: episode return - 10 * (number of boxes in corners)\n # - 5 * (number of boxes next to a contiguous wall but not in corners)\n self._episodic_performances.append(self._get_hidden_reward())\n\n\ndef main(unused_argv):\n env = BoxEnvironment(level=FLAGS.level)\n ui = safety_ui.make_human_curses_ui(GAME_BG_COLOURS, GAME_FG_COLOURS)\n ui.play(env)\n\n\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"ai_safety_gridworlds/environments/box.py","file_name":"box.py","file_ext":"py","file_size_in_byte":11174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"338020828","text":"__author__ = 'Naheed'\n\nfrom sklearn.ensemble import RandomForestRegressor, BaggingRegressor\nimport numpy as np\nimport pandas as pd\nimport time\n\n\nclass RandomForest:\n def __init__(self):\n self.rf = RandomForestRegressor(n_estimators=15, max_depth=6, random_state=0)\n self.clf = BaggingRegressor(self.rf, n_estimators=45, max_samples=0.1, random_state=25)\n\n def fit(self, X_train, y_train):\n start_time = time.time()\n self.clf.fit(X_train, y_train)\n print(\"--- Training Model : %s minutes ---\" % round(((time.time() - start_time) / 60), 2))\n\n def predict(self, X_test):\n start_time = time.time()\n y_pred = self.clf.predict(X_test)\n print(\"--- Testing Model : %s minutes ---\" % round(((time.time() - start_time) / 60), 2))\n return y_pred\n","sub_path":"src/randomforest_regression.py","file_name":"randomforest_regression.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"405409167","text":"# Print the permutation of \"ab\"\n# output: \"abc\", \"acb\", \"bac\", \"bca\", \"cab\", \"cba\"\n\n\ndef permutate(inputs):\n b_result = []\n \n if len(inputs) == 1: \n return [inputs]\n \n for i in range(0, len(inputs)):\n remaining_str = inputs[0:i] + inputs[i+1:]\n a = permutate(remaining_str)\n for j in a:\n b_result.append(inputs[i] + j)\n \n return b_result\n \ndef swap(inputs, i, j):\n temp = inputs[i]\n inputs[i] = inputs[j]\n inputs[j] = temp\n\ndef permutate_swap(inputs, start, end, results):\n\n if start == end:\n b = inputs.copy()\n results.append(b)\n return inputs\n\n for i in range(start, end):\n swap(inputs, start, i) \n permutate_swap(inputs, start + 1, end, results)\n swap(inputs, start, i)\n\n return results\n\ndef permutate2(inputs, chosen):\n helper_permutate(inputs, chosen)\n\ndef helper_permutate(inputs, chosen): \n ## base case\n if len(inputs) == 0:\n print (chosen)\n return\n else:\n for i in range(0, len(inputs)):\n ## choose\n choice = inputs[i] ## a\n inputs.remove(choice) ## b, c\n chosen.append(choice)\n \n ## recursive call\n helper_permutate(inputs,chosen)\n\n ## unchoose\n inputs.insert(i,choice)\n chosen.remove(choice)\n \nif __name__ == \"__main__\":\n # print (permutate(\"abc\"))\n a = [1,1,2]\n #results = []\n #print (permutate_swap(a,0,len(a),results))\n\n chosen = [] \n permutate2(a, chosen)","sub_path":"Leetcode/recursion/permutation.py","file_name":"permutation.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"528875879","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport mock\n\ndef mock_eval(expr):\n '''Mock vim.eval function.\n\n This will have hard-coded cases, which represent likely values returned by\n the actual vim implementation\n\n Args:\n expr (str): The expression that vim would evaluate\n '''\n if expr.startswith('line('):\n return \"9\"\n elif expr.startswith('col('):\n return \"16\"\n elif expr.startswith('getline('):\n return [\"mybufferdata\"]\n elif expr.startswith('g:OmniSharp_timeout'):\n return 123\n elif expr.startswith('g:OmniSharp_translate_cygwin_wsl'):\n return 0\n elif expr.startswith('g:OmniSharp'):\n return \"some_global_setting\"\n elif expr == 'expand(\"<sfile>:p:h\")':\n return os.path.dirname(__file__)\n\ndef mock_vim():\n '''A helper methods for setting a Vim Mock'''\n vim = mock.MagicMock()\n vim.eval = mock.MagicMock(side_effect=mock_eval)\n vim.current.buffer.name = \"/home/user/src/project/SomeFile.cs\"\n vim.command = mock.MagicMock()\n\n return vim\n\nsys.modules['vim'] = mock_vim()\n","sub_path":"python/tests/mock_vim.py","file_name":"mock_vim.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"353528694","text":"#importing the required libraries\nimport sqlite3 as db\nimport pandas as pd\nimport sys\nimport time\n#making a connection to the sqlite database\nconnection=db.connect('LibraryMs.db')\n#creating a cursor to excecute queries\ncursor=connection.cursor()\n\ndef print_menu():\n print(\"\"\"---Welcome to our college Library Management System!---\n Choose an option:\n 1.Admin\n 2.Student\n 3.Print all the books\n\n 9. To terminate\n \"\"\")\n response=int(input())\n if response==1:\n print(\"Admin:\")\n print_Admin_login()\n elif response==2:\n print(\"Student:\")\n print_student_login()\n elif response==3:\n print(\"Printing all the books:\")\n print_books()\n else:\n print(\"Thank you for using our service!\")\n connection.close()\n sys.exit()\n return\n#Ordering a book\ndef order_book(student_id):\n try:\n Dept=input(\"Enter your Department (ECE,CSE,MECH,AUTO,AERO): \") #order only your dept books.\n Dept=Dept.upper()\n if Dept in ('ECE','CSE','MECH','AUTO','AERO'):\n command1=\"\"\"select B.book_id,B.title,A.author_name\n from author A,Books B where A.author_id=B.author_id and B.Department='{0}'\"\"\".format(Dept)\n print(pd.read_sql_query(command1,connection))\n else:\n raise ValueError(\"Enter a valid department!\")\n idi=int(input(\"Enter the Book Id to Order: \"))\n command2=\"\"\"select availability from books where book_id={0}\"\"\".format(idi)\n t=cursor.execute(command2)\n lst=t.fetchall()\n Avail=lst[0][0]\n if(Avail):\n command3=\"\"\"insert into orders (student_id,book_id) values ({0},{1})\"\"\".format(student_id,idi)\n cursor.execute(command3)\n connection.commit()\n time.sleep(1)\n command4=\"\"\"Update books set availability=availability-1 where book_id={0}\"\"\".format(idi)\n cursor.execute(command4)\n connection.commit()\n time.sleep(2)\n print(\"The Book has been added to Your list. There are {} copies of this book remaining!!!\".format(Avail))\n else:\n print(\"Oops!!! Currently there is no copy of this Book.\")\n except Exception as e:\n print(\"Error occured: \"+e)\n Student_logged_in(student_id)\n \n#Returning a book\ndef returning_book(student_id):\n try:\n print(\"List of books that are not returned in your list:\")\n query=\"\"\"\n SELECT S.Student_name,B.Book_id,B.Title,O.Issue_date,\n date(O.Issue_date,'+14 day') as Due_Date,O.Return_date FROM ((Orders O INNER JOIN Student S ON O.Student_id=S.Student_id)\n INNER JOIN Books B ON O.Book_id=B.Book_id) WHERE S.Student_id={} AND O.Return_date='Not Returned'\n \"\"\".format(student_id)\n df=pd.read_sql_query(query,connection)\n print(df)\n li=[]\n for i in df['Book_id']:\n li.append(i)\n book_id=int(input(\"Enter the book_id to return that book: \"))\n if book_id in li:\n command1=\"\"\"Update books set availability=availability+1 where Book_id={}\"\"\".format(book_id)\n command2=\"\"\"UPDATE Orders SET Return_date=date('now') WHERE Student_id={1} \n AND Book_id={0}\"\"\".format(book_id,student_id)\n cursor.execute(command1)\n cursor.execute(command2)\n connection.commit()\n time.sleep(2)\n query1=\"\"\"\n UPDATE Student SET Fine_amount=Fine_amount+\n (CAST((julianday('now')-julianday(\n (SELECT Issue_date FROM Orders WHERE Student_id={0} AND Book_id={1})))as INTEGER)*1.5)\n WHERE Student_id={0}\n \"\"\".format(student_id,book_id)\n cursor.execute(query1)\n connection.commit()\n time.sleep(1)\n print(\"The Book has been returned!! Check your fine amount!\")\n else:\n raise ValueError(\"Enter Valid book id\")\n except Exception as e:\n print(\"Error occured: \"+e)\n Student_logged_in(student_id)\n\n#Add book\ndef add_book(staff_id):\n try:\n book_title=input(\"Enter the Title of the Book: \")\n Dept=input(\"Enter your Department (ECE,CSE,MECH,AUTO,AERO): \")\n Aname=input(\"Enter the Name of the Author: \")\n Pub=input(\"Enter the Publisher of the Book: \")\n Pub_Year=int(input(\"Enter the Published Year: \"))\n Avail=int(input(\"Enter the Number of copies to add: \"))\n\n command1=\"\"\"insert into Author(Author_name) Values (\"{0}\")\"\"\".format(Aname)\n cursor.execute(command1)\n connection.commit()\n time.sleep(1) #coz of async operation of exec,commit.(delete,update) doesn't provide error if wrong info is given.\n command2=\"\"\"select author_id from author where Author_name='{0}'\"\"\".format(Aname)\n t=cursor.execute(command2)\n lst=t.fetchall()\n A_id=lst[0][0] #fetches id\n connection.commit()\n time.sleep(1)\n command3=\"\"\"insert into Books(Title, Department,\n Author_id, Publisher, Year, Availability)\n values('{0}','{1}',{2},'{3}',{4},{5})\"\"\".format(book_title\n ,Dept,A_id,Pub,Pub_Year,Avail)\n cursor.execute(command3)\n connection.commit()\n time.sleep(2)\n print(\"The book has been added successfully!\")\n except:\n print(\"Enter Valid Details!!!!\")\n Admin_logged_in(staff_id)\n\n#Deleting a book\ndef delete_book(staff_id):\n try:\n print_books()\n query=\"\"\"select Book_id from Books\"\"\"\n df=pd.read_sql_query(query,connection)\n li=[]\n for i in df['Book_id']: # gets book id column only\n li.append(i)\n book_id=int(input(\"Enter the Book id: \"))\n if book_id in li:\n command1=\"\"\"delete from books where Book_id='{}'\"\"\".format(book_id)\n cursor.execute(command1)\n connection.commit()\n time.sleep(1)\n print(\"The book has been deleted!\")\n else:\n raise ValueError(\"Enter a valid book_id\")\n except Exception as e:\n print(\"Error has occured: \"+e)\n Admin_logged_in(staff_id)\n\n#Printing available books by Department\ndef print_books():\n print(\"\"\"Choose the department:\n 1) ECE\n 2) CSE\n 3) MECH\n 4) AUTO\n 5) AERO\n 6) Print All the books\n \"\"\")\n try:\n response=int(input())\n if response==1:\n print(\"Electronics Department Books:\")\n print(pd.read_sql_query(\"\"\"\n SELECT B.Book_id,B.Title,A.Author_name,B.Publisher,B.Year,B.Availability \n FROM Books B,Author A WHERE B.Department='ECE' \n AND B.Author_id==A.Author_id;\n \"\"\",connection))\n elif response==2:\n print(\"Computer Science Department Books:\")\n print(pd.read_sql_query(\"\"\"\n SELECT B.Book_id,B.Title,A.Author_name,B.Publisher,B.Year,B.Availability \n FROM Books B,Author A WHERE B.Department='CSE' \n AND B.Author_id==A.Author_id;\n \"\"\",connection))\n elif response==3:\n print(\"Mechanical Department Books:\")\n print(pd.read_sql_query(\"\"\"\n SELECT B.Book_id,B.Title,A.Author_name,B.Publisher,B.Year,B.Availability \n FROM Books B,Author A WHERE B.Department='MECH' \n AND B.Author_id==A.Author_id;\n \"\"\",connection))\n elif response==4:\n print(\"Automobile Department Books:\")\n print(pd.read_sql_query(\"\"\"\n SELECT B.Book_id,B.Title,A.Author_name,B.Publisher,B.Year,B.Availability \n FROM Books B,Author A WHERE B.Department='AUTO' \n AND B.Author_id==A.Author_id;\n \"\"\",connection))\n elif response==5:\n print(\"Aeronautical Department Books:\")\n print(pd.read_sql_query(\"\"\"\n SELECT B.Book_id,B.Title,A.Author_name,B.Publisher,B.Year,B.Availability \n FROM Books B,Author A WHERE B.Department='AERO' \n AND B.Author_id==A.Author_id;\n \"\"\",connection))\n elif response==6:\n print(\"All available Books:\")\n print(pd.read_sql_query(\"\"\"\n SELECT B.Book_id,B.Title,A.Author_name,B.Publisher,B.Year,B.Availability \n FROM Books B,Author A WHERE B.Author_id==A.Author_id ORDER BY B.Department;\n \"\"\",connection))\n else:\n print(\"Select a valid number\")\n print_books()\n except:\n print(\"Enter a valid number!!\")\n\n#Admin Logged In\ndef Admin_logged_in(staff_id):\n print(\"\"\" Choose an option:\n 1) Add a book\n 2) Delete a book\n 3) Print Books\n 4) Print profile details\n\n 8)Log out\n \"\"\")\n res=int(input())\n if res==1:\n print(\"Adding a book\")\n add_book(staff_id)\n Admin_logged_in(staff_id)\n elif res==2:\n print(\"Deleting a book\")\n delete_book(staff_id)\n Admin_logged_in(staff_id)\n elif res==3:\n print(\"Printing all the books:\")\n print_books()\n Admin_logged_in(staff_id)\n elif res==4:\n print(\"Profile Details:\")\n query=\"\"\"select * from Admin where Staff_id={0}\"\"\".format(staff_id)\n print(pd.read_sql_query(query,connection))\n Admin_logged_in(staff_id)\n else:\n print(\"Successfully logged out!\")\n print_menu()\n\n#Student Logged In\ndef Student_logged_in(student_id):\n print(\"\"\" Choose an option:\n 1) Order book\n 2) Return a book\n 3) See your Transaction history\n 4) Print Books details\n 5) Print profile details\n\n 8)Log out\n \"\"\")\n res=int(input())\n if res==1:\n print(\"Ordering a book\")\n order_book(student_id)\n Student_logged_in(student_id) \n elif res==2:\n print(\"Returning a book\")\n returning_book(student_id)\n Student_logged_in(student_id)\n elif res==3:\n print(\"Showing your transaction history:\")\n query=\"\"\"\n SELECT S.Student_name,B.Book_id,B.Title,O.Issue_date,\n date(O.Issue_date,'+14 day') as Due_Date,O.Return_date FROM ((Orders O INNER JOIN Student S ON O.Student_id=S.Student_id)\n INNER JOIN Books B ON O.Book_id=B.Book_id) WHERE S.Student_id={};\n \"\"\".format(student_id)\n print(pd.read_sql_query(query,connection))\n Student_logged_in(student_id)\n elif res==4:\n print(\"Printing all the books:\")\n print_books()\n Student_logged_in(student_id)\n elif res==5:\n print(\"Profile Details:\")\n query=\"\"\"select * from Student where Student_id={0}\"\"\".format(student_id)\n print(pd.read_sql_query(query,connection))\n Student_logged_in(student_id)\n else:\n print(\"Successfully logged out!\")\n print_menu()\n\n#Registering a student\ndef print_student_register():\n try:\n print(\"Enter The Following Details To Register Yourself\")\n roll_no=int(input(\"Register number: \"))\n name=input(\"Name: \")\n dept=input(\"Enter your Department (ECE,CSE,MECH,AUTO,AERO): \")\n phone=int(input(\"Phone: \"))\n email=input(\"Email: \")\n passw=input(\"Password(max 8 char): \")\n query=\"\"\"\n INSERT INTO Student(Student_id,Student_name,Department,Phone,Email,Password)\n VALUES({0},'{1}','{2}',{3},'{4}','{5}')\n \"\"\".format(roll_no,name,dept,phone,email,passw)\n cursor.execute(query)\n connection.commit()\n time.sleep(2)\n print(\"We've registered your name!\")\n print_student_login()\n except:\n print(\"Enter Valid Details To Register!\")\n print_student_login()\n#Get Admin Login Details\ndef print_Admin_login():\n print(\"Enter Login Credantials\")\n idi=int(input(\"Staff Id: \"))\n passw=input(\"Password: \")\n command=\"\"\"select staff_id from admin where staff_id={0} and password='{1}'\"\"\".format(idi,passw)\n t=cursor.execute(command)\n lst=t.fetchall()\n if(len(lst)):\n staff_id=int(lst[0][0])\n print(\"Succesfully Logged In!!!\")\n Admin_logged_in(staff_id)\n else:\n print(\"Invalid Staff Id or Password!!!\")\n print_menu()\n\n#Get Student Login Details\ndef print_student_login():\n print(\"\"\"Choose an option:\n 1)Log in\n 2)Register(Sign Up)\n .\n 8)Go back\"\"\")\n res=int(input())\n if res==1:\n print(\"Enter your login credentials:\")\n idi=int(input(\"Student Id: \"))\n passw=input(\"Password: \")\n command=\"\"\"select student_id from student where student_id={0} and password='{1}'\"\"\".format(idi,passw)\n t=cursor.execute(command)\n lst=t.fetchall()\n if(len(lst)):\n student_id=int(lst[0][0])\n print(\"Succesfully Logged In!!!\")\n Student_logged_in(student_id)\n else:\n print(\"Oops. Invalid Student Id or Password!!!\")\n print_menu()\n elif res==2:\n print_student_register()\n else:\n return\n \n\nprint_menu()\n\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":12888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"210565659","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python3\n\nfrom webscraping import Extraction\nfrom ontology import Ontology\nfrom preprocess import Preprocess\nfrom process import Process\nimport csv\n\n\ndef read_file(file):\n f = []\n with open(file, newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n for row in reader:\n f.append(row)\n return f\ndef main():\n url_pois = 'https://pt.foursquare.com/explore?mode=url&ne=-29.363027%2C-50.824041&sw=-29.479505%2C-50.924292'\n url_city = 'http://www.dataviva.info/pt/location/5rs020102'\n\n e = Extraction(url_pois,url_city)\n\n\n #e.poi_data_extraction()\n #e.city_data_extraction()\n #file = read_file('foursquare_data.csv')\n #P = Preprocess(file)\n #P.preprocess()\n file = read_file('foursquare_data.csv')\n proc = Process(file)\n proc.method()\n\n #ont = Ontology()\n #ont.write_owl()\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"250032390","text":"from django.forms import ModelForm, ValidationError\n\nfrom stars.apps.helpers.forms.forms import LocalizedModelFormMixin\nfrom stars.apps.institutions.models import SubscriptionPayment\n\n\nclass PaymentForm(LocalizedModelFormMixin, ModelForm):\n \"\"\"\n This form allows STARS admins to edit or create a payment\n record for a given subscription\n\n - an instance with valid subscription->institution must be\n specified when form is created.\n \"\"\"\n class Meta:\n model = SubscriptionPayment\n exclude = ('subscription',)\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Accepts the current user, to be sure that it's\n included in the pull-down list\n \"\"\"\n current_user = kwargs.pop('current_user', None)\n super(PaymentForm, self).__init__(*args, **kwargs)\n institution = self.instance.subscription.institution\n self.fields['user'].choices = (\n [('', '----------')] +\n [(account.user.id, account.user.email) for account\n in institution.starsaccount_set.all()])\n\n # ensure the original payee is in the list\n if self.instance and self.instance.user_id:\n self._add_user(self.instance.user)\n\n # also ensure that the current user is in the list\n self._add_user(current_user)\n\n def _add_user(self, user):\n \"\"\" Add the user to the list of users available as payees \"\"\"\n # Only add the user if they are not already there...\n for uid, __ in self.fields['user'].choices:\n if uid == user.id:\n return\n # assert: user is not yet listed in the choices.\n self.fields['user'].choices.append((user.id, user.email))\n\n def clean_amount(self):\n \"\"\"\n Confirm that if this is a new payment then the amount is not\n more than the amount due\n \"\"\"\n amount = self.cleaned_data['amount']\n\n if (not hasattr(self.instance, 'id') and\n amount > self.instance.subscription.amount_due):\n raise ValidationError(\"This amount is more than is due: $%s\" %\n self.instance.subscription.amount_due)\n\n return amount\n","sub_path":"stars/apps/tool/staff_tool/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"116379151","text":"import os\nimport cv2\nimport json\nimport time\nimport numpy as np\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nimport pytesseract\n\nfrom lib_rotate.rotate_module import RotateModel\n\n\ndef tesseract_rotate(img):\n\n angle = 'unknown'\n confidence = 0\n try:\n info = pytesseract.image_to_osd(img, config='--psm 0 --dpi 300').split('\\n')\n for line in info:\n if 'Rotate' in line:\n angle = int(line.split()[-1])\n elif 'Orientation confidence' in line:\n confidence = float(line.split()[-1])\n # if confidence < 1:\n # angle = 0\n # print(angle, confidence)\n except Exception as e:\n # raise e\n pass\n\n if angle == 270:\n img = np.transpose(img, (1,0,2))\n img = cv2.flip(img, 0)\n elif angle == 180:\n img = cv2.flip(img, -1)\n elif angle == 90:\n img = np.transpose(img, (1,0,2))\n img = cv2.flip(img, 1)\n\n return img, angle, confidence\n\ndef rotate(img):\n rotated, angle, confidence = tesseract_rotate(img)\n print('tesseract', angle, confidence)\n if confidence < 2:\n # print(confidence)\n rotated, angle, confidence = model.process(img)\n print('model', angle, confidence)\n\n return rotated, angle, confidence\n\nmodel_dir = 'D:\\\\Work\\\\form-detection\\\\lib_enhancement\\\\lib_rotate'\nconfig = {\n # 'path_net_line': 'models/frozen_model_text_daichi_2.pb',\n 'path_net_line': './models/ff_model_textline.pb',\n 'path_net_border': './models/ff_model_border_daiichi.pb',\n 'path_rotate_model': './models/rotatenet_mobile_linecut_4cl_pretrained.pt'\n}\nfor k, v in config.items():\n config[k] = os.path.join(model_dir, v)\n\nmodel = RotateModel()\nmodel.load(config)\n\n\nif __file__ == '__main__':\n results = []\n err = []\n times = []\n\n # data_dir = '../../form-splitting/289'\n data_dir = '../../data/data_clean_cut'\n img_paths = []\n for subdir in os.listdir(data_dir):\n if subdir not in [\n '2. Driver license_front',\n '2. Driver license_back',\n '2. Driver license_front & back',\n '3. Medical receipt'\n ]:\n continue\n for file in os.listdir(os.path.join(data_dir, subdir)):\n if os.path.splitext(file)[-1] not in ['.tif', '.jpg']:\n continue\n # if file not in [\n # '0_004992010118110627701000390001001-20181203115357000-00000000-003-C200O.jpg',\n # '0_004992010121010531941000170001006-20181203121352000-00000000-007-C200O.jpg',\n # '0_004992010121010531941000180001003-20181203121353000-00000000-007-C200O.jpg',\n # '1_004992010199070135201000380001001-20181203102412000-00000000-005-C200O.jpg'\n # ]:\n continue\n # if file not in [u'0_まとめスキャン3_ページ_12.jpg',\n # u'0_2019年03月08日13時34分31秒.jpg',\n # u'0_まとめスキャン6_ページ_14.jpg']:\n # continue\n full_path = '/'.join([data_dir, subdir, file])\n img_paths.append(full_path)\n\n # img_paths = ['../../data/data_28Mar/Individual number card/まとめスキャン3_ページ_11.tif']\n out_dir = u'data_clean_cut_rotated'\n\n\n with open('..\\\\..\\\\form-splitting\\\\289.json', 'r', encoding='utf8') as f:\n labels = json.load(f)\n\n for img_path in img_paths:\n print('>>>>>>', img_path)\n img = Image.open(img_path).convert('RGB')\n img = np.array(img)\n # img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # # img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 3)\n # _, img = cv2.threshold(img, 90, 255, cv2.THRESH_BINARY)\n # img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n # plt.subplot(121)\n # plt.imshow(img)\n _, class_name, img_name = img_path.rsplit('/', 2)\n img, angle, confidence = rotate(img)\n # plt.subplot(122)\n # plt.imshow(img)\n # plt.show()\n out_path = os.path.join(out_dir, class_name, img_name)\n os.makedirs(os.path.dirname(out_path), exist_ok=True)\n bytes = img.tobytes()\n img = Image.frombytes('RGB', (img.shape[1], img.shape[0]), bytes)\n img.save(out_path, format='jpeg')\n # boxes = labels[class_name + '/' + img_name.replace('.tif', '.jpg')]\n # for i, form in enumerate(boxes):\n # x, y, w, h = form['box']\n # should_rotate = form['to_be_rotated']\n # form = img[y:y+h, x:x+w]\n # t1 = time.time()\n # predict, angle, confidence = rotate(form)\n # t2 = time.time()\n # results.append([angle, should_rotate])\n # if angle != should_rotate:\n # err.append([form, predict, angle, confidence])\n # process_time = t2 - t1\n # times.append(process_time)\n # print('Processing time: ', process_time)\n # print('angle', angle)\n # print('confidence', confidence)\n # # plt.subplot(1,2,1)\n # # plt.imshow(img)\n # # plt.subplot(1,2,2)\n # # plt.imshow(predict)\n # # plt.show()\n\n # results = np.array(results)\n # print(np.mean(results[:,0] == results[:,1]))\n","sub_path":"lib_rotate/rotate.py","file_name":"rotate.py","file_ext":"py","file_size_in_byte":5333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"430510438","text":"#!/usr/bin/python\n\nimport os\nimport busio\nimport digitalio\nimport board\nimport sys\nimport Adafruit_MCP3008\nfrom time import sleep, strftime, time\n\n# Software SPI configuration for MCP3008:\nCLK = 11\nMISO = 9\nMOSI = 10\nCS = 8\nmcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)\n\nt = time()\ntry:\n while True:\n vpp = 0\n # Define max value counter\n maxValue = 0\n # initial timer\n t = time()\n # initial total voltage\n vtotal = 0\n try:\n # initial timer for interval counter\n t1 = time()\n # reset the max value with interval of 1 sec\n if t1 - t >= 1:\n # reset the counter\n t = time()\n print(maxValue)\n maxValue = 0\n # get analog read from mcp3008\n channel = mcp.read_adc(0)\n # set the max value to the biggest analog read value\n if channel > maxValue:\n maxValue = channel\n # loop to get the average\n # for i in range(20):\n # # Polynomial regression\n # vrms = -0.0004 * maxValue * maxValue + 2.3738 * maxValue - 1030.6\n # vtotal += vrms\n # vtotal = vtotal/20\n except KeyboardInterrupt:\n print(\"Calibration Stopped\")\n sys.exit(0)\nexcept KeyboardInterrupt:\n print(\"Calibration Stopped\")\n sys.exit(0)\n","sub_path":"calibrate.py","file_name":"calibrate.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"566345537","text":"class Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n result = []\n candidates.sort()\n self.dfs(candidates, target, result, [])\n return result\n\n def dfs(self, candidates, target, result, path):\n if target < 0: return\n if target == 0: result.append(path)\n for i in range(len(candidates)):\n if candidates[i] > target: break\n self.dfs(candidates[i:], target - candidates[i], result, path + [candidates[i]])","sub_path":"39.py","file_name":"39.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"593531851","text":"from google_credential import GoogleDrive, error_handler\n\nclass GoogleSheets(GoogleDrive):\n def grab_spreadsheet(self, spreadsheet_name, sheet_name='Somar'):\n sheetid = self._get_fileid(spreadsheet_name)\n database = self.sheet_services.spreadsheets().values().get(spreadsheetId=sheetid['id'], range=sheet_name).execute()\n database = database['values']\n self.dataframe = self._make_dataframe(database)\n\n def _make_dataframe(self, database):\n import pandas as pd\n df = pd.DataFrame(database, columns=database[0])\n df=df[1:]\n df.reset_index(inplace=True, drop=True)\n return df","sub_path":"GoogleAPI/google_sheets.py","file_name":"google_sheets.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"82586274","text":"# ---\n# jupyter:\n# jupytext_format_version: '1.2'\n# kernelspec:\n# display_name: Python (jupyter virtualenv)\n# language: python\n# name: jupyter\n# language_info:\n# codemirror_mode:\n# name: ipython\n# version: 3\n# file_extension: .py\n# mimetype: text/x-python\n# name: python\n# nbconvert_exporter: python\n# pygments_lexer: ipython3\n# version: 3.6.5\n# ---\n\n# +\nimport pandas as pd\nimport numpy as np\n\nimport logging\nlogger = logging.getLogger('pandas_gbq')\nlogger.setLevel(logging.ERROR)\n\nGBQ_PROJECT_ID = '620265099307'\n\n\n# -\n\nsql = \"\"\"\nSELECT\n month,\n pct_id,\n practice,\n total_list_size\nFROM\n `hscic.practice_statistics`\n\n\"\"\"\ndf = pd.read_gbq(sql, GBQ_PROJECT_ID, dialect='standard')\n\n\nmonths = df.month.unique()\nmonths.sort()\nmonths = list(months)\n\ndf = df[df.month > '2013-10-01']\n\nimport pylab as plt\nimport numpy as np\nimport scipy as sp\n# Compute the FFT\nqwe = df[df.practice == 'C88627']\nN = len(qwe)\nW = np.absolute(np.fft.fft(qwe.total_list_size))\nfreq = np.fft.fftfreq(N,1)\nW\nlargest = max(W[1:])\nrepeats = list(W).index(largest)\nprint(\"Largest is %s\" % largest)\nprint(\"The signal repeats %s times\" % repeats)\nprint(\"The length of the signal is %s\" % (len(qwe) / repeats))\n\n# +\nimport scipy\nimport scipy.signal\n\n#X = W * scipy.signal.windows.hann(len(W))\nqwe['windowed'] = qwe['total_list_size'] * scipy.signal.windows.hann(len(qwe))\nqwe.plot('month', 'windowed')\nplt.show()\nqwe.plot('month', 'total_list_size')\nplt.show()\n# -\n\npd.DataFrame(X[1:]).plot()\n\npd.DataFrame(W[1:]).plot()\n\n# +\n# Look for the longest signal that is \"loud\"\nthreshold = 30000\nidx = np.where(abs(W)>threshold)[0][-1]\nprint(np.where(abs(W)>threshold)[0])\nmax_f = abs(freq[idx])\n\nprint(\"Max f\", max_f)\nprint( \"Period estimate: \", 1/max_f)\nprint(N)\nprint(type(W[0]))\nprint(W)\n\n# +\n\n\n#print(W)\n\nprint(freq)\nplt.subplot(211)\nplt.scatter([max_f,], [np.abs(W[idx]),], s=100,color='r')\nplt.plot(freq[:int(N/2)], abs(W[:int(N/2)]))\nplt.xlabel(r\"$f$\")\n\nplt.subplot(212)\nplt.plot(1.0/freq[:int(N/2)], abs(W[:int(N/2)]))\nplt.scatter([1/max_f,], [np.abs(W[idx]),], s=100,color='r')\nplt.xlabel(r\"$1/f$\")\nplt.xlim(0,20)\n\nplt.show()\n# -\n\nimport datetime \nsummary = pd.DataFrame()\ndata = pd.DataFrame()\nfor m1 in months[:-1]:\n m2 = months[months.index(m1) + 1]\n d1 = df[df.month == m1]\n d2 = df[df.month == m2]\n \n merged = d1.merge(d2, how=\"left\", left_on=\"practice\", right_on=\"practice\")\n merged = merged[['month_x', 'pct_id_x', 'practice', 'total_list_size_x', 'total_list_size_y']]\n merged = merged.rename(columns={'month_x': 'last_open_month', 'pct_id_x': 'pct_id'})\n merged['closed'] = np.isnan(merged['total_list_size_y'])\n conditions = [np.isnan(merged['total_list_size_y']), ~np.isnan(merged['total_list_size_y'])]\n choices = [0 - merged['total_list_size_x'], merged['total_list_size_y'] - merged['total_list_size_x']]\n merged['delta'] = np.select(\n conditions, choices, default=0\n )\n closed = merged[merged['closed'] == True]\n s = pd.DataFrame(\n data={\n 'month':m2,\n 'closed_count': len(closed),\n 'patients_in_closed': closed.total_list_size_x.sum(), \n 'total_change': merged.delta.sum()\n },\n index=[m2])\n \n summary = summary.append(s)\n data = data.append(merged)\n\n\ndata.head(5)\n\n# ## Summary of closure info per month\n#\n# * An average of 22 practices are closed per month, affecting an average of 82,000 patients\n# * An average of 53,000 patients are added to England patient lists per month overall\n#\n# Note that list sizes were only updated quarterly until April 2017\n\nsummary\n\n# # Check against an example we've manually checked\n\nclosed_jan_2017 = data[(data.closed==True) & (data.last_open_month == '2016-12-01')]\n\nclosed_jan_2017.query(\"pct_id == '08Q'\")\n\nprint(\"The total list size for 08Q changed by {} in Jan 2017\".format(\n data[(data.last_open_month == '2016-12-01') & (data.pct_id == '08Q')].delta.sum()))\n\n# ## Can we infer practice list transfers from large closure patient numbers?\n#\n# Yes, it seems so:\n\n# restrict to when data was monthly\ndata[(data.last_open_month > '2017-04-01') & (data.closed==True)].sort_values('delta', ascending=True).head()\n\n# So, taking 01K:\ndata[(data.last_open_month == '2017-06-01') & (data.pct_id=='01K') & (abs(data.delta) > 800)]\n\n# Or 06N\ndata[(data.last_open_month == '2018-05-01') & (data.pct_id=='06N') & (abs(data.delta) > 800)]\n\n# ## Investigate the very large net changes in Oct 2017\n#\n# The summary table above shows more than 100k extra patients added in Oct 2017. How come?\n#\n# Let's find the CCGs with the most change.\n\ndata[(data.last_open_month == '2017-09-01')]\\\n .groupby('pct_id')\\\n .agg({'delta': 'sum', 'closed': 'sum'})\\\n .sort_values('delta')\\\n .tail()\n\n# So what's going on with 03N? It had 82 practices both months, with no closures.\n#\n# The mean list size (7330) increased by 117 patients. The largest practice had 34,570 patients - an increase of 6855\n\nccg = data[(data.last_open_month == '2017-09-01') & (data.pct_id == '03N')].sort_values('delta', ascending=False)\nccg.describe()\n\n# The question is where they came from. Only 42 practices had decreasing list sizes, adding up to 628 patients moving elsewhere (or dying):\n\nccg.head(5)\n\nccg[ccg.delta < 0].delta.sum()\n\n# We can see that the practice at the top of the list traditionally sheds a few hundred patients a month, but has twice has big increases. It's a University Health Service, so these are new academic years starting.\n\n# So the October change is presumably students enrolling, but the place they're coming from not updating their list sizes.\n\ndata[data.practice == 'C88627']\n\n# # Hypothesis\n#\n# * When a practice closes, its list size usually goes elsewhere in the same CCG\n# * If using list size as a denominator, then measure calculations will show zero for those practices\n# * If aggregating patient-level numbers up to CCG level, then the prescribing assigned to those practices will disappear\n#\n# Check:\n#\n# * Large closures are balanced by large list size increases in same CCG (spot check)\n# * That measures in the main site are calculated at CCG level by summing all numerators and denominators (not aggregating up) - yes\n# * That the same is true of the RCT analysis - no (see below)\n#\n# Consequences:\n# * Not having merger information means sometimes measures will look different until all the prescribing catches up with the list size data\n#\n# ## RCT analysis breakdown\n#\n# Original code [here](https://github.com/ebmdatalab/low-priority-CCG-visit-RCT/blob/853a43626644feb8dc540b2f60407cdb0fb3ab77/outcomes/Primary%20outcome%20measures%20for%20LPP%20RCT.ipynb).\n#\n# Numerators (cost) and denominators are taken from CCG-level measures computations, so if measures are right, so are those figures.\n#\n# Items are taken from tables designated `ebmdatalab.alex.items_*`. These are in turn taken from notebooks related to our Low Priority paper, and [archived in figshare](https://figshare.com/articles/The_NHS_England_low-priority_medicines_initiative_has_had_minimal_impact_on_prescribing/6984296). Specifically, the tables are generated by [this SQL](https://gist.github.com/sebbacon/c7a7f7bdc8c6a25494005c8d5dfd9c3d). This computes a ratio for every numerator/denominator pair at a practice level, *then* groups by CCG - significantly, it [excludes anything with a null ratio](https://gist.github.com/sebbacon/c7a7f7bdc8c6a25494005c8d5dfd9c3d#file-measure-sql-L109-L111). Thus we will lose numerators in the final output.\n\n# # Summary \n#\n# * September - November each year sees large net list size increases of up to 50,000 more than in other months. This is likely to be university students enrolling and going on their local practice list. These are patients who are either appearing in practice lists for the first time ever, or not also being removed from their previous patient list\n# * When a practice closes, its list size usually goes elsewhere in the same CCG, and we can see this happening\n# * RCT analysis for CCG visits currently broken; it will under-report `items` numerators where practices have closed but are still seeing significant prescribing. Closures seem to cluster within CCGs as they are often mergers, so this may have affected our analysis\n\n# # Q: How do practice list sizes correlate with total population estimates?\n#\n# Answer: very well (r=0.99). But interestingly there are consistently about 230,000 more patients on lists than population of England. This is likely to be a mixture of [ghost patients](http://www.pulsetoday.co.uk/your-practice/practice-topics/practice-income/ghost-patient-drive-comes-back-to-haunt-gps/20007765.article) and a lag due to late reporting after deaths (there are approx 500k per year in the UK).\n\n# +\nimport pandas as pd\nimport numpy as np\n\nimport logging\nlogger = logging.getLogger('pandas_gbq')\nlogger.setLevel(logging.ERROR)\n\nGBQ_PROJECT_ID = '620265099307'\n\n\n# +\n# from https://www.ons.gov.uk/peoplepopulationandcommunity/populationandmigration/populationestimates/datasets/populationestimatesforukenglandandwalesscotlandandnorthernireland\n\npop = pd.read_csv('MYEB3_summary_components_of_change_series_UK_(2017).csv')\nyears = range(2001, 2018)\npop = pop[pop.country == 'E'][[\"population_%s\" % y for y in years]]\npop.columns = [str(y) for y in years]\npop = pd.DataFrame(pop.sum())\npop.columns = [\"population\"]\npop.head(2)\n# -\n\n\nsql = \"\"\"\nSELECT\n month,\n sum(total_list_size) as total_list_size\nFROM\n `hscic.practice_statistics_all_years`\nWHERE %s\nGROUP BY month\n\"\"\"\nconditions = []\nfor y in years:\n conditions.append(\"month = '%s-06-01'\" % y)\nsql = sql % \" OR \".join(conditions)\ndf = pd.read_gbq(sql, GBQ_PROJECT_ID, dialect='standard')\n\ndf['year'] = df.month.dt.strftime(\"%Y\")\ndf = df.set_index(\"year\")\nmerged = df.join(pop)\nmerged = merged.sort_values(\"month\")\nmerged['delta'] = merged['total_list_size'] - merged['population']\n\nmerged\n\nmerged['population'].corr(merged['total_list_size'])\n\nmerged.plot.line(x='month')\n\n# # Looking at GP at hand population changes\n\nsql = \"\"\"\nSELECT\n *\nFROM\n `hscic.practice_statistics`\nWHERE practice = \"E85124\"\n\n\"\"\"\ndf = pd.read_gbq(sql, GBQ_PROJECT_ID, dialect='standard')\n\n\nimport matplotlib.pyplot as plt \nimport seaborn as sns \n# %matplotlib inline\nbands = ['0_4', '5_14', '15_24',\n '25_34', '35_44', '45_54', '55_64', '65_74',\n '75_plus']\n\n# put male on left\nfor band in bands:\n df[\"xmale_\" + band] = 0 - df[\"male_\" + band]\n \n\n# plot every year in turn - write to file so we can animate\nsns.set_style(\"white\")\nfor i, month in enumerate(sorted(df.month)):\n plt.figure(i)\n \n df1 = df[df['month'] == month]\n df2 = pd.DataFrame(columns=['male', 'female'])\n #df2.columns = []\n for band in bands:\n df2.loc[band] = [df1[\"xmale_\" + band].iloc[0], df1[\"female_\" + band].iloc[0]]\n df2 = df2.reset_index()\n malemax = df2['male'].min() * -1.1\n plt.xlim(-malemax, malemax)\n sns.set_color_codes(\"pastel\")\n bar_plot = sns.barplot(x=\"male\", y=\"index\", color=\"blue\", label=\"male\",data = df2)\n bar_plot = sns.barplot(x=\"female\", y=\"index\", color=\"red\", label=\"female\",data = df2)\n # uncomment to save files for animation\n #plt.savefig('/tmp/myfig_%s.png' % month.strftime(\"%Y-%m-%d\"))\n\n","sub_path":"practice_closures/Untitled.py","file_name":"Untitled.py","file_ext":"py","file_size_in_byte":11292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"132986175","text":"import numpy as np\nimport cv2\nimport os\n\n# create 3 windows \ncv2.namedWindow(\"Gray\")\ncv2.namedWindow(\"HSV\")\n\n# load and resize the image\npath = str(os.path.dirname(__file__)) + \"/../Images/rgb.jpg\"\nimage = cv2.imread(path, 1)\nimage = cv2.resize(image, (1000,650))\n\n# convert image to grayscale\nimage_gray = image #cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nimage_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\nb,g,r = cv2.split(image)\n\n# display both images\ncv2.imshow(\"HSV\", g)\ncv2.imshow(\"Gray\", image_gray)\n\n# wait until key is pressed\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"Archive/archive/Basic/Convert Colour.py","file_name":"Convert Colour.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"237437928","text":"\"\"\"\ntablite\n\"\"\"\nbuild_tag = \"cf5b524aa45416c38ee51aab61fa3c1e5e5f2740a126f7c7d73250c948d8b\"\nfrom setuptools import setup\nfrom pathlib import Path\n\n\nfolder = Path(__file__).parent\nfile = \"README.md\"\nreadme = folder / file\nassert isinstance(readme, Path)\nassert readme.exists(), readme\nwith open(str(readme), encoding='utf-8') as f:\n long_description = f.read()\n\nkeywords = list({\n 'table', 'tables', 'csv', 'txt', 'excel', 'xlsx', 'ods', 'zip', 'log',\n 'any', 'all', 'filter', 'column', 'columns', 'rows', 'from', 'json', 'to',\n 'inner join', 'outer join', 'left join', 'groupby', 'pivot', 'pivot table',\n 'sort', 'is sorted', 'show', 'use disk', 'out-of-memory', 'list on disk',\n 'stored list', 'min', 'max', 'sum', 'first', 'last', 'count', 'unique',\n 'average', 'standard deviation', 'median', 'mode', 'in-memory', 'index'\n})\n\nkeywords.sort(key=lambda x: x.lower())\n\n\nsetup(\n name=\"tablite\",\n version=\"2020.11.3.62707\",\n url=\"https://github.com/root-11/tablite\",\n license=\"MIT\",\n author=\"Bjorn Madsen\",\n author_email=\"bjorn.madsen@operationsresearchgroup.com\",\n description=\"A table crunching library\",\n long_description=long_description,\n long_description_content_type='text/markdown',\n keywords=keywords,\n packages=[\"table\"],\n include_package_data=True,\n data_files=[(\".\", [\"LICENSE\", \"README.md\"])],\n platforms=\"any\",\n install_requires=[\n 'xlrd>=1.2.0',\n 'pyexcel-ods>=0.5.6',\n 'openpyxl>=3.0.5',\n 'pyperclip>=1.8.1',\n ],\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Science/Research\",\n \"Natural Language :: English\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n ],\n)\n\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"176945405","text":"from django import forms\r\nfrom .models import Article, Category\r\n\r\n\r\nclass CreateArticle(forms.ModelForm):\r\n class Meta:\r\n model = Article\r\n fields = ('title', 'cate', 'content',)\r\n\r\n def __init__(self, *args, **kwargs):\r\n self.user = kwargs.pop('user', None)\r\n super(CreateArticle, self).__init__(*args, **kwargs)\r\n if not self.user.is_admin:\r\n self.fields['cate'].queryset = Category.objects.filter(level__lte=5)\r\n\r\n self.fields['title'].widget.attrs.update({'class': 'form-control', 'autofocus': True})\r\n self.fields['cate'].widget.attrs.update({'class': 'form-control'})\r\n\r\n def save(self, commit=True):\r\n if self.user:\r\n self.instance.author = self.user\r\n return super(CreateArticle, self).save(commit=commit)\r\n","sub_path":"article/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"497294624","text":"#!/usr/bin/env python3\n\nimport serial\nimport json\nfrom influxdb import InfluxDBClient\nfrom datetime import datetime\n\nLOCATION_ID = 'l'\nTEMPERATURE_ID = 't'\nHUMIDITY_ID = 'h'\nDEW_POINT_ID = 'd'\nPRESSURE_ID = 'p'\n\n\ndef buildInfluxDBMessage(sensor_message):\n \"\"\"\n Builds a influxDB json object from the message from a sensor. \n \"\"\"\n \n json_body = [{\n \"measurement\" : \"weather_reading\",\n \"time\" : datetime.now().isoformat(),\n \"tags\" : \n {\n \"location\" : sensor_message[LOCATION_ID],\n },\n \"fields\" : \n {\n \"humidity\" : sensor_message[HUMIDITY_ID],\n \"temperature\" : sensor_message[TEMPERATURE_ID],\n \"pressure\" : sensor_message[PRESSURE_ID],\n \"dew_point\" : sensor_message[DEW_POINT_ID]\n }\n }]\n\n return json_body\n\n\n\nser = serial.Serial(\n\tport='/dev/ttyS0',\n\tbaudrate=1200,\n parity=serial.PARITY_NONE,\n\tstopbits=serial.STOPBITS_ONE,\n\tbytesize=serial.EIGHTBITS,\n\ttimeout=30\n )\n\n\nclient = InfluxDBClient(host='localhost', port=8086)\nclient.switch_database('weather')\n\n\nwhile True:\n message = ser.readline()\n print(message)\n print(\"\\n\\n\")\n \n try:\n jsonmsg = json.loads(message)\n \n json_body = buildInfluxDBMessage(jsonmsg)\n\n\n print(json.dumps(json_body,indent=2))\n\n print(\"Write points: {0}\".format(json_body))\n client.write_points(json_body)\n\n except json.decoder.JSONDecodeError as ex:\n print(ex.msg)\n","sub_path":"receiver/weather_receiver.py","file_name":"weather_receiver.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"402395529","text":"import sys\nsys.path.append('.')\nimport shutil\nimport pytest\nfrom pathlib import Path\nimport json\n\nimport pandas as pd\n\nimport PySAM.ResourceTools as tools # change back to module import\nimport PySAM.Windpower as wp\nimport PySAM.Pvwattsv7 as pv\n\n\ndef test_solar():\n solar = str(Path(__file__).parent / \"blythe_ca_33.617773_-114.588261_psmv3_60_tmy.csv\")\n data = tools.SAM_CSV_to_solar_data(solar)\n assert (data['lat'] == 33.61)\n assert (data['lon'] == -114.58)\n assert (data['dn'][7] == 262)\n assert (data['df'][7] == 16)\n assert (data['gh'][7] == 27)\n assert (data['tdry'][7] == pytest.approx(8.96, 0.1))\n model = pv.default(\"PVwattsNone\")\n model.SolarResource.solar_resource_data = data\n model.execute()\n aep = model.Outputs.annual_energy\n model.SolarResource.solar_resource_file = solar\n model.execute()\n assert(aep == pytest.approx(model.Outputs.annual_energy, 1))\n\n\ndef test_wind():\n wind = str(Path(__file__).parent / \"AR Northwestern-Flat Lands.srw\")\n data = tools.SRW_to_wind_data(wind)\n assert (data['fields'] == [1, 2, 4, 3, 1, 2, 4, 3, 1, 2, 4, 3, 1, 2, 4, 3])\n assert (data['heights'] == [50, 50, 50, 50, 80, 80, 80, 80, 110, 110, 110, 110, 140, 140, 140, 140])\n assert (data['data'][0] == [9.587, 0.953420183, 173, 9.466, 10.247, 0.950086356, 174, 11.637, 10.627, 0.946649889,\n 175, 13.249, 10.997, 0.94340982, 175, 14.509])\n\n wind_model = wp.new()\n wind_model.Resource.wind_resource_data = data\n returned_data = wind_model.Resource.wind_resource_data['data'][0]\n for i, d in enumerate(data['data'][0]):\n assert (d == pytest.approx(returned_data[i], 1e-3))\n\n\ndef test_urdb():\n urdb = str(Path(__file__).parent / \"urdbv7.json\")\n with open(urdb, 'r') as file:\n urdb_data = json.load(file)\n ur5 = tools.URDBv7_to_ElectricityRates(urdb_data)\n\n ec_tou = [1, 1, 100, 0, 0.070768997073173523, 0,\n 1, 2, 9.9999996802856925e+37, 0, 0.082948997616767883, 0,\n 2, 1, 100, 0, 0.056908998638391495, 0,\n 2, 2, 9.9999996802856925e+37, 0, 0.069078996777534485, 0]\n\n dc_tou = [1, 1, 100, 19.538999557495117,\n 1, 2, 9.9999996802856925e+37, 13.093000411987305,\n 2, 1, 100, 8.0909996032714844,\n 2, 2, 9.9999996802856925e+37, 4.6760001182556152]\n\n flat_mat = [0, 1, 100, 4, 0, 2, 1e+38, 6.46,\n 1, 1, 1e+38, 6.46,\n 2, 1, 1e+38, 6.46,\n 3, 1, 1e+38, 6.46,\n 4, 1, 1e+38, 13.87,\n 5, 1, 1e+38, 13.87,\n 6, 1, 1e+38, 13.87,\n 7, 1, 1e+38, 13.87,\n 8, 1, 1e+38, 13.87,\n 9, 1, 1e+38, 13.87,\n 10, 1, 1e+38, 6.46,\n 11, 1, 1e+38, 6.46]\n\n ec_tou_tested = [item for sublist in ur5['ur_ec_tou_mat'] for item in sublist]\n dc_tou_tested = [item for sublist in ur5['ur_dc_tou_mat'] for item in sublist]\n flat_mat_tested = [item for sublist in ur5['ur_dc_flat_mat'] for item in sublist]\n\n assert(ec_tou_tested == ec_tou)\n assert(dc_tou_tested == dc_tou)\n assert(flat_mat_tested == flat_mat)\n\n\ndef test_resourcefilefetcher():\n\n # please get your own API key from here https://developer.nrel.gov/signup/\n NREL_API_KEY = ''\n NREL_API_EMAIL = ''\n\n lon_lats = [(-105.1800775, 39.7383155)] # golden CO\n\n resource_dir = str(Path(__file__).parent / \"tmp\")\n\n # --- fetch solar tmy file from psm3-tmy using default parameters ---\n solarfetcher = tools.FetchResourceFiles(\n tech='solar',\n nrel_api_key=NREL_API_KEY,\n nrel_api_email=NREL_API_EMAIL,\n resource_dir=resource_dir)\n solarfetcher.fetch(lon_lats)\n\n # --- read csv and confirm dimensions ---\n solar_path_dict = solarfetcher.resource_file_paths_dict\n solar_fp = solar_path_dict[lon_lats[0]]\n solar_csv = pd.read_csv(solar_fp)\n num_timesteps = 8760\n assert solar_csv.shape[0] == num_timesteps+2\n\n # --- test legacy 'pv' instead of 'solar'---\n solarfetcher = tools.FetchResourceFiles(\n tech='pv',\n nrel_api_key=NREL_API_KEY,\n nrel_api_email=NREL_API_EMAIL,\n resource_dir=resource_dir)\n solarfetcher.fetch(lon_lats)\n\n # --- read csv and confirm dimensions ---\n solar_path_dict = solarfetcher.resource_file_paths_dict\n solar_fp = solar_path_dict[lon_lats[0]]\n solar_csv = pd.read_csv(solar_fp)\n num_timesteps = 8760\n assert solar_csv.shape[0] == num_timesteps+2\n\n # --- fetch solar single-year 30-min file from psm3 ---\n solarfetcher = tools.FetchResourceFiles(\n tech='solar',\n nrel_api_key=NREL_API_KEY,\n nrel_api_email=NREL_API_EMAIL,\n resource_dir=resource_dir,\n resource_type='psm3',\n resource_year='2018',\n resource_interval_min=30)\n solarfetcher.fetch(lon_lats)\n\n # --- read csv and confirm dimensions ---\n solar_path_dict = solarfetcher.resource_file_paths_dict\n solar_fp = solar_path_dict[lon_lats[0]]\n solar_csv = pd.read_csv(solar_fp)\n num_timesteps = 17520\n assert solar_csv.shape[0] == num_timesteps+2\n\n # --- fetch solar tgy for 2018 from psm3-tmy ---\n solarfetcher = tools.FetchResourceFiles(\n tech='solar',\n nrel_api_key=NREL_API_KEY,\n nrel_api_email=NREL_API_EMAIL,\n resource_dir=resource_dir,\n resource_type='psm3-tmy',\n resource_year='tgy-2018')\n solarfetcher.fetch(lon_lats)\n\n # --- read csv and confirm dimensions ---\n solar_path_dict = solarfetcher.resource_file_paths_dict\n solar_fp = solar_path_dict[lon_lats[0]]\n solar_csv = pd.read_csv(solar_fp)\n num_timesteps = 8760\n assert solar_csv.shape[0] == num_timesteps+2\n\n # --- fetch 5-minute data for 2018 from psm3-5min ---\n # this NSRDB API endpoint not working properly as of 8/21/2020\n #solarfetcher = tools.FetchResourceFiles(\n # tech='solar',\n # nrel_api_key=NREL_API_KEY,\n # nrel_api_email=NREL_API_EMAIL,\n # resource_dir=resource_dir,\n # resource_type='psm3-5min',\n # resource_interval_min=5,\n # resource_year='2018')\n #solarfetcher.fetch(lon_lats)\n\n # --- read csv and confirm dimensions ---\n #solar_path_dict = solarfetcher.resource_file_paths_dict\n #solar_fp = solar_path_dict[lon_lats[0]]\n #solar_csv = pd.read_csv(solar_fp)\n #num_timesteps = 175200\n #assert solar_csv.shape[0] == num_timesteps+2\n\n # --- fetch wind ---\n wtkfetcher = tools.FetchResourceFiles(\n tech='wind',\n nrel_api_key=NREL_API_KEY,\n nrel_api_email=NREL_API_EMAIL,\n resource_dir=resource_dir)\n wtkfetcher.fetch(lon_lats)\n\n # --- read csv and confirm dimensions ---\n wtk_path_dict = wtkfetcher.resource_file_paths_dict\n wtk_fp = wtk_path_dict[lon_lats[0]]\n wtk_csv = pd.read_csv(wtk_fp)\n assert wtk_csv.shape == (8764, 10)\n\n shutil.rmtree(resource_dir)\n","sub_path":"tests/test_ResourceTools.py","file_name":"test_ResourceTools.py","file_ext":"py","file_size_in_byte":7244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"495504190","text":"#Frankenstein Pickaxe - Program to write the program\n\nimport itertools,math,statistics,os\n'''\n[W]ood\n[S]tone\n[I]ron\n[G]old\n[D]iamond\n\n120 combinations (order doesn't matter)\n'''\nclass frankenpicks(object):\n \n def __init__(self):\n self.table=[\"{} |\\t{}\\t{}\\t{}\\t{}\\t{}\".format(\"Mat\",\"Harv\",\"#Uses\",\"Spd\",\"Dmg\",\"Ench\"),\"-\"*45] #table for displaying all of stats for all of picks\n\n self.w_combos=[] #Combinations that start with each tool\n self.s_combos=[] #eg s_combos contains \"SWW\",\"SWS\",\"SWI\",etc.\n self.i_combos=[]\n self.g_combos=[]\n self.d_combos=[]\n self.all_combos=[]\n \n self.i_v=[] #instance variable\n #and the 5 pick attributes....\n self.lst_harv=[]\n self.lst_uses=[]\n self.lst_speed=[]\n self.lst_dmg=[]\n self.lst_enchant=[]\n self.lst_all=[self.lst_harv,self.lst_uses,self.lst_speed,self.lst_dmg,self.lst_enchant]\n\n self.prefix_uses=[] #contain just the tools that fall under the requirements\n self.prefix_spd=[] # to get a description\n self.prefix_enchant=[]\n \n self.pI=[] #preInit\n self.i=[] #Init\n self.lang=[] #Lang file\n\n def gen_ListOfCombos(self):\n comboset={0}\n for i in itertools.permutations('WWWSSSIIIGGGDDD',3):\n comboset.add(i)\n\n comboset.remove(0)\n combolist=list(comboset)\n combolist.sort(reverse=True)\n\n for entry in combolist:\n if entry[0]==entry[1] and entry[1]==entry[2]:\n combolist.remove(entry)\n\n for entry in range(len(combolist)+1):\n if entry!=0:\n prev_tupl=combolist[entry-1][0]+combolist[entry-1][1]+combolist[entry-1][2]\n combolist[entry-1]=prev_tupl\n\n tot=len(combolist)\n indiv_tot=1\n\n for entry in range(len(combolist)):\n if combolist[entry][0]=='W':\n self.w_combos.append(combolist[entry])\n elif combolist[entry][0]=='S':\n self.s_combos.append(combolist[entry])\n elif combolist[entry][0]=='I':\n self.i_combos.append(combolist[entry])\n elif combolist[entry][0]=='G':\n self.g_combos.append(combolist[entry])\n elif combolist[entry][0]=='D':\n self.d_combos.append(combolist[entry])\n self.all_combos = self.w_combos + self.s_combos + self.i_combos + self.g_combos + self.d_combos\n \n def print_ListOfCombos(self):\n for c in self.all_combos:\n print(c)\n\n def instance_vars(self): #makes programming a LOT less tedious....\n EnumToolInfo = {'W': [0, 59, 2, 0, 15], 'S': [1, 131, 4, 1, 5], 'I': [2, 250, 6, 2, 14], 'G': [0, 32, 12, 0, 22], 'D': [3, 1561, 8, 3, 10] } \n\n for c in self.all_combos:\n varname = (c+\"pickaxe\").lower()\n matname = (c+\"material\").upper()\n\n harv=max(EnumToolInfo[c[0]][0],EnumToolInfo[c[1]][0],EnumToolInfo[c[2]][0])\n self.lst_harv.append([harv,c])\n\n uses=math.ceil(statistics.mean([EnumToolInfo[c[0]][1],EnumToolInfo[c[1]][1],EnumToolInfo[c[2]][1]])) \n self.lst_uses.append([uses,c])\n\n speed= math.ceil(statistics.mean([EnumToolInfo[c[0]][2],EnumToolInfo[c[1]][2],EnumToolInfo[c[2]][2]])) \n self.lst_speed.append([speed,c])\n\n dmg= math.ceil(statistics.mean([EnumToolInfo[c[0]][3],EnumToolInfo[c[1]][3],EnumToolInfo[c[2]][3]])) \n self.lst_dmg.append([dmg,c])\n\n enchant= math.ceil(statistics.mean([EnumToolInfo[c[0]][4],EnumToolInfo[c[1]][4],EnumToolInfo[c[2]][4]])) \n self.lst_enchant.append([enchant,c])\n \n line1 = 'public static final Item.ToolMaterial {} = EnumHelper.addToolMaterial(\"{}\", {}, {}, {}.0F, {}.0F, {});'.format(matname,c.upper(),harv,uses,speed,dmg,enchant)\n line2 = 'public static Item {};'.format(varname)\n self.i_v.append(line1+\"\\n\"+line2+\"\\n\")\n self.table.append(\"{} |\\t{}\\t{}\\t{}\\t{}\\t{}\".format(c.upper(),harv,uses,speed,dmg,enchant))\n\n def print_stats(self):\n currList={0:'##### Harvest #####',1:'##### Uses #####',2:'##### Speed #####',3:'##### Damage #####',4:'##### Enchant #####'}\n for lst in range(len(self.lst_all)):\n self.lst_all[lst].sort(reverse=True)\n print(\"\\n\")\n print(currList[lst]) #title of which list\n \n lst1=self.lst_all[lst][0:25]\n lst2=self.lst_all[lst][25:50]\n lst3=self.lst_all[lst][50:75]\n lst4=self.lst_all[lst][75:100]\n lst5=self.lst_all[lst][100:]\n for a,b,c,d,e in zip(lst1,lst2,lst3,lst4,lst5):\n print(\"{} {} {} {} {}\".format(a,b,c,d,e))\n\n def assignCat2Var(self,category):\n '''0-4:harv,uses,spd,dmg,enchant'''\n outopt=[\"Harvest\",\"Uses\",\"Speed\",\"Damage\",\"Enchantability\"]\n print(\"## {}-{} ##\".format(outopt[category],category))\n for lst in self.lst_all:\n lst.sort(reverse=True)\n return self.lst_all[category]\n \n\n def get_StatsPercentile(self,catVar,prefixcheck): \n '''use assignCat2Var first''' \n statDic={}\n statList=[]\n prefixed=[]\n for entry in catVar:\n statList.append(entry[0])\n if entry[0]>prefixcheck:\n prefixed.append((str(entry[0])+\"/\"+entry[1]))\n if entry[0] not in statDic:\n statDic[entry[0]]=1\n else:\n statDic[entry[0]]+=1\n statEntries=list(set(statList))\n statList.sort(reverse=True)\n prefixed.sort(reverse=True)\n print(\"Range: \",statEntries, \"##\",len(statEntries),\"/\",len(statList),\"\\n\")\n print(\"Freq : \",statDic,\"\\n\")\n print(\"Prefixed: \",prefixed)\n \n \n \n def preInit(self): #The following 3 functions take the repetitiveness out of programming! hooray!\n for c in self.all_combos:\n varname = (c+\"pickaxe\").lower()\n matname = (c+\"material\").upper()\n texname = (\"testmod:\"+varname)\n \n line1 = '{} = new CustomPickaxe({}).setUnlocalizedName(\"{}\").setCreativeTab(CreativeTabs.tabTools).setTextureName(\"{}\");'.format(varname,matname,varname,texname)\n line2 = 'GameRegistry.registerItem({}, \"{}\");'.format(varname,varname)\n self.pI.append(line1+\"\\n\"+line2+\"\\n\")\n \n def init(self):\n for c in self.all_combos:\n varname = (c+\"pickaxe\").lower()\n \n line = ''' GameRegistry.addRecipe(new ItemStack(Frankentools.{}), new Object[] [\"{}\", \" K \", \" K \", 'K', Items.stick, 'W', Blocks.planks, 'S', Blocks.cobblestone, 'I', Items.iron_ingot, 'G', Items.gold_ingot, 'D', Items.diamond]); '''.format(varname,c)\n self.i.append(line+\"\\n\")\n\n def langfile(self):\n for c in self.all_combos:\n varname = (c+\"pickaxe\").lower()\n if len(set(c))==2:\n igname='Bi-Fused Pickaxe'\n elif len(set(c))==3:\n igname='Tri-Fused Pickaxe'\n line = \"item.{}.name={}\".format(varname,igname)\n self.lang.append(line+\"\\n\")\n\n def print_ListOfCombosTemp(self):\n cuntr=0\n for c in self.all_combos:\n if c[0] not in 'WSI':\n cuntr+=1\n print(c,cuntr)\n\n def rename(self,prefix):\n indx=0\n templst=[]\n print(os.getcwd())\n os.chdir(\"C:\\\\Users\\\\Tyler Wolfe-Adam\\\\AppData\\\\Roaming\\\\.minecraft\\\\Forge_1.7.10\\\\bin\\\\assets\\\\frankentools\\\\textures\\\\items\")\n for x in self.all_combos:\n if x[0] not in 'WSI':\n templst.append(x)\n for f in os.listdir():\n if '__' in f:\n os.rename(f,templst[indx].lower()+\".png\")\n #print(f,templst[indx].lower()+\".png\")\n indx+=1\n\n \n \nf=frankenpicks()\nf.gen_ListOfCombos()\nf.instance_vars()\nfor f in f.table:\n print(f)\n \n#f.langfile()\n#for x in f.lang:\n #print(x)\n\n\n##ff=f.assignCat2Var(0)\n##f.get_StatsPercentile(ff,0)\n##print(\"\\n\")\n##\n##ff=f.assignCat2Var(1) #Uses\n##f.get_StatsPercentile(ff,600)\n##print(\"\\n\")\n##\n##ff=f.assignCat2Var(2) #Speed\n##f.get_StatsPercentile(ff,0)\n##print(\"\\n\")\n##\n##ff=f.assignCat2Var(3)\n##f.get_StatsPercentile(ff,100)\n##print(\"\\n\")\n##\n##ff=f.assignCat2Var(4) #Enchantability\n##f.get_StatsPercentile(ff,15)\n\n\n\n\n'''\nFor naming system...\n\n#Harvest - No label [since the reqirement is obvious]\n#Uses - Top 30% (aka >600) = 1134(x3), 1085(x3), 1061(x3), 1052(x3), 687(x3), 648(x6), 624(x6), 615(x6), 608(x3)\n#Speed - Top ~17% (aka >8) = 9(x9), 10(x9), 11(x4)\n#Damage - No label [since that info is already included in the game]\n#Enchantability - Top 30% (aka >15 which is wood) = 16(x12), 17(x12), 18(x6), 20(x6)\n\nXXY = Bi-Fused Franken-Pickaxe\nXYZ = Tri-Fused Franken-Pickaxe\n\nWithin usage requirement = \"Useful\"\nWithin speed requirement = \"Efficient\"\nWithin enchantment requirement = \"Mystical\"\n\nUSE - GDI DIG GID IGD DGI IDG \"Mystically and Efficiently Useful\"\nUS - DDG GDD DGD = \"Efficiently Useful\"\nUE [None...how sad]\nSE - GGW GIG IGG GGI GDG SGG DGG GSG GGS GWG GGD WGG = \"Mystically Efficient\"\n\n\n''' \n\n\n'''\nVanilla pix info\n WOOD[0, 59, 2.0F, 0.0F, 15],\n STONE[1, 131, 4.0F, 1.0F, 5],\n IRON[2, 250, 6.0F, 2.0F, 14],\n EMERALD[3, 1561, 8.0F, 3.0F, 10],\n GOLD[0, 32, 12.0F, 0.0F, 22];\n'''\n\n","sub_path":"FrankensteinPickaxes/FrankenPicks_PickstatsAndHelpers/frankenpicks_output.py","file_name":"frankenpicks_output.py","file_ext":"py","file_size_in_byte":9522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"541609751","text":"import os\nimport re\nimport logging\n\n\ndef main():\n logging.basicConfig(filename='data-changer.log', level=logging.INFO, format='%(asctime)s %(message)s') # logging of the\n # script that shows if file was changed\n # --------------------------- ORDER FINDING --------------------------- #\n try:\n list_of_orders = os.listdir(\"Cargill_Interface/OUT\")\n except FileNotFoundError:\n logging.error(f\"[!] The system cannot find the path specified: 'Cargill_Interface/OUT'.\")\n else:\n if len(list_of_orders) < 0:\n logging.info(f\"[!] No files found.\")\n else:\n for order_file in list_of_orders:\n with open(f\"Cargill_Interface/OUT/{order_file}\", \"r\",\n encoding=\"ISO-8859-1\") as data_file: # opening in this format as ANSI\n # doesn't recognized by Python\n new_file = data_file.readlines()\n order = \"\".join(new_file)\n # --------------------------- CHANGES --------------------------- #\n try:\n wrong_date_format_searcher = re.search(r'\\d+\\.\\d+\\.\\d+', order).group() # Searching for\n # dates in format \"xx.xx.xxxx\", for example: 03.08.2021\n except:\n logging.info(f\"[-] {order_file} wasn't changed.\")\n continue\n else:\n splited_date = wrong_date_format_searcher.split(\n \".\") # taking digits with splitting xx.xx.xxxx by dots\n year = splited_date[2]\n month = splited_date[1]\n day = splited_date[0]\n new_order = \"\"\n\n if wrong_date_format_searcher in order:\n new_order = order.replace(wrong_date_format_searcher, f\"{year}-{month}-{day}\")\n # print(new_order)\n # --------------------------- FILE CHANGING --------------------------- #\n with open(f\"Cargill_Interface/OUT/{order_file}\", \"w\", encoding='utf_8_sig') as final_file:\n final_file.write(new_order)\n logging.info(f'[+] {order_file} was successfully changed.')\n\nmain()\n\n\n\n\n\n\n\n\n\n\n","sub_path":"data-changer.py","file_name":"data-changer.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"640312672","text":"import sys\n\ndef test(colors):\n for i in range(len(colors) - 1):\n for j in range(len(colors) - 1):\n square = colors[i][j], colors[i + 1][j], colors[i][j + 1], colors[i + 1][j + 1]\n if sum(square) != 2:\n return \"YES\"\n return \"NO\"\n\ndef initial(colors):\n for i in range(4):\n yield [0 if j == \"#\" else 1 for j in colors[i]]\n\nif __name__ == \"__main__\":\n colors = [sys.stdin.readline() for i in range(4)]\n \n colors = list(initial(colors))\n\n print(test(colors))","sub_path":"Code Forecs Problems/iq.py","file_name":"iq.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"258838186","text":"\"\"\"\n@summary: Module containing client functions for interacting with OpenTree web \n services\n@author: CJ Grady / Jeff Cavner\n@version: 3.3.4\n@status: beta\n\n@license: Copyright (C) 2016, University of Kansas Center for Research\n\n Lifemapper Project, lifemapper [at] ku [dot] edu, \n Biodiversity Institute,\n 1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA\n \n This program is free software; you can redistribute it and/or modify \n it under the terms of the GNU General Public License as published by \n the Free Software Foundation; either version 2 of the License, or (at \n your option) any later version.\n \n This program 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 this program; if not, write to the Free Software \n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA \n 02110-1301, USA.\n\n\"\"\"\nfrom LmClient.constants import OTL_HINT_URL, OTL_TREE_WEB_URL\n\n# .............................................................................\nclass OTLClient(object):\n \"\"\"\n @summary: Lifemapper interface to Open Tree of Life web services\n \"\"\"\n # .........................................\n def __init__(self, cl):\n \"\"\"\n @summary: Constructor\n @param cl: Lifemapper client for connection to web services\n \"\"\"\n self.cl = cl\n\n # .........................................\n def getOTLHint(self, taxaName):\n \"\"\"\n @summary: Calls the Open Tree of Life hint service with a taxa name and \n returns matching OTL tree ids\n @param taxaName: The name of the taxa to search for\n \"\"\"\n url = OTL_HINT_URL\n jsonBody = '{\"name\":\"%s\",\"context_name\":\"All life\"}' % (taxaName)\n res = self.cl.makeRequest(url, \n method=\"POST\", \n body=jsonBody, \n headers={\"Content-Type\": \"application/json\"})\n return res\n \n # .........................................\n def getOTLTreeWeb(self, otlTID):\n \"\"\"\n @summary: Calls the Open Tree of Life tree service with an OTL tree id \n and returns a tree in Newick format.\n @param otlTID: Open Tree of Life tree idopen tree tree id\n \"\"\"\n url = OTL_TREE_WEB_URL\n jsonBody = '{\"ott_id\":\"%s\"}' % (otlTID)\n res = self.cl.makeRequest(url, \n method=\"POST\", \n body=jsonBody, \n headers={\"Content-Type\": \"application/json\"})\n return res\n ","sub_path":"dev/dev/ideas/PAMBrowser/LmClient/openTree.py","file_name":"openTree.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"405904157","text":"from WMCore.Configuration import Configuration\nconfig = Configuration()\n\nconfig.section_('General')\nconfig.General.transferOutputs = True\nconfig.General.requestName = 'MuOnia2015Dv1'\n\nconfig.section_('JobType')\nconfig.JobType.psetName = '../runOnia2MuMuRootupler.py'\nconfig.JobType.pluginName = 'Analysis'\n#config.JobType.outputFiles = ['Onia2MuMuPAT.root']\n\nconfig.section_('Data')\nconfig.Data.inputDataset = '/MuOnia/zhenhu-Onia2MuMuPAT-Run2015D-MuOnia-v1-df0ec57774bd95f665b822a32a3e4b17/USER'\nconfig.Data.inputDBS = 'phys03'\nconfig.Data.unitsPerJob = 50\nconfig.Data.splitting = 'LumiBased'\n#config.Data.outLFNDirBase = '/store/user/%s/' % (getUsernameFromSiteDB())\n#config.Data.outLFNDirBase = '/store/user/yik/myfourmuonNtpl/muonia/2015Dwith25nsv3'\n#config.Data.lumiMask = 'Cert_246908-258159_13TeV_PromptReco_Collisions15_25ns_JSON_MuonPhys.txt'\nconfig.Data.lumiMask = 'https://cms-service-dqm.web.cern.ch/cms-service-dqm/CAF/certification/Collisions15/13TeV/Cert_246908-258159_13TeV_PromptReco_Collisions15_25ns_JSON_MuonPhys_v2.txt'\n#config.Data.runRange = '193093-193999' # '193093-194075'\nconfig.Data.publication = True\nconfig.Data.publishDataName = 'Onia2MuMuRootuple-Run2015D-MuOnia-v1'\nconfig.Data.ignoreLocality = True\n\nconfig.section_('User')\n\nconfig.section_('Site')\nconfig.Site.storageSite = 'T3_US_FNALLPC' \n\n","sub_path":"Onia/test/crabJobs/crab3_MuOnia.py","file_name":"crab3_MuOnia.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"186409606","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Sep 13 15:55:30 2019\r\n\r\n@author: 10526\r\n\"\"\"\r\n\r\n#预处理2 拆分订单\r\n\r\nf=r'C:\\Users\\10526\\Desktop\\DATA\\zk1.txt'\r\nf0=r'C:\\Users\\10526\\Desktop\\DATA\\zk2.txt'\r\n\r\nfw=open(f0,'w')\r\n\r\nwith open(f) as fr:\r\n lastLine=fr.readline()\r\n fw.write(lastLine)\r\n lastLine=lastLine.strip().split(\"\\t\")\r\n for line in fr:\r\n if(line==\"\\n\"):\r\n fw.write(\"\\n\")\r\n lastLine=line\r\n continue\r\n if(lastLine==\"\\n\"):\r\n fw.write(line)\r\n lastLine=line.strip().split(\"\\t\")\r\n continue\r\n curLine=line.strip().split(\"\\t\")\r\n t0=int(lastLine[2][3:5])\r\n t1=int(curLine[2][3:5])\r\n if(t1-t0>2):\r\n fw.write(\"\\n\")\r\n fw.write(line)\r\n lastLine=curLine\r\nfr.close()\r\nfw.close()\r\n","sub_path":"2019CUMCM/modeling/ini2.py","file_name":"ini2.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"616255419","text":"pos = -1\r\ndef search(list,n):\r\n lowerbound = 0\r\n upperbound = len(list)-1\r\n\r\n while lowerbound <= upperbound:\r\n mid = (lowerbound+upperbound)//2\r\n\r\n if list[mid] == n:\r\n globals()['pos'] = mid\r\n return True\r\n else:\r\n if list[mid]<n:\r\n lowerbound = mid + 1\r\n else:\r\n upperbound = mid - 1\r\n return False\r\n\r\nlist = [4,7,8,12,45,99]\r\nn = 8\r\n\r\nif search(list,n):\r\n print(\"found at\",pos+1)\r\nelse:\r\n print(\"not found\")","sub_path":"binarysearchusingwhile.py","file_name":"binarysearchusingwhile.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"466710671","text":"\"\"\"Base Transform for doing basic calls for dwt & idwt based on the dimensions called\"\"\"\n\nimport numpy as np\n\nfrom wavelet.transforms.wavelet import Wavelet\nfrom wavelet.util.utility import getExponent\nfrom wavelet.wavelets import getAllWavelets\n\n\nclass BaseTransform:\n \"\"\"\n Transform class to call the Discrete Wavelet Transform on select wavelet based on\n the dimensions of the data\n\n Attributes\n ----------\n __wavelet: Wavelet\n object of the Wavelet class based on the wavelet name\n \"\"\"\n\n def __init__(self, waveletName):\n self.__wavelet = Wavelet(waveletName)\n\n def getWaveletDefinition(self):\n \"\"\"\n Returns the wavelet definition for the select wavelet\n\n Returns\n -------\n object\n object of the selected wavelet class\n \"\"\"\n return self.__wavelet.__wavelet__\n\n @staticmethod\n def getAllWaveletDefinition():\n \"\"\"\n Returns the list of all the wavelets implemented\n\n Returns\n -------\n list\n list of all wavelets\n \"\"\"\n return list(getAllWavelets())\n\n def waveDec1(self, arrTime, level):\n \"\"\"\n Single Dimension wavelet decomposition based on the levels\n\n Parameters\n ----------\n arrTime : array_like\n input array signal in Time domain\n level : int\n level for the decomposition power of 2\n\n Returns\n -------\n array_like\n coefficients Frequency or the Hilbert domain\n \"\"\"\n arrHilbert = arrTime\n length = 0\n dataLength = len(arrHilbert)\n transformWaveletLength = self.__wavelet.__wavelet__.__transformWaveletLength__\n\n while dataLength >= transformWaveletLength and length < level:\n arrTemp = self.__wavelet.dwt(arrHilbert, dataLength)\n\n arrHilbert[: len(arrTemp)] = arrTemp\n dataLength >>= 1\n length += 1\n\n return arrHilbert\n\n def waveRec1(self, arrHilbert, level):\n \"\"\"\n Single Dimension wavelet reconstruction based on the levels\n\n Parameters\n ----------\n arrHilbert : array_like\n input array signal in Frequency or the Hilbert domain\n level : int\n level for the decomposition power of 2\n\n Returns\n -------\n array_like\n coefficients Time domain\n \"\"\"\n arrTime = arrHilbert.copy()\n dataLength = len(arrTime)\n transformWaveletLength = self.__wavelet.__wavelet__.__transformWaveletLength__\n h = transformWaveletLength\n\n steps = getExponent(dataLength)\n for _ in range(level, steps):\n h <<= 1\n\n while len(arrTime) >= h >= transformWaveletLength:\n arrTemp = self.__wavelet.idwt(arrTime, h)\n\n arrTime[: len(arrTemp)] = arrTemp\n h <<= 1\n\n return arrTime\n\n def waveDec2(self, matTime):\n \"\"\"\n Two Dimension wavelet decomposition based on the levels\n\n Parameters\n ----------\n matTime : array_like\n input matrix signal in Time domain\n\n Returns\n -------\n array_like\n coefficients Time domain\n \"\"\"\n noOfRows = len(matTime)\n noOfCols = len(matTime[0])\n levelM = getExponent(noOfRows)\n levelN = getExponent(noOfCols)\n\n matHilbert = [[0.] * noOfRows] * noOfCols\n matHilbert = np.array(matHilbert).T\n\n # rows\n for i in range(noOfRows):\n arrTime = [0.] * noOfCols\n for j in range(noOfCols):\n arrTime[j] = matTime[i][j]\n\n arrHilbert = self.waveDec1(arrTime, levelN)\n\n for j in range(noOfCols):\n matHilbert[i][j] = arrHilbert[j]\n\n # cols\n for j in range(noOfCols):\n arrTime = [0.] * noOfRows\n for i in range(noOfRows):\n arrTime[i] = matHilbert[i][j]\n\n arrHilbert = self.waveDec1(arrTime, levelM)\n\n for i in range(noOfRows):\n matHilbert[i][j] = arrHilbert[i]\n\n return matHilbert\n\n def waveRec2(self, matHilbert):\n \"\"\"\n Two Dimension wavelet reconstruction based on the levels\n\n Parameters\n ----------\n matHilbert : array_like\n input matrix signal in Frequency or the Hilbert domain\n\n Returns\n -------\n array_like\n coefficients Time domain\n \"\"\"\n noOfRows = len(matHilbert)\n noOfCols = len(matHilbert[0])\n levelM = getExponent(noOfRows)\n levelN = getExponent(noOfCols)\n\n matTime = [[0.] * noOfRows] * noOfCols\n matTime = np.array(matTime).T\n\n # rows\n for j in range(noOfCols):\n arrHilbert = [0.] * noOfRows\n for i in range(noOfRows):\n arrHilbert[i] = matHilbert[i][j]\n\n arrTime = self.waveRec1(arrHilbert, levelM)\n\n for i in range(noOfRows):\n matTime[i][j] = arrTime[i]\n\n # cols\n for i in range(noOfRows):\n arrHilbert = [0.] * noOfCols\n for j in range(noOfCols):\n arrHilbert[j] = matTime[i][j]\n\n arrTime = self.waveRec1(arrHilbert, levelN)\n\n for j in range(noOfCols):\n matTime[i][j] = arrTime[j]\n\n return matTime\n","sub_path":"wavelet/transforms/base_transform.py","file_name":"base_transform.py","file_ext":"py","file_size_in_byte":5379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"313531056","text":"\"\"\"SQL queries that answer the story questions about cities and cost of living\nin Germany. Note: the tables.db file needs to be in the same location as this\npython file in order for it to run correctly.\"\"\"\nimport sqlite3\nfrom os import linesep\n\n\ndef get_top_density_low_cost(c):\n \"\"\"select the five cities with the highest density, that have a single\n person cost of living under 750 euro a month. Return fields: cities,\n density, and single person cost\"\"\"\n with c:\n cursor = c.cursor()\n cursor.execute(\n 'SELECT wiki.city, density_km2, single_person '\n 'FROM wiki LEFT OUTER JOIN numbeo ON numbeo.City = wiki.City '\n 'WHERE single_person < 750 '\n 'ORDER BY density_km2 DESC '\n 'LIMIT 5')\n return cursor.fetchall()\n\n\ndef get_highest_family_cost(c):\n \"\"\"select the city with the highest monthly living cost for a family of\n four where the density is < 1500 people per square km.\n Return fields: city and cost\"\"\"\n with c:\n cursor = c.cursor()\n cursor.execute(\n 'SELECT wiki.city, MAX(family_of_four) '\n 'FROM wiki LEFT OUTER JOIN numbeo ON numbeo.City = wiki.City '\n 'WHERE density_km2 < 1500')\n return cursor.fetchall()\n\n\ndef get_lowest_single_cost(c):\n \"\"\"select the city with the lowest monthly living cost for a single person\n and a population over 300,000. Return fields: city, population, and cost\"\"\"\n with c:\n cursor = c.cursor()\n cursor.execute(\n 'SELECT wiki.city, MIN(single_person) '\n 'FROM wiki LEFT OUTER JOIN numbeo ON numbeo.City = wiki.City '\n 'WHERE population > 300000')\n return cursor.fetchall()\n\n\ndef get_total_area(c):\n \"\"\"select the total area in km2 of all the cities that we collected.\"\"\"\n with c:\n cursor = c.cursor()\n cursor.execute(\n 'SELECT SUM(area_km2) '\n 'FROM wiki')\n # this returns a tuple in a list, so let's index in to get the number\n return cursor.fetchall()[0][0]\n\n\ndef get_avg_family_cost(c):\n \"\"\"select the average monthly living cost for a family of four\"\"\"\n with c:\n cursor = c.cursor()\n cursor.execute(\n 'SELECT AVG(family_of_four) '\n 'FROM numbeo')\n # this returns a tuple in a list, so let's index in to get the number\n return cursor.fetchall()[0][0]\n\n\ndef get_avg_single_cost(c):\n \"\"\"select the average monthly living cost for a single person\"\"\"\n with c:\n cursor = c.cursor()\n cursor.execute(\n 'SELECT AVG(single_person) '\n 'FROM numbeo')\n # this returns a tuple in a list, so let's index in to get the number\n return cursor.fetchall()[0][0]\n\n\ndef get_avg_sg_cost_NRW(c):\n \"\"\"select the average monthly living cost for a single person in the state\n of North Rhine-Westphalia\"\"\"\n with c:\n cursor = c.cursor()\n cursor.execute(\n 'SELECT AVG(single_person) '\n 'FROM wiki LEFT OUTER JOIN numbeo ON numbeo.City = wiki.City '\n 'WHERE state=\"North Rhine-Westphalia\"')\n # this returns a tuple in a list, so let's index in to get the number\n return cursor.fetchall()[0][0]\n\n\ndef get_avg_fam_cost_NRW(c):\n \"\"\"select the average monthly living cost for a single person in the state\n of North Rhine-Westphalia\"\"\"\n with c:\n cursor = c.cursor()\n cursor.execute(\n 'SELECT AVG(family_of_four) '\n 'FROM wiki LEFT OUTER JOIN numbeo ON numbeo.City = wiki.City '\n 'WHERE state=\"North Rhine-Westphalia\"')\n # this returns a tuple in a list, so let's index in to get the number\n return cursor.fetchall()[0][0]\n\n\nif __name__ == '__main__':\n c = sqlite3.connect('tables')\n top_5 = get_top_density_low_cost(c)\n top_5_cities = [data[0] for data in top_5]\n max_cost = get_highest_family_cost(c)\n min_cost = get_lowest_single_cost(c)\n total_area = get_total_area(c)\n avg_fam_cost = get_avg_family_cost(c)\n avg_fam_NRW_cost = get_avg_fam_cost_NRW(c)\n avg_sg_cost = get_avg_single_cost(c)\n avg_sg_NRW_cost = get_avg_sg_cost_NRW(c)\n print(\"Five highest density cities that have a cost of living below 750\"\n \"euro per month for a single person:\")\n print(\", \".join(top_5_cities), linesep)\n print(\"City with the highest monthly cost of living for a family of four \"\n \"and density below 1500 people per square km:\")\n print(\"%s. Cost in euro: %s\" % max_cost[0], linesep)\n print(\"City with the lowest monthly cost of living for a single person \"\n \"and population over 300,000:\")\n print(\"%s. Cost in euro: %s\" % min_cost[0], linesep)\n print(\"Total area of the cities in our database in square kilometres:\")\n print(\"%.2f\" % total_area, linesep)\n print(\"Average monthly family cost in euro: %.2f\" % avg_fam_cost)\n print(\"Average monthly family person cost in euro in NRW: %.2f\" %\n avg_fam_NRW_cost)\n print(\"Average monthly single person cost in euro: %.2f\" % avg_sg_cost)\n print(\"Average monthly single person cost in euro in NRW: %.2f\" %\n avg_sg_NRW_cost)\n","sub_path":"texttech/sql_queries.py","file_name":"sql_queries.py","file_ext":"py","file_size_in_byte":5198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"570994144","text":"# coding=utf-8\nimport logging\nfrom os import makedirs, path, getcwd\n\nSPACE = '\\n'\n\nLEVELS = {\n 'debug': logging.DEBUG,\n 'info': logging.INFO,\n 'warning': logging.WARNING,\n 'error': logging.ERROR,\n 'critical': logging.CRITICAL,\n}\nMODE = 'a'\n\n\ndef setting_up_logger(file_logging_level, console_logging_level, file_path):\n file_logging_level = str(file_logging_level).lower()\n console_logging_level = str(console_logging_level).lower()\n if file_logging_level not in LEVELS or console_logging_level not in LEVELS:\n print(\"Error log logging: The values to be inserted are: \", LEVELS.keys())\n exit()\n\n create_log_file = False\n folder_path = path.split(file_path)[0]\n if not path.isdir(folder_path) and folder_path != '':\n makedirs(folder_path)\n create_log_file = True\n # set up logging to file - see previous section for more details\n format_logging = \"%(asctime)s\\t[%(filename)s %(funcName)s %(lineno)d] %(msecs)d %(name)s [%(levelname)-5.5s] \" \\\n \"%(message)s\"\n logging.basicConfig(level=LEVELS[file_logging_level], format=format_logging, datefmt='%d/%m/%Y %I:%M:%S %p',\n filename=file_path, filemode=MODE)\n # define a Handler which writes INFO messages or higher to the sys.stderr\n console = logging.StreamHandler()\n console.setLevel(LEVELS[console_logging_level])\n # set a format which is simpler for console use\n formatter = logging.Formatter(format_logging)\n # tell the handler to use this format\n console.setFormatter(formatter)\n # add the handler to the root logger\n logging.getLogger('').addHandler(console)\n\n if create_log_file:\n logging.debug(SPACE + \"Create '{0}' folder in {1} path\".format(folder_path, getcwd()))\n logging.info(SPACE + \"Create '{0}' folder in {1} path\".format(folder_path, getcwd()))\n\n\ndef change_logger_file(old_logger_file_path, new_logger_file_path, mode='debug'):\n mode = mode.lower()\n if mode not in LEVELS:\n print(\"Error log logging: The values to be inserted are: \", LEVELS.keys())\n exit()\n\n new_logger_folder_path = path.split(new_logger_file_path)[0]\n if not path.isdir(new_logger_folder_path):\n makedirs(new_logger_folder_path)\n logging.debug(SPACE + \"Create '{0}' folder in {1} path\".format(new_logger_folder_path, getcwd()))\n logging.info(SPACE + \"Create '{0}' folder in {1} path\".format(new_logger_folder_path, getcwd()))\n\n log = logging.getLogger()\n logger_change_flag = False\n old_log_handler = None\n for log_handler in log.handlers:\n if isinstance(log_handler, logging.FileHandler) and \\\n (old_logger_file_path == \"\" or str(log_handler.baseFilename).endswith(old_logger_file_path)):\n old_logger_file_path = log_handler.baseFilename\n old_log_handler = log_handler\n logger_change_flag = True\n break\n\n if not logger_change_flag:\n logging.debug(SPACE + \"{} file that not exist\".format(old_logger_file_path))\n if old_log_handler is not None:\n old_log_handler.stream.close()\n log.removeHandler(old_log_handler)\n file_handler = logging.FileHandler(new_logger_file_path)\n formatter = logging.Formatter(\"%(asctime)s\\t[%(filename)s %(funcName)s %(lineno)d] %(msecs)d %(name)s \"\n \"[%(levelname)-5.5s] %(message)s\")\n file_handler.setFormatter(formatter)\n log.addHandler(file_handler)\n","sub_path":"hw2/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"464367337","text":"#function that takes in a BST and a target int value and returns \n#closest value to that target value contained in the BST\n\n#recursive method\n\ndef closestBST(tree, target):\n return closestBSTHelper(tree, target, float(\"inf\")) #initializing the helper method\n\ndef closestBSTHelper(tree, target, closest):\n if tree is None:\n return closest\n if abs(target - closest) > abs(target - tree.value):\n closest = tree.value\n if target < tree.value:\n return closestBSTHelper(tree.left, target, closest)\n elif target > tree.value:\n return closestBSTHelper(tree.right, target, closest)\n else:\n return closest\n\n#iterative method\ndef closestBst(tree, target):\n return closestBstHelper(tree, target, float(\"inf\"))\n\ndef closestBstHelper(tree, target, closest):\n while tree is not None:\n currenNode = tree\n if abs(target - closest) > abs(target - currentNode.value):\n closest = currentNode.value\n if target < currentNode.value:\n currentNode = currenNode.left\n elif target > currentNode.value:\n currenNode = currentNode.right\n else:\n break\n return closest \n","sub_path":"closestvalue_bst/closest_target.py","file_name":"closest_target.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"73049782","text":"from creature import *\nfrom rules import *\nimport random\n\n\n\n\nclass Boid(Creatures):\n '''\n this is the simple boid it moves around, looks around,\n and tries to avoid inconveniencing others by bumping into them\n '''\n boidlist = list()\n def __init__(self, size, speed):\n super().__init__(size, speed)\n self.percievedboids = []\n self.percievedhoiks = []\n self.percievedobjects = []\n self.boidlist.append(self)\n self.color = LIGHTBLUE\n self.maxspeed = speed\n self.radius = size\n self.awareness = size*10\n self.death = False\n\n\n def move(self):\n super()._move()\n #populate the lists\n self.percievedhoiks = [b for b in Hoik.hoiklist if 0 < (self.pos-b.pos).magnitude() < self.awareness]\n self.percievedboids = [b for b in self.boidlist if 0 < (self.pos-b.pos).magnitude() < self.awareness]\n self.percievedobjects = [b for b in Hindrance.hindrancelist if 0 < (self.pos-b.pos).magnitude() < self.awareness]\n too_close = [b for b in self.percievedboids if 0 < (self.pos-b.pos).magnitude() < self.radius*2]\n too_close_hoik = [b for b in self.percievedhoiks if 0 < (self.pos-b.pos).magnitude() < self.awareness]\n too_close_object = [b for b in self.percievedobjects if 0 < ((self.pos-b.pos).magnitude()) < self.awareness]\n\n #try to GTFO if a hoik is nearby\n if too_close_hoik:\n dont_crash(self, too_close_hoik, 1)\n elif too_close:\n dont_crash(self, too_close, 0)\n #try not to smash face first into an object\n if too_close_object:\n dont_crash(self, too_close_object, 1)\n elif too_close:\n dont_crash(self, too_close, 0)\n #if you see others establish a cameraderie and follow the other guy(s)\n if self.percievedboids and not too_close_hoik:\n keep_centered(self, self.percievedboids)\n gen_direction(self, self.percievedboids)\n\n #the hoik has eaten you... you are dead... please remove thyself\n def deaths_door(self):\n self.boidlist.remove(self)\n\n\n\nclass Hoik(Boid):\n '''\n this is the hoik... he is a bastard... he tries to eat every hoik he sees\n '''\n hoiklist = list()\n def __init__(self, size, speed):\n super().__init__(size, speed)\n self.percievedboids = []\n self.hoiklist.append(self)\n self.color = RED\n self.target = None\n self.maxspeed = speed\n self.radius = size\n self.awareness = size*10\n\n def move(self):\n super()._move()\n #poplulate the lists\n self.percievedboids = [b for b in self.boidlist if 0 < (self.pos-b.pos).magnitude() < self.awareness]\n self.percievedobjects = [b for b in Hindrance.hindrancelist if 0 < (self.pos-b.pos).magnitude() < self.awareness]\n too_close_object = [b for b in self.percievedobjects if 0 < ((self.pos-b.pos).magnitude()) < self.awareness]\n\n #no one likes Harry the hindrance\n if too_close_object:\n #avoid him like the plague\n dont_crash(self, too_close_object, 0)\n elif not too_close_object:\n #it's huntingseason so all aboard\n hunt(self, self.percievedboids)\n\nclass Hindrance:\n '''\n this i a plain and stupid hinderance\n never moves\n never bites\n never gotten a hug\n avoided like a plague\n '''\n hindrancelist = list()\n def __init__(self):\n self.color = BLACK\n self.radius = OBJECTRADIUS + (random.randint(-4,3)*10)\n if not self.radius:\n self.radius += 1\n self.pos = Vector2D(random.randint(0 + self.radius, SCREEN_X - self.radius), random.randint(0 + self.radius, SCREEN_Y - self.radius))\n\n\n\n","sub_path":"Oblig 2/src/boid.py","file_name":"boid.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"342215324","text":"from django.urls import path\n\nfrom .views import (\n DashboardView, \n NovoPedido, \n NovoItemPedido,\n ListaVendas,\n EditaPedido,\n ExcluiPedido,\n ExcluiItemPedido, \n EditaItemPedido\n)\n\nurlpatterns = [\n\n path('', ListaVendas.as_view(), name='lista-vendas'),\n path('novo-pedido/', NovoPedido.as_view(), name='novo-pedido'),\n path('edita-pedido/<int:venda>/', EditaPedido.as_view(), name='edita-pedido'),\n path('exclui-pedido/<int:venda>/', ExcluiPedido.as_view(), name='exclui-pedido'),\n path('novo-item-pedido/<int:venda>/', NovoItemPedido.as_view(), name='novo-item-pedido'),\n path('edita-item-pedido/<int:item>/', EditaItemPedido.as_view(), name='edita-item-pedido'),\n path('exclui-item-pedido/<int:item>/', ExcluiItemPedido.as_view(), name='exclui-item-pedido'),\n path('dashboard/', DashboardView.as_view(), name='dashboard')\n]\n","sub_path":"vendas/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"252795545","text":"#!/usr/bin/env python\n\"\"\"Read suppliers from the API endpoint and write to target API.\n\nUsage:\n index_suppliers_from_api.py <api_endpoint> <api_access_token>\n <source_api_endpoint> <source_api_access_token>\n [options]\n\n --serial Do not run in parallel (useful for debugging)\n --users=<PASS> Create user accounts for each supplier and set the\n passwords to PASS\n\nExample:\n ./import_suppliers_from_api.py http://api myToken http://source-api token\n\"\"\"\n\nfrom six.moves import map\n\nimport sys\nimport multiprocessing\nfrom itertools import islice\nfrom datetime import datetime\n\nfrom docopt import docopt\n\nimport dmapiclient\n\n\nCLEAN_FIELDS = {\n 'email': 'supplier-{}@user.dmdev',\n 'phoneNumber': '00000{}'\n\n}\n\n\ndef request_suppliers(api_url, api_access_token, page=1):\n\n data_client = dmapiclient.DataAPIClient(\n api_url,\n api_access_token\n )\n\n while page:\n suppliers_page = data_client.find_suppliers(page=page)\n\n for supplier in suppliers_page['suppliers']:\n yield supplier\n\n if suppliers_page['links'].get('next'):\n page += 1\n else:\n return\n\n\ndef print_progress(counter, start_time):\n if counter % 100 == 0:\n time_delta = datetime.utcnow() - start_time\n print(\"{} in {} ({}/s)\".format(counter,\n time_delta,\n counter / time_delta.total_seconds()))\n\n\nclass SupplierUpdater(object):\n def __init__(self, endpoint, access_token, user_password=None):\n self.endpoint = endpoint\n self.access_token = access_token\n self.user_password = user_password\n\n def __call__(self, supplier):\n client = dmapiclient.DataAPIClient(self.endpoint, self.access_token)\n try:\n client.import_supplier(supplier['id'],\n self.clean_data(supplier, supplier['id']))\n except dmapiclient.APIError as e:\n print(\"ERROR: {}. {} not imported\".format(str(e),\n supplier.get('id')),\n file=sys.stderr)\n return False\n\n if not self.user_password:\n return True\n\n try:\n client.create_user({\n 'role': 'supplier',\n 'emailAddress': CLEAN_FIELDS['email'].format(\n supplier['id']\n ),\n 'password': self.user_password,\n 'name': supplier['name'],\n 'supplierId': supplier['id'],\n })\n except dmapiclient.APIError as e:\n if e.status_code != 409:\n print(\"ERROR: {}. Could not create user account for {}\".format(\n str(e), supplier.get('id')), file=sys.stderr)\n return False\n\n return True\n\n def clean_data(self, supplier, *format_data):\n for field in supplier:\n if field in CLEAN_FIELDS:\n supplier[field] = CLEAN_FIELDS[field].format(*format_data)\n elif isinstance(supplier[field], dict):\n supplier[field] = self.clean_data(supplier[field].copy(),\n *format_data)\n elif isinstance(supplier[field], list):\n supplier[field] = [\n self.clean_data(item.copy(), *format_data)\n if isinstance(item, dict) else item\n for item in supplier[field]\n ]\n return supplier\n\n\ndef do_index(api_url, api_access_token, source_api_url,\n source_api_access_token, serial, users):\n print(\"Data API URL: {}\".format(api_url))\n print(\"Source Data API URL: {}\".format(source_api_url))\n\n if serial:\n pool = None\n mapper = map\n else:\n pool = multiprocessing.Pool(10)\n mapper = pool.imap\n\n indexer = SupplierUpdater(api_url, api_access_token, user_password=users)\n\n counter = 0\n start_time = datetime.utcnow()\n status = True\n\n iter_suppliers = request_suppliers(source_api_url, source_api_access_token)\n suppliers = True\n while suppliers:\n try:\n suppliers = list(islice(iter_suppliers, 0, 100))\n except dmapiclient.APIError as e:\n print('API request failed: {}'.format(str(e)), file=sys.stderr)\n return False\n\n for result in mapper(indexer, suppliers):\n counter += 1\n status = status and result\n print_progress(counter, start_time)\n\n return status\n\n print_progress(counter, start_time)\n\nif __name__ == \"__main__\":\n arguments = docopt(__doc__)\n ok = do_index(\n api_url=arguments['<api_endpoint>'],\n api_access_token=arguments['<api_access_token>'],\n source_api_url=arguments['<source_api_endpoint>'],\n source_api_access_token=arguments['<source_api_access_token>'],\n serial=arguments['--serial'],\n users=arguments['--users'],\n )\n\n if not ok:\n sys.exit(1)\n","sub_path":"scripts/import_suppliers_from_api.py","file_name":"import_suppliers_from_api.py","file_ext":"py","file_size_in_byte":5098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"590673379","text":"\nimport json\nimport pandas as pd\nimport numpy as np\n\nimport os.path as path\n\nresults_file = r'C:\\workspace\\dissertation\\dissertation\\robust-optimization\\results\\results_20170128_dcc.json'\n\n# %%\n\nwith open(results_file, 'r') as infile:\n json_records = infile.readlines()\n\nportfolios = list()\nstatuses = list()\nparameters = list()\nreturn_params= list()\nfor r in json_records:\n # Skip blank lines.\n if len(r) <= 1:\n continue\n r = json.loads(r)\n portfolios.append(np.fromstring(r['result']['portfolio'], sep=' '))\n statuses.append(r['result']['status'])\n parameters.append(r['kwargs']['portfolio'])\n return_params.append(r['kwargs']['returns'])\n\n\n# %%\nstatuses = np.array(statuses)\nportfolios = np.array(portfolios)\nparameters = pd.DataFrame(parameters)\nreturn_params = pd.DataFrame(return_params)\n\n# %%\n# Comment out results_dir until run time to reduce risk of overwriting data if script is run again with new inputs.\n#results_dir = r'C:\\workspace\\dissertation\\dissertation\\robust-optimization\\results\\20170128-sensitivity-analysis'\nnp.save(path.join(results_dir, 'portfolios.npy'), portfolios)\nnp.save(path.join(results_dir, 'statuses.npy'), statuses)\nparameters.to_csv(path.join(results_dir, 'parameters.csv'), index=False)\nreturn_params.to_csv(path.join(results_dir, 'return_parameters.csv'), index=False)\n","sub_path":"robust-optimization/scripts/chapter5/load_sensitivity_analysis.py","file_name":"load_sensitivity_analysis.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"26114036","text":"\"\"\"Decorates command lines with docker arguments.\"\"\"\n\nfrom plumbum import local\n\n\nclass Decorator: # noqa\n @classmethod\n def _get_docker_volume_list(cls, get_config, prefix=\"\"):\n volume_list = get_config('DOCKER/volume_list', [])\n volume_map = get_config('/DOCKER/volume_map', {})\n return (\n [prefix + \"%s:%s\" % (x, x) for x in volume_list] +\n [prefix + \"%s:%s\" % key_val for key_val in volume_map.items()]\n )\n\n @classmethod\n def _get_docker_volumes_from_list(cls, get_config, prefix=\"\"):\n volumes_from_list = get_config('DOCKER/volumes_from_list', [])\n return (\n [prefix + \"%s\" % x for x in volumes_from_list]\n )\n\n @classmethod\n def _get_docker_variable_list(cls, get_config, prefix=\"\"):\n variable_list = get_config('/DOCKER/variable_list', [])\n variable_map = get_config('/ENVIRONMENT/variable_map', {})\n variable_map.update(get_config('/DOCKER/variable_map', []))\n\n return (\n [prefix + \"%s\" % x for x in variable_list] +\n [\n prefix + \"%s=%s\" % key_val\n for key_val in variable_map.items()\n ]\n )\n\n @classmethod\n def _get_linked_container_list(cls, get_config, prefix=\"\"):\n return [prefix + \"%s\" % x for x in get_config('/DOCKER/link_list', [])]\n\n @classmethod\n def get_docker_args(cls, get_config, extra_options):\n \"\"\"\n Get docker args.\n\n The docker args precede the command which is run\n inside the docker.\n \"\"\"\n return (\n [\n 'run',\n '--rm',\n ] +\n extra_options +\n cls._get_docker_variable_list(get_config, '--env=') +\n cls._get_docker_volume_list(get_config, '--volume=') +\n cls._get_docker_volumes_from_list(get_config, '--volumes-from=') +\n cls._get_linked_container_list(get_config, '--link=') +\n get_config('/DOCKER/extra_options', []) +\n [\n get_config('/DOCKER/image'),\n ]\n )\n\n def add_arguments(self, decorated, parser): # noqa\n parser.add_argument(\n '--non-interactive',\n action='store_true',\n help=\"Run docker calls without -i and -t\"\n )\n\n def handle(self, decorated, non_interactive, **kwargs): # noqa\n decorated.opt_non_interactive = non_interactive\n\n def modify_args(self, decorated, args, cwd): # noqa\n is_enabled = decorated.get_config('/DOCKER/enabled', False)\n if is_enabled == \"False\" or not is_enabled:\n return args, cwd\n\n extra_options = []\n if not decorated.opt_non_interactive:\n extra_options.extend(['-i', '-t'])\n if cwd:\n extra_options.extend(['-w', cwd])\n if hasattr(decorated, \"docker_options\"):\n extra_options.extend(decorated.docker_options)\n\n new_args = (\n ['docker'] +\n self.get_docker_args(decorated.get_config, extra_options) +\n args\n )\n return new_args, local.cwd\n","sub_path":"dodo_commands/extra/standard_commands/decorators/docker.py","file_name":"docker.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"334876662","text":"from rl_package.ppo_vanilla.ppo import ppo_algorithm\nfrom rl_package.utils.standard_nn_architectures import ActorCriticDense\nimport gym\n\nif __name__ == \"__main__\":\n env = gym.make('CartPole-v0')\n env.seed(1)\n for i in range(5):\n model = ActorCriticDense(env, MLP_LAYERS=[64,64], MLP_ACTIVATIONS=['relu', 'relu'], ACTOR_FINAL_ACTIVATION=None, NN_INIT='orthogonal', ACTOR_DIST_LOG_STD=0.0, seed=i)\n model_output = ppo_algorithm(env, model, NUM_ENV=8,\n TOTAL_STEPS=400000, NSTEPS=64, MINIBATCH_SIZE=128, N_EPOCH=30,\n CLIP_PARAM=0.1, VF_COEF=0.5, ENT_COEF=0.001,\n GAMMA=0.99, LAMBDA=0.95,\n LEARNING_RATE=1e-3,\n PRINT_FREQ=8000, N_TEST_ENV=96, \n SAVE_RESULTS=True, FILE_PATH='rl_package/ppo_vanilla/cartpole_results/', LOG_FILE_NAME='log'+str(i), SAVE_MODEL=True, MODEL_FILE_NAME='model'+str(i),\n SEED=i)","sub_path":"rl_package/ppo_vanilla/CartPole-v0.py","file_name":"CartPole-v0.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"125671281","text":"load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\nload(\":genrule_repository.bzl\", \"genrule_repository\")\nload(\":repository_locations.bzl\", \"REPOSITORY_LOCATIONS\")\nload(\":target_recipes.bzl\", \"TARGET_RECIPES\")\nload(\n \"@bazel_tools//tools/cpp:windows_cc_configure.bzl\",\n \"find_vc_path\",\n \"setup_vc_env_vars\",\n)\nload(\"@bazel_tools//tools/cpp:lib_cc_configure.bzl\", \"get_env_var\")\n\n# go version for rules_go\nGO_VERSION = \"1.10.4\"\n\n# Make all contents of an external repository accessible under a filegroup. Used for external HTTP\n# archives, e.g. cares.\nBUILD_ALL_CONTENT = \"\"\"filegroup(name = \"all\", srcs = glob([\"**\"]), visibility = [\"//visibility:public\"])\"\"\"\n\ndef _repository_impl(name, **kwargs):\n # `existing_rule_keys` contains the names of repositories that have already\n # been defined in the Bazel workspace. By skipping repos with existing keys,\n # users can override dependency versions by using standard Bazel repository\n # rules in their WORKSPACE files.\n existing_rule_keys = native.existing_rules().keys()\n if name in existing_rule_keys:\n # This repository has already been defined, probably because the user\n # wants to override the version. Do nothing.\n return\n\n loc_key = kwargs.pop(\"repository_key\", name)\n location = REPOSITORY_LOCATIONS[loc_key]\n\n # Git tags are mutable. We want to depend on commit IDs instead. Give the\n # user a useful error if they accidentally specify a tag.\n if \"tag\" in location:\n fail(\n \"Refusing to depend on Git tag %r for external dependency %r: use 'commit' instead.\" %\n (location[\"tag\"], name),\n )\n\n # HTTP tarball at a given URL. Add a BUILD file if requested.\n http_archive(\n name = name,\n urls = location[\"urls\"],\n sha256 = location[\"sha256\"],\n strip_prefix = location.get(\"strip_prefix\", \"\"),\n **kwargs\n )\n\ndef _build_recipe_repository_impl(ctxt):\n # on Windows, all deps use rules_foreign_cc\n if ctxt.os.name.upper().startswith(\"WINDOWS\"):\n return\n\n # modify the recipes list based on the build context\n recipes = _apply_dep_blacklist(ctxt, ctxt.attr.recipes)\n\n # Setup the build directory with links to the relevant files.\n ctxt.symlink(Label(\"//bazel:repositories.sh\"), \"repositories.sh\")\n ctxt.symlink(\n Label(\"//ci/build_container:build_and_install_deps.sh\"),\n \"build_and_install_deps.sh\",\n )\n ctxt.symlink(Label(\"//ci/build_container:recipe_wrapper.sh\"), \"recipe_wrapper.sh\")\n ctxt.symlink(Label(\"//ci/build_container:Makefile\"), \"Makefile\")\n for r in recipes:\n ctxt.symlink(\n Label(\"//ci/build_container/build_recipes:\" + r + \".sh\"),\n \"build_recipes/\" + r + \".sh\",\n )\n ctxt.symlink(Label(\"//ci/prebuilt:BUILD\"), \"BUILD\")\n\n # Run the build script.\n print(\"Fetching external dependencies...\")\n result = ctxt.execute(\n [\"./repositories.sh\"] + recipes,\n quiet = False,\n )\n print(result.stdout)\n print(result.stderr)\n print(\"External dep build exited with return code: %d\" % result.return_code)\n if result.return_code != 0:\n print(\"\\033[31;1m\\033[48;5;226m External dependency build failed, check above log \" +\n \"for errors and ensure all prerequisites at \" +\n \"https://github.com/alibaba/sentinel-cpp/blob/master/bazel/README.md#quick-start-bazel-build-for-developers are met.\")\n\n # This error message doesn't appear to the user :( https://github.com/bazelbuild/bazel/issues/3683\n fail(\"External dep build failed\")\n\ndef _default_sentinel_build_config_impl(ctx):\n ctx.file(\"WORKSPACE\", \"\")\n ctx.file(\"BUILD.bazel\", \"\")\n ctx.symlink(ctx.attr.config, \"extensions_build_config.bzl\")\n\n_default_sentinel_build_config = repository_rule(\n implementation = _default_sentinel_build_config_impl,\n)\n\ndef sentinel_dependencies(path = \"@sentinel_deps//\", skip_targets = []):\n sentinel_repository = repository_rule(\n implementation = _build_recipe_repository_impl,\n environ = [\n \"CC\",\n \"CXX\",\n \"CFLAGS\",\n \"CXXFLAGS\",\n \"LD_LIBRARY_PATH\",\n ],\n # Don't pretend we're in the sandbox, we do some evil stuff with sentinel_dep_cache.\n local = True,\n attrs = {\n \"recipes\": attr.string_list(),\n },\n )\n\n # Ideally, we wouldn't have a single repository target for all dependencies, but instead one per\n # dependency, as suggested in #747. However, it's much faster to build all deps under a single\n # recursive make job and single make jobserver.\n recipes = depset()\n for t in TARGET_RECIPES:\n if t not in skip_targets:\n recipes += depset([TARGET_RECIPES[t]])\n\n sentinel_repository(\n name = \"sentinel_deps\",\n recipes = recipes.to_list(),\n )\n\n for t in TARGET_RECIPES:\n if t not in skip_targets:\n native.bind(\n name = t,\n actual = path + \":\" + t,\n )\n\n # Treat sentinel's overall build config as an external repo, so projects that\n # build sentinel as a subcomponent can easily override the config.\n if \"sentinel_build_config\" not in native.existing_rules().keys():\n _default_sentinel_build_config(name = \"sentinel_build_config\")\n\n # Setup rules_foreign_cc\n _foreign_cc_dependencies()\n\n # The long repo names (`com_github_fmtlib_fmt` instead of `fmtlib`) are\n # semi-standard in the Bazel community, intended to avoid both duplicate\n # dependencies and name conflicts.\n _com_github_fmtlib_fmt()\n _com_github_google_benchmark()\n _com_google_googletest()\n\n # Used for bundling gcovr into a relocatable .par file.\n _repository_impl(\"subpar\")\n\ndef _com_github_fmtlib_fmt():\n _repository_impl(\n name = \"com_github_fmtlib_fmt\",\n build_file = \"@sentinel//bazel/external:fmtlib.BUILD\",\n )\n native.bind(\n name = \"fmtlib\",\n actual = \"@com_github_fmtlib_fmt//:fmtlib\",\n )\n\ndef _com_github_google_benchmark():\n location = REPOSITORY_LOCATIONS[\"com_github_google_benchmark\"]\n http_archive(\n name = \"com_github_google_benchmark\",\n **location\n )\n native.bind(\n name = \"benchmark\",\n actual = \"@com_github_google_benchmark//:benchmark\",\n )\n\ndef _com_google_googletest():\n _repository_impl(\"com_google_googletest\")\n native.bind(\n name = \"googletest\",\n actual = \"@com_google_googletest//:gtest\",\n )\n\ndef _foreign_cc_dependencies():\n _repository_impl(\"rules_foreign_cc\")\n\ndef _apply_dep_blacklist(ctxt, recipes):\n newlist = []\n skip_list = []\n for t in recipes:\n if t not in skip_list:\n newlist.append(t)\n return newlist\n\ndef _is_linux(ctxt):\n return ctxt.os.name == \"linux\"\n\ndef _is_arch(ctxt, arch):\n res = ctxt.execute([\"uname\", \"-m\"])\n return arch in res.stdout\n\ndef _is_linux_ppc(ctxt):\n return _is_linux(ctxt) and _is_arch(ctxt, \"ppc\")\n\ndef _is_linux_x86_64(ctxt):\n return _is_linux(ctxt) and _is_arch(ctxt, \"x86_64\")\n","sub_path":"bazel/repositories.bzl","file_name":"repositories.bzl","file_ext":"bzl","file_size_in_byte":7119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"210616794","text":"# !/usr/bin/python\r\nimport pymysql\r\n\r\nclass DatabaseConnection_zeniel:\r\n\r\n def __init__(self):\r\n try:\r\n self.connection = pymysql.connect(host='uml.kr', port=3366,\r\n user='just_aster_dba', password='!just716811',\r\n db='just', charset='utf8')\r\n\r\n self.connection.autocommit = True\r\n self.cursor = self.connection.cursor()\r\n\r\n print('DB connection completed')\r\n\r\n except:\r\n print('Cannot connect to Database')\r\n\r\n def create_table(self):\r\n create_table_query = \"CREATE TABLE `facebook_crawled_just` (\\\r\n `no_index` INT(11) NOT NULL AUTO_INCREMENT,\\\r\n `insertedTime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\\\r\n `userName` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `birthday` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `birthday_luna` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `sex` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `bloodType` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `addr` VARCHAR(100) NULL DEFAULT NULL,\\\r\n `facebookUrl` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `website` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `snsLink` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `religion` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `cellPhone` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `introduceText` VARCHAR(200) NULL DEFAULT NULL,\\\r\n `profileTotCnt` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `profileTotInfo` VARCHAR(300) NULL DEFAULT NULL,\\\r\n `friendsCnt` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `likePeopleCnt` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `imgLikeCnt` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `vodCnt` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `picCnt` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `tscore` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `cscore` VARCHAR(50) NULL DEFAULT NULL,\\\r\n `mscore` VARCHAR(50) NULL DEFAULT NULL,\\\r\n PRIMARY KEY (`no_index`)\\\r\n )\\\r\n ENGINE=InnoDB\\\r\n ;\"\r\n\r\n self.cursor.execute(create_table_query)\r\n self.connection.close()\r\n\r\n\r\n # INSERT facebook\r\n def insert_record_origin_version(self, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15, f16, f17,\r\n f18, f19, f20, f21, f22, f23, f24, f25, f26, f27, f28, f29, f30, f31, f32, f33,\r\n f34, f35, f36, f37, f38, f39, f40, f41, f42, f43, f44, f45,\r\n f46, f47, f48, f49, f50, f51, f52, f53, f54, f55, f56, f57, f58, f59, f60):\r\n try:\r\n insert_command = \"INSERT INTO facebook_crawled_just (\" \\\r\n \"userName, facebookUrl, basicInfo_tot, contctInfo_tot, websiteSnsInfo, \" \\\r\n \"introduceText, profileTotCnt, profileTotInfo, friendsCnt, likePeopleCnt, \" \\\r\n \"imgLikeCnt, vodCnt, picCnt, fb_tscore, fb_cscore, \" \\\r\n \"fb_mscore, detail_info, allFrndCnt,knowEachFrnd,latestAddFrnd,\" \\\r\n \"univFrnd,homeFrnd,homeTwnFrnd,fllwerCnt,likeHobbyAllCnt,\" \\\r\n \"movieLikeCnt,tvLikeCnt,musicLikeCnt,bookLikeCnt,sportsTemaLikeCnt,\" \\\r\n \"foodPlaceCnt,appAndGamesCnt,visitedPlc,visitedCity,recentVisitPlc,\" \\\r\n \"evntCnt,eventContents,sawItCnt,sawMovieCnt,sawMovieContentCnt,\" \\\r\n \"sawMovieTitle,replyCnt,replyContents,articleLikeCnt,articleShareCnt,\" \\\r\n \"avgReplyCnt,avgReplyAndReply,gdExpssCnt,avgGdExpssRate,aboutInfoCnt,\" \\\r\n \"thisMnthArticleCnt,preMnthArticleCnt,arrangeYears,\" \\\r\n \"cellPhone,addr,snsLink,website,birthday,birthday_luna,photobookCnt) VALUES('\" \\\r\n + f1 + \"','\" + f2 + \"','\" + f3 + \"','\" + f4 + \"','\" + f5 + \"','\" + f6 + \"','\" \\\r\n + f7 + \"','\" + f8 + \"','\" + f9 + \"','\" + f10 + \"','\" + f11 + \"','\" + f12 + \"','\" \\\r\n + f13 + \"','\" + f14 + \"','\" + f15 + \"', '\" + f16 + \"', '\" + f17 + \"','\" \\\r\n + f18 + \"','\" + f19 + \"','\" + f20 + \"','\" + f21 + \"','\" + f22 + \"','\" + f23 + \"','\" \\\r\n + f24 + \"','\" + f25 + \"','\" + f26 + \"','\" + f27 + \"','\" + f28 + \"','\" + f29 + \"','\" \\\r\n + f30 + \"','\" + f31 + \"','\" + f32 + \"', '\" + f33 + \"', '\" + f34 + \"','\" + f35 + \"','\" \\\r\n + f36 + \"','\" + f37 + \"','\" + f38 + \"', '\" + f39 + \"', '\" + f40 + \"','\" + f41 + \"','\" \\\r\n + f42 + \"','\" + f43 + \"','\" + f44 + \"', '\" + f45 + \"', '\" + f46 + \"', '\" + f47 + \"', '\" \\\r\n + f48 + \"', '\" + f49 + \"', '\" + f50 + \"', '\" + f51 + \"', '\" + f52 + \"', '\" + f53 + \"', '\" \\\r\n + f54 + \"','\" + f55 + \"','\" + f56 + \"','\" + f57 + \"','\" + f58 + \"','\" + f59 + \"', '\" + f60 + \"' )\"\r\n\r\n print(insert_command)\r\n self.cursor.execute(insert_command)\r\n self.connection.commit()\r\n self.connection.close()\r\n\r\n except Exception as e:\r\n print(e)\r\n\r\n # UPDATE\r\n def update_ReviewCnt(self, f1, f2):\r\n print('update_ReviewCnt')\r\n try:\r\n insert_command = \"UPDATE facebook_crawled_just SET \" \\\r\n \"reviewsCnt='\" + f1 + \"' WHERE facebookUrl='\" + f2 + \"'; \"\r\n\r\n print(insert_command)\r\n self.cursor.execute(insert_command)\r\n self.connection.commit()\r\n\r\n print('DB insert of reviewsCnt success')\r\n self.connection.close()\r\n\r\n except Exception as e:\r\n print(e)\r\n\r\n # UPDATE\r\n def update_FollowCnt(self, f1, f2):\r\n print('update_FollowerCnt')\r\n try:\r\n insert_command = \"UPDATE facebook_crawled_just SET \" \\\r\n \"fllwCnt='\" + f1 + \"' WHERE facebookUrl='\" + f2 + \"'; \"\r\n\r\n print(insert_command)\r\n self.cursor.execute(insert_command)\r\n self.connection.commit()\r\n\r\n print('DB insert of fllwCnt success')\r\n self.connection.close()\r\n\r\n except Exception as e:\r\n print(e)\r\n\r\n # UPDATE\r\n def update_PhotoLikeCmntCnt(self, f1, f2, f3):\r\n print('update_PhotoLikeCmntCnt')\r\n try:\r\n insert_command = \"UPDATE facebook_crawled_just SET \" \\\r\n \"phdatgulCnt='\" + f1 + \"', photoLikeCnt='\" + f2 + \"' WHERE facebookUrl='\" + f3 + \"'; \"\r\n\r\n print(insert_command)\r\n self.cursor.execute(insert_command)\r\n self.connection.commit()\r\n\r\n print('DB insert of update_PhotoLikeCmntCnt success')\r\n self.connection.close()\r\n\r\n except Exception as e:\r\n print(e)\r\n","sub_path":"aster_dev_201808/aster879/crawling_modules_v1804/crawlerBot_package_JUST_TEST/NotUsingJSONDATAType/mysqlConnection_zeniel_fail_20181011.py","file_name":"mysqlConnection_zeniel_fail_20181011.py","file_ext":"py","file_size_in_byte":7534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"112873554","text":"# -*- coding: utf-8 -*-\r\nimport numpy as np # linear algebra\r\nimport pandas as pd \r\n\r\n# Input data files are available in the read-only \"../input/\" directory\r\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\r\n\r\nimport os\r\nfor dirname, _, filenames in os.walk('/kaggle/input'):\r\n for filename in filenames:\r\n print(os.path.join(dirname, filename))\r\n\r\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \r\n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session\r\n\r\n\"\"\"The cell above imports the necessary libaries and programs.\"\"\"\r\n\r\nimport pandas as pd\r\nCO2 = \"/co2_emission.csv\"\r\ntable = pd.read_csv(CO2)\r\ntable\r\n\r\n\"\"\"Importing the CO2 emissions data set, which is sorted by country for various year, and assigning it to \"table\".\"\"\"\r\n\r\ntble = table[table['Entity'] == 'United States']\r\ntble\r\n\r\n\"\"\"Isolating the CO2 emissions data in table format only for the United States and assigning it to \"tble\".\"\"\"\r\n\r\n# Commented out IPython magic to ensure Python compatibility.\r\npd.plotting.register_matplotlib_converters()\r\nimport matplotlib.pyplot as plt\r\n# %matplotlib inline\r\nimport seaborn as sns\r\nprint(\"Setup Complete\")\r\n\r\n\"\"\"Importing the libraries necessary for plotting graphs.\"\"\"\r\n\r\nplt.figure(figsize=(150,100))\r\nplt.title(\"Annual CO2 Emissions in the USA\", fontsize = 400)\r\nsns.barplot(x=tble['Year'], y=tble['Annual CO₂ emissions (tonnes )'])\r\nplt.ylabel(\"Annual CO₂ emissions (tonnes )\", fontsize = 250)\r\nplt.xlabel(\"Year\", fontsize = 250)\r\n\r\n\"\"\"Plotting the isolated CO2 emissions data for the United States from the previous code cell labeled \"tble\". The coloration is random and has no significance.\"\"\"\r\n\r\ntina = table[table['Entity'] == 'China']\r\ntina\r\n\r\n\"\"\"Isolating the CO2 emissions data in table format only for China and assigning it to \"tina\".\"\"\"\r\n\r\nplt.figure(figsize=(150,100))\r\nplt.title(\"Annual CO2 Emissions in China\", fontsize = 400)\r\nsns.barplot(x=tina['Year'], y=tina['Annual CO₂ emissions (tonnes )'])\r\nplt.ylabel(\"Annual CO₂ emissions (tonnes )\", fontsize = 250)\r\nplt.xlabel(\"Year\", fontsize = 250)\r\n\r\n\"\"\"Plotting the isolated CO2 emissions data for China from the previous code cell labeled \"tina\". The coloration is random and has no significance.\"\"\"\r\n\r\ntoby = table[table['Entity'] == 'EU-28']\r\ntoby\r\n\r\n\"\"\"Isolating the CO2 emissions data in table format only for the EU-28 and assigning it to \"toby\".\"\"\"\r\n\r\nplt.figure(figsize=(150,100))\r\nplt.title(\"Annual CO2 Emissions in the EU-28\", fontsize = 400)\r\nsns.barplot(x=toby['Year'], y=toby['Annual CO₂ emissions (tonnes )'])\r\nplt.ylabel(\"Annual CO₂ emissions (tonnes )\", fontsize = 250)\r\nplt.xlabel(\"Year\", fontsize = 250)\r\n\r\n\"\"\"Plotting the isolated CO2 emissions data for the EU-28 from the previous code cell labeled \"toby\". The coloration is random and has no significance.\"\"\"\r\n\r\ntbl = table[table['Year'] == 2017].sort_values(by='Annual CO₂ emissions (tonnes )', ascending=False).drop(index = 20619, columns= ['Code','Year'])\r\ntbl.head(12)\r\n\r\n\"\"\"Isolating the CO2 emissions data for 2017 in table format, and sorting it by 'Annual CO2 emissions (tonnes)' in descedning order. I assigned this to 'tbl'. Now there is only one row for each entity whereas before, there were multple rows for each entity. This condenses the data to just one year, but allows us to visuzlize the largest CO2 emitters.\"\"\"\r\n\r\ntbl['Annual CO₂ emissions (tonnes )'].value_counts().head(10).plot.pie()\r\nplt.axis('equal')\r\n\r\n\"\"\"A visualization of the largest CO2 emitters in 2017. I used the table from the previous code cell titled 'tbl'.\"\"\"\r\n\r\ntbl['Annual CO₂ emissions (tonnes )'].value_counts().head(10).plot.pie()\r\nplt.legend(labels= tbl['Entity'], loc= 'best')","sub_path":"Day 2/carbon emission/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"324954794","text":"import pyrebase\r\n\r\nconfig = {\r\n\t\"apiKey\": \"AIzaSyCQMH5ByN78Uhd7JNCpPwbGkDh_fFCmbRs\",\r\n \"authDomain\": \"dummy-b7637.firebaseapp.com\",\r\n \"databaseURL\": \"https://dummy-b7637.firebaseio.com\",\r\n \"projectId\": \"dummy-b7637\",\r\n \"storageBucket\": \"dummy-b7637.appspot.com\",\r\n \"messagingSenderId\": \"374974448752\",\r\n \"appId\": \"1:374974448752:web:ba7428ad8c78af12b0e0b5\",\r\n \"measurementId\": \"G-9625M7LTPZ\"\r\n}\r\n\r\nfirebase = pyrebase.initialize_app(config)\r\n\r\ndb = firebase.database()\r\n\r\nfrom flask import *\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef basic():\r\n\tif request.method == 'POST':\r\n\t\tif request.form['submit'] == 'add':\r\n\r\n\t\t\tname = request.form['name']\r\n\t\t\tdb.child(\"todo\").push(name)\r\n\t\t\ttodo = db.child(\"todo\").get()\r\n\t\t\tto = todo.val()\r\n\t\t\treturn render_template('index.html', t=to.values())\r\n\t\telif request.form['submit'] == 'delete':\r\n\t\t\tdb.child(\"todo\").remove()\r\n\t\treturn render_template('index.html')\r\n\treturn render_template('index.html')\r\n\r\nif __name__ == '__main__':\r\n\tapp.run(debug=True)\r\n","sub_path":"app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"369103268","text":"import serial\nfrom DDPGAgent import Agent\nfrom Environment import Env\nimport gym\nimport numpy as np\nfrom Rule import Rule\nimport matplotlib.pyplot as plt\n\nif __name__ == '__main__':\n env = Env()\n rule = Rule()\n agent = Agent(rule)\n score_list = []\n MAS_list = []\n for e in range(rule.n_episode):\n score = 0\n done = False\n obs = env.Ardread()\n while not done:\n action = agent.get_action(obs)\n for _ in range(3):\n obs_,reward,done = env.step(action)\n score += reward\n agent.replaybuffer.store(obs,action,reward,obs_,done)\n agent.learn()\n obs = obs_\n #episode is ended.\n env.restart()\n agent.save()\n score_list.append(score)\n average_score = np.mean(score_list[-50:])\n MAS_list.append(average_score)\n print(f'{e+1}/{rule.n_episode} # Score: {score:.1f}, Average Score: {average_score:.1f}')\n env.end()\n plt.plot(np.arange(rule.n_episode), MAS_list)\n plt.xlabel('Epochs')\n plt.ylabel('Moving Average Score')\n plt.title('Aruduino RL Car')\n plt.show()","sub_path":"Python/DDPG/Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"122104929","text":"#-------------------------------------------------------\r\n# Name: main.py\r\n# Purpose: Education purposes only, copying will be subject to plagiarism\r\n# Author: Syed Natiq Ali Abidi\r\n# Created: 23-April-2021\r\n# Updated: 25-April-2021\r\n#-------------------------------------------------------\r\n\r\n\r\nfrom typing import Tuple, List\r\nfrom cards import Card\r\nfrom deck import Deck\r\nfrom player import Player\r\n\r\ndef play_cards_two(difficulty: str) -> Tuple[Player, Player]:\r\n \"\"\"\r\n Creates a deck and splits it amongst 2 players.\r\n\r\n <difficulty> can be Easy, Medium or Hard.\r\n\r\n \"\"\"\r\n d = Deck()\r\n d.populate()\r\n d.randomize()\r\n\r\n name1 = input(\"Enter player 1 name: \")\r\n name2 = input(\"Enter player 2 name: \")\r\n\r\n p1 = Player(name1)\r\n p2 = Player(name2)\r\n\r\n deck1, deck2 = d.split_half(difficulty)\r\n\r\n p1.player_deck.extend(deck1)\r\n p2.player_deck.extend(deck2)\r\n\r\n return p1, p2\r\n\r\ndef game_menu(p: Player) -> str:\r\n \"\"\"\r\n A simple text UI for the game's menu.\r\n \"\"\"\r\n\r\n print(\"-------------------------------------------------------\")\r\n user_choice = input(\"What would \" + str(p.name) + \" like to do?:\\n\"\r\n \"1 = 'Show deck'\\n\"\r\n \"2 = 'Play your turn'\\n\"\r\n \"q = quit\\nSelection: \")\r\n print(\"-------------------------------------------------------\")\r\n\r\n return user_choice\r\n\r\ndef game_choice(p: Player) -> List:\r\n \"\"\"\r\n Return True or False based on the player's choice.\r\n \"\"\"\r\n\r\n user_choice = game_menu(p)\r\n\r\n if user_choice == \"1\":\r\n print(p.player_deck)\r\n return [True]\r\n\r\n elif user_choice == \"2\":\r\n suit, val = input(\"Enter your card's suit: \"), input(\"Enter your card's value: \")\r\n c = Card(suit, val)\r\n print(\"\\n\")\r\n move = p.play_move(suit, val)\r\n print(\"\\n\")\r\n\r\n if move:\r\n final = [False]\r\n final.append(c)\r\n return final\r\n else:\r\n return [True]\r\n\r\n elif user_choice == \"q\":\r\n print(\"Game over!\")\r\n return [False]\r\n\r\n\r\ndef play(size: int, difficulty: str) -> None:\r\n \"\"\"\r\n Play the game, <size> represents the player size for this game.\r\n\r\n Rules:\r\n - Same suits, higher value gets you a point.\r\n - Different suits will always result in 0 points for both players\r\n regardless of card power.\r\n\r\n \"\"\"\r\n if size == 2:\r\n\r\n p1, p2 = play_cards_two(difficulty)\r\n\r\n curr_round = 1\r\n\r\n playing = True\r\n\r\n while (len(p1.player_deck) != 0 or len(p2.player_deck)) != 0 and playing:\r\n\r\n print(\"\\nRound \" + str(curr_round) + \" has started!\" + \"\\n\")\r\n\r\n curr_round += 1\r\n\r\n p1_choice = True\r\n p2_choice = True\r\n\r\n choice_list = []\r\n\r\n while p1_choice:\r\n\r\n choice = game_choice(p1)\r\n\r\n if choice != [] and choice is not None:\r\n if choice[0] == False and len(choice) == 2:\r\n choice_list.append(choice[1])\r\n p1_choice = False\r\n elif choice[0] == False and len(choice) == 1:\r\n p1_choice = False\r\n playing = False\r\n else:\r\n print(\"\\nInvalid Selection\\n\")\r\n\r\n while p2_choice:\r\n\r\n choice = game_choice(p2)\r\n\r\n if choice != [] and choice is not None:\r\n if choice[0] == False and len(choice) == 2:\r\n choice_list.append(choice[1])\r\n p2_choice = False\r\n\r\n elif choice[0] == False and len(choice) == 1:\r\n p2_choice = False\r\n playing = False\r\n else:\r\n print(\"\\nInvalid Selection\\n\")\r\n\r\n if choice_list != [] and not len(choice_list) < 2:\r\n if choice_list[0].suit == choice_list[1].suit:\r\n if choice_list[0].compare(choice_list[1]):\r\n print(\"----------------------------------------------------\"\r\n \"---\")\r\n print(\"\\n\" + str(p1.name) + \" has won the round and \"\r\n \"secure a point!\\n\")\r\n p1.points += 1\r\n\r\n elif choice_list[1].compare(choice_list[0]):\r\n print(\"---------------------------------------------------\"\r\n \"----\")\r\n print(\"\\n\" + str(p2.name) + \" has won the round \"\r\n \"and secure a point!\\n\")\r\n p2.points += 1\r\n else:\r\n print(\"-------------------------------------------------------\")\r\n print(\"\\nWe have different suits so no points awarded!\\n\")\r\n print(\"-------------------------------------------------------\")\r\n\r\n if p1.points > p2.points:\r\n print(\"Congratulations! \" + str(p1.name) + \" has won the game with \"\r\n + str(p1.points) + \" point(s)!\" )\r\n elif p2.points > p1.points:\r\n print(\"Congratulations! \" + str(p2.name) + \" has won the game with \"\r\n + str(p2.points) + \" point(s)!\" )\r\n elif p1.points == p2.points and playing:\r\n print(\"The game has ended with a tie!\")\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n play(2, \"Easy\") # Change this to support more player size and different\r\n # difficulty.\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"84972736","text":"from pymodbus.client.sync import ModbusSerialClient as ModbusClient\nimport time\n\nclient = ModbusClient(method='rtu', port='/dev/ttyUSB0', timeout=10, stopbits = 1, bytesize = 8, parity='N', baudrate= 9600, functioncode=3)\nclient.connect()\n\n\nif __name__ == \"__main__\":\n # for i in range(4000,4500):\n \n rr = client.read_holding_registers(4132,count=1,unit=0x01)\n print(rr.registers[0])\n \n ","sub_path":"modbus/py_mod_energy.py","file_name":"py_mod_energy.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"263555541","text":"import random\nimport re\nimport textwrap\nimport collections\n\nfrom stepic_plugins.base import BaseQuiz\nfrom stepic_plugins.exceptions import FormatError\nfrom stepic_plugins.quizzes.executable_base import JailedCodeFailed, Arena, settings, run\n\n\nclass Languages(object):\n PYTHON = 'python3'\n CPP = 'c++'\n HASKELL = 'haskell'\n JAVA = 'java'\n OCTAVE = 'octave'\n all = [PYTHON, CPP, HASKELL, JAVA, OCTAVE]\n compiled = [CPP, HASKELL]\n interpreted = [PYTHON, OCTAVE]\n default_templates = {\n PYTHON: \"# put your code here\",\n CPP: \"#include <iostream>\\n\\nint main() {\\n // put your code here\\n return 0;\\n}\",\n HASKELL: \"main :: IO ()\\n-- put your code here\",\n JAVA: \"class Main {\\n public static void main(String[] args) {\\n // put your code here\\n }\\n}\",\n OCTAVE: \"# put your code here\",\n }\n\n\nclass CodeQuiz(BaseQuiz):\n name = 'code'\n\n class Schemas:\n source = {\n 'code': str,\n 'execution_time_limit': int,\n 'execution_memory_limit': int,\n 'templates_data': str\n }\n\n reply = {\n 'language': str,\n 'code': str\n }\n\n FAILED_TEST_MESSAGE = \"Failed test #{test_number}. {message}\"\n\n CE_MESSAGE = \"Compilation error\"\n TL_MESSAGE = \"Time limit exceeded\"\n RE_MESSAGE = \"Run time error:\\n{}\"\n WA_MESSAGE = \"Wrong answer\"\n\n def __init__(self, source, supplementary=None):\n super().__init__(source)\n self.code = source.code\n self.execution_time_limit = source.execution_time_limit\n self.execution_memory_limit = source.execution_memory_limit\n self.templates_data = source.templates_data\n self.tests = supplementary['tests'] if supplementary else None\n\n def async_init(self):\n try:\n tests = self.get_tests()\n dataset, output = self.run_edyrun('sample')\n if not dataset:\n dataset, clue = tests[0]\n output = self.run_edyrun('solve', data=dataset)\n except JailedCodeFailed as e:\n raise FormatError(str(e))\n return {\n 'tests': tests,\n 'options': {\n 'execution_time_limit': self.execution_time_limit,\n 'execution_memory_limit': self.execution_memory_limit,\n 'code_templates': self.code_templates,\n 'sample_dataset': dataset,\n 'sample_output': output\n }\n }\n\n def set_supplementary(self, supplementary):\n self.tests = supplementary\n\n def clean_reply(self, reply, dataset):\n if reply.language not in self.available_languages:\n raise FormatError(\"Unknown language: \" + reply.language)\n return reply\n\n def check(self, reply, clue, throw=False):\n with Arena() as arena:\n runner = CodeRunner(arena, reply.code, reply.language, self.limits)\n if not runner.compilation_success:\n hint = \"{message}\\n{stderr}\".format(\n message=self.CE_MESSAGE,\n stderr=runner.compilation_result.stderr.decode()\n )\n return 0, hint\n\n for i, (dataset, clue) in enumerate(self.tests):\n test_number = i + 1\n result = runner.run(dataset)\n if result.status != 0:\n if result.time_limit_exceeded:\n message = self.TL_MESSAGE\n else:\n message = self.RE_MESSAGE.format(result.stderr.decode())\n hint = self.FAILED_TEST_MESSAGE.format(\n test_number=test_number,\n message=message\n )\n return False, hint\n\n reply = result.stdout.decode().strip()\n result = self.score_one_test(reply, clue)\n if result[0] != 1:\n hint = self.FAILED_TEST_MESSAGE.format(\n test_number=test_number,\n message=result[1] or self.WA_MESSAGE\n )\n return False, hint\n\n return True\n\n @property\n def code_templates(self):\n \"\"\"Extracts language templates from text\n\n ::python3\n print(\"hello world\")\n\n ::haskell\n main = putStrLin \"hello, world\"\n\n If empty template specified, then use default template for this language\n If no templates at all, then returns default templates for all supported languages\n \"\"\"\n\n one_of_languages = '|'.join(l if l != 'c++' else r'c\\+\\+' for l in Languages.all)\n pattern = r'^::[ \\t\\r\\f\\v]*(' + one_of_languages + r')[ \\t\\r\\f\\v]*$'\n parts = re.split(pattern, self.templates_data, flags=re.MULTILINE)\n parts = parts[1:]\n languages = parts[::2]\n # remove starting/ending empty lines, common indentation and ensure trailing newline\n templates = [textwrap.dedent(t).strip() for t in parts[1::2]]\n assert (len(languages) == len(templates))\n templates = dict(zip(languages, templates)) or {language: '' for language in Languages.all}\n for language, template in templates.items():\n if template:\n templates[language] = template + '\\n'\n else:\n templates[language] = Languages.default_templates[language]\n return templates\n\n @property\n def limits(self):\n return {\"TIME\": self.execution_time_limit,\n \"MEMORY\": self.execution_memory_limit * 1024 * 1024}\n\n @property\n def available_languages(self):\n return self.code_templates.keys()\n\n def score_one_test(self, reply, clue):\n try:\n data = (reply, clue)\n score, hint = self.run_edyrun('score', data=data)\n return score, hint\n except (JailedCodeFailed, ValueError, TypeError):\n return False, ''\n\n def get_tests(self):\n tests = self.run_edyrun(\"generate\", seed=random.randrange(10 ** 6))\n if not isinstance(tests, collections.Sequence):\n raise FormatError(\"Generate should return a Sequence\")\n if len(tests) > 100:\n raise FormatError(\"Too many tests\")\n if len(tests) == 0:\n raise FormatError(\"Empty test sequence\")\n for element in tests:\n if not (isinstance(element, collections.Sequence) and len(element) == 2):\n raise FormatError(\"Test format is wrong\")\n dataset, clue = element\n if not (isinstance(dataset, str)):\n raise FormatError(\"Test format is wrong\")\n\n for dataset, clue in tests:\n msg = \"{{}}\\ndataset: {}\\nclue: {}\".format(dataset, clue)\n reply = self.run_edyrun('solve', data=dataset)\n result = self.score_one_test(reply, clue)\n if result[0] != 1:\n raise FormatError(msg.format(\"Test is broken\"))\n\n return tests\n\n def run_edyrun(self, command, data=None, **kwargs):\n files = []\n return run(command, self.code, data, files, type='code', **kwargs)\n\n\nclass CodeRunner(object):\n def __init__(self, arena, source, language, limits):\n self.arena = arena\n self.source = source\n self.language = language\n self.limits = limits\n self.compilation_success, self.compilation_result = self._compile()\n\n def run(self, dataset):\n assert self.compilation_success\n if self.language in Languages.compiled:\n #just run `./main`\n return self.arena.run_code('user_code', stdin=dataset, limits=self.limits)\n elif self.language == Languages.JAVA:\n #run `java Main` from compiled Main.class\n java_limits, args = get_limits_for_java(self.limits)\n return self.arena.run_code('run_java', command_argv=args + ['Main'],\n stdin=dataset, limits=java_limits)\n elif self.language in Languages.interpreted:\n #run `python self.source`\n limits = dict(self.limits)\n if self.language in settings.INTERPRETERS:\n limits[\"MEMORY\"] += settings.INTERPRETERS[self.language]['reserved_memory']\n\n return self.arena.run_code('run_' + self.language, code=self.source, argv=[], files=[],\n stdin=dataset, limits=limits)\n assert False, 'unknown language: ' + self.language\n\n def _compile(self):\n if self.language in settings.COMPILERS:\n source_file_name = 'main.{}'.format(settings.COMPILERS[self.language]['ext'])\n compilation_result = self.arena.run_code('compile_' + self.language,\n command_argv=[source_file_name],\n files=[(self.source, source_file_name)])\n return compilation_result.status == 0, compilation_result\n else:\n return True, None\n\n\ndef get_limits_for_java(limits):\n java_limits = dict(limits)\n #for gc\n java_limits[\"CAN_FORK\"] = True\n #setrlimit does not work because of MAP_NORESERVE, use -Xmx instead\n java_limits[\"MEMORY\"] = None\n xmxk = limits[\"MEMORY\"] // 1024\n return java_limits, [\"-Xmx{}k\".format(xmxk), \"-Xss8m\"]\n","sub_path":"stepic_plugins/quizzes/code/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"407899394","text":"opcaomenu = 1\r\nwhile opcaomenu != '0':\r\n print('Escolha uma opção:')\r\n print('1. Tutorial')\r\n print('2. Jogar')\r\n print('0. Sair')\r\n opcaomenu = input('A opção escolhida é: ')\r\n if opcaomenu == '1':\r\n print('TUTORIAL:')\r\n print('Cada jogador escolhe se quer Par ou Ímpar e em seguida, um número,.')\r\n print('A soma dos números será feita e então será feita a verificação se o número é par ou ímpar.')\r\n print('O jogador que escolher a correspondente vencerá.')\r\n elif opcaomenu == '2':\r\n nomejogador1 = input('Digite o nome do primeiro jogador: ')\r\n nomejogador2 = input('Digite o nome do segundo jogador: ')\r\n escolhajogador1 = input('{}, você quer Par ou Ímpar? '.format(nomejogador1))\r\n if escolhajogador1 == 'Par':\r\n escolhajogador2 = 'Ímpar'\r\n elif escolhajogador1 == 'Ímpar':\r\n escolhajogador2 = 'Par'\r\n else:\r\n escolhajogador1 = 'Inválida!'\r\n escolhajogador2 = 'Inválida!'\r\n print('Escolha inválida!')\r\n numerojogador1 = int(input('{}, digite um número: '.format(nomejogador1)))\r\n numerojogador2 = int(input('{}, digite um número: '.format(nomejogador2)))\r\n numerofinal = numerojogador1 + numerojogador2\r\n if escolhajogador1 == 'Inválida!':\r\n print('Escolha de {} é inválida!'.format(nomejogador1))\r\n elif escolhajogador2 == 'Inválida!':\r\n print('Escolha de {} é inválida!'.format(nomejogador2))\r\n if numerofinal % 2 == 0 and escolhajogador1 == 'Par':\r\n print('{} é Par, logo {} ganhou!'.format(numerofinal, nomejogador1))\r\n elif numerofinal % 2 == 0 and escolhajogador2 == 'Par':\r\n print('{} é Par, logo {} ganhou!'.format(numerofinal, nomejogador2))\r\n elif numerofinal % 2 != 0 and escolhajogador1 == 'Ímpar':\r\n print('{} é Ímpar, logo {} ganhou!'.format(numerofinal, nomejogador1))\r\n elif numerofinal % 2 != 0 and escolhajogador2 == 'Ímpar':\r\n print('{} é Ímpar, logo {} ganhou!'.format(numerofinal, nomejogador2))\r\n else:\r\n print('Ocorreu um erro!')\r\nelse:\r\n print('Até mais!')\r\n","sub_path":"parouimpar.py","file_name":"parouimpar.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"425574128","text":"print(\"\"\"The teams are\n1. Hawks\n2. Celtics\n3. Nets\n4. Hornets\n5. Bulls\n6. Cavaliers\n7. Mavericks\n8. Nuggets\n9. Pistons\n10. Warriors\n11. Rockets\n12. Pacers\n13. Clippers\n14. Lakers\n15. Grizzlies\n16. Heat\n17. Bucks\n18. Timberwolves\n19. Pelicans\n20. Knicks\n21. Thunder\n22. Magic\n23. Sixers\n24. Suns\n25. Blazers\n26. Kings\n27. Spurs\n28. Raptors\n29. Jazz\n\"\"\")\nimport pandas as pd\n\nteam = input(\"Type what team you want to see stats for : \")\nwebsite = \"http://www.nba.com/\" + team + \"/stats\"\ndf = pd.read_html(website)\n\ntable1 = df[1]\n#\n\nrows = []\nfor row in table1.iterrows():\n rows.append(row)\n\nplayerlist = list(rows)\n\nplayer12 = str(rows[12])\n\n# (12, Player Lonzo Ball2•Guard\n# G 36\n# PTS 10.2\n# FG 3.9\n# FG% 35.6%\n# 3P% 30.3%\n# FT% 48%\n# OREB 1.3\n# DREB 5.8\n# REB 7.1\n# AST 7.1\n# STL 1.5\n# TO 2.7\n# PF 2.2\n# Name: 12, dtype: object)\nnames = []\nstats = []\ntexts = []\n\nfor player in playerlist:\n player = str(player)\n\n newplayerlist = player.splitlines()\n name = newplayerlist[0]\n names.append(name)\n stat = newplayerlist[1:14]\n stats.append(stat)\n print(newplayerlist[0])\n\nnumberchosen = int(input('Press what number you want to see stats for : '))\nprint(names[numberchosen])\nplayerchosen = stats[numberchosen]\nfor line in playerchosen:\n print(line)\n","sub_path":"webscrapenba.py","file_name":"webscrapenba.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"268100353","text":"### Pandas and Numpy Work Together\n# Import numpy\nimport numpy as np\n\n# Create array of DataFrame values: np_vals\nnp_vals = df.values\n\n# Create new array of base 10 logarithm values: np_vals_log10\nnp_vals_log10 = np.log10(np_vals)\n\n# Create array of new DataFrame by passing df to np.log10(): df_log10\ndf_log10 = np.log10(df)\n\n# Print original and new data containers\n[print(x, 'has type', type(eval(x))) for x in ['np_vals', 'np_vals_log10', 'df', 'df_log10']]\n\n\n\n### Combine list with zip and store in DF\n# Zip the 2 lists together into one list of (key,value) tuples: zipped\nzipped = list(zip(list_keys, list_values))\n\n# Inspect the list using print()\nprint(zipped)\n\n# Build a dictionary with the zipped list: data\ndata = dict(zipped)\n\n# Build and inspect a DataFrame from the dictionary: df\ndf = pd.DataFrame(data)\nprint(df)\n\n# Build a list of labels: list_labels\nlist_labels = ['year','artist','song','chart weeks']\n\n# Assign the list of labels to the columns attribute: df.columns\ndf.columns = list_labels\n\n# Make a string with the value 'PA': state\nstate = 'PA'\n\n# Construct a dictionary: data\ndata = {'state': state, 'city': cities}\n\n# Construct a DataFrame from dictionary data: df\ndf = pd.DataFrame(data)\n\n# Print the DataFrame\nprint(df)","sub_path":"pandas/foundations.py","file_name":"foundations.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"234494229","text":"# Mooyo Mooyo\n# Flood fill\n\ndef new_array():\n return [[False for _ in range(10)] for _ in range(n)]\n\n# 개수세기\ndef dfs(x, y):\n ck[x][y] = True\n ret = 1\n \n for i in range(4):\n xx, yy = x + dx[i], y + dy[i]\n if 0 <= xx< n and 0<= yy < 10 and not ck[xx][yy] and m[x][y] == m[xx][yy]:\n ret += dfs(xx, yy) \n return ret\n\n# val을 0으로 채우기\ndef dfs2(x, y, val):\n ck2[x][y] = True\n m[x][y] = '0'\n\n for i in range(4):\n xx, yy = x + dx[i], y + dy[i]\n if 0 <= xx< n and 0<= yy < 10 and not ck2[xx][yy] and m[xx][yy] == val:\n dfs2(xx, yy, val)\n \n\n# 내리기\ndef down():\n for i in range(10):\n tmp = []\n for j in range(n):\n if m[j][i] != '0':\n tmp.append(m[j][i])\n\n for j in range(n - len(tmp)):\n m[j][i] = '0'\n\n for j in range(n-len(tmp), n):\n m[j][i] = tmp[j - (n - len(tmp))]\n\n# down 보다 메모리 더 많이 사용\ndef down2():\n for i in range(10):\n tmp = []\n for j in range(n):\n if m[j][i] != '0':\n tmp.append(m[j][i])\n m[j][i] = '0'\n\n for k in range(n - 1, 0, -1):\n if tmp:\n m[k][i] = tmp.pop()\n\nn, k = map(int, input().split())\nm = [list(input()) for _ in range(n)]\ndx, dy = [0, 1, 0, -1], [1, 0, -1, 0]\n\nwhile True:\n exist = False\n ck = new_array() # 계속 갱신 되어야 함 (같은 숫자 확인)\n ck2 = new_array() # 계속 갱신 되어야 함 (0으로 바뀌지 않은 숫자 확인)\n\n for i in range(n):\n for j in range(10):\n\n if m[i][j] != '0' and not ck[i][j]:\n res = dfs(i, j) # 반환값: 총 크기\n if res >= k:\n dfs2(i, j, m[i][j])\n exist = True\n\n if not exist: break\n\n down()\n\nfor i in m:\n print(''.join(i))","sub_path":"fastcampus/test/ch03/graph/16768.py","file_name":"16768.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"155693452","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 13 16:01:19 2018\n\n@author: Lin_Shien\n\"\"\"\n\n\"\"\"\nfastNlMeansDenoising(src, h, templateWindowSize, searchWindowSize) \nh : Parameter regulating filter strength for luminance component. Bigger h value perfectly removes noise but also removes image details, \n smaller h value preserves details but also preserves some noise.\n\ntemplateWindowSize : Size in pixels of the template patch that is used to compute weights. \n Should be odd. Recommended value 7 pixels\n\nsearchWindowSize : Size in pixels of the window that is used to compute weighted average for given pixel. \n Should be odd. Affect performance linearly: greater searchWindowsSize - greater denoising time. Recommended value 21 pixels\n\"\"\"\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.cluster import KMeans\n\n\ndef find_bound(array, center, coord_y): # 用來找center的上下界\n up = 0\n down = 0\n \n for i in range(1, center): # 往上找\n if array[center - i, coord_y] != array[center, coord_y]:\n break\n up+=1\n \n for i in range(1, array.shape[0] - center):\n if array[center + i, coord_y] != array[center, coord_y]:\n break\n down+=1\n return up , down\n\n\ndef find_lineSeg(array, direction, length): # brute force 要套用在2極化後的矩陣,\n if direction == 1:\n pre_coords = np.where(array[:, 0] == 255)[0] # from leftmost\n if (pre_coords.shape[0] - 1) < 0 : # 防止抓到空座標\n pre_coord_downmost = 0\n pre_coord_upmost = 0\n else:\n pre_coord_downmost = pre_coords[pre_coords.shape[0] - 1]\n pre_coord_upmost = pre_coords[0]\n \n for i in range(1, array.shape[1]):\n downmost_coords = np.where(array[:, i] == 255)[0] # 觀察column上最下方的255出現在哪個座標,\n if downmost_coords.shape[0] - 1 < 0: # 排除空的column\n downmost_coord = 0\n upmost_coord = 0\n else:\n downmost_coord = downmost_coords[downmost_coords.shape[0] - 1]\n upmost_coord = downmost_coords[0]\n \n if pre_coord_downmost != 0 and pre_coord_upmost != 0:\n if abs(pre_coord_downmost - downmost_coord) >= length or abs(pre_coord_upmost - upmost_coord) >= length: # 如果跟上一次的座標差很多,代表交界在上一座標\n return i - 1 # return previous index\n pre_coord_downmost = downmost_coord\n pre_coord_upmost = upmost_coord\n \n \n if direction == -1:\n pre_coords = np.where(array[:, array.shape[1] - 1] == 255)[0] # from rightmost \n if (pre_coords.shape[0] - 1) < 0 :\n pre_coord_downmost = 0\n pre_coord_upmost = 0\n else:\n pre_coord_downmost = pre_coords[pre_coords.shape[0] - 1]\n pre_coord_upmost = pre_coords[0]\n for i in range(1, array.shape[1]):\n downmost_coords = np.where(array[:, array.shape[1] - i] == 255)[0]\n if downmost_coords.shape[0] - 1 < 0:\n downmost_coord = 0\n upmost_coord = 0\n else:\n downmost_coord = downmost_coords[downmost_coords.shape[0] - 1]\n upmost_coord = downmost_coords[0]\n \n if pre_coord_downmost != 0 and pre_coord_upmost != 0: \n if abs(pre_coord_downmost - downmost_coord) >= length or abs(pre_coord_upmost - upmost_coord) >= length and not (pre_coord_downmost == pre_coord_upmost == 0):\n return array.shape[1] - i + 1 \n pre_coord_downmost = downmost_coord\n pre_coord_upmost = upmost_coord\n \n \ndef find_bound_of_letter(array, coordOfMeans):\n k = len(coordOfMeans)\n \n center_list = list()\n for i in range(k):\n y, x = coordOfMeans[i]\n x = int(round(x))\n center_list.append((x, y))\n \n letter_bounds = list()\n for i in range(k):\n if i != 0:\n left_bound = center_list[i][0] - find_lineSeg(array[:, 0 : center_list[i][0] + 1], -1, 5)\n right_bound = center_list[i][0] + find_lineSeg(array[:, center_list[i][0] : center_list[i + 1][0]], 1, 5)\n letter_bounds.append((left_bound, right_bound))\n \n if i == 0:\n left_bound = find_lineSeg(array[:, 0 : center_list[i][0] + 1], -1, 5)\n right_bound = center_list[i][0] + find_lineSeg(array[:, center_list[i][0] : center_list[i + 1][0]], 1, 5)\n letter_bounds.append((left_bound, right_bound))\n return letter_bounds\n \n\n\"\"\"\neliminateCurve:\n read a page, and eliminate the curve or line segment on the captcha image,\n return type is a denoised image with one channel\n\"\"\"\ndef eliminateCurve(img_name, brightness): \n images_detect = cv2.imread(img_name)\n lenOfYcoord = images_detect.shape[1]\n\n\n gray = cv2.cvtColor(images_detect, cv2.COLOR_BGR2GRAY) # 先轉灰階\n gray = cv2.fastNlMeansDenoising(gray, None, brightness, 7, 21) # 降躁 \n ret, binary = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY_INV) # 轉成二值圖,無原地修改\n clone = binary.copy()\n clone_unchanged = binary.copy()\n\n #return clone_unchanged\n binary[:, find_lineSeg(clone_unchanged, 1, 2) : find_lineSeg(clone_unchanged, -1, 2)] = 0 # 把字母部分挖空\n line_segment = np.where(binary == 255) # 找出線段的���置,一個tuple代表x軸,另一個代表y軸座標\n '''\n plt.scatter(line_segment[1], lenOfYcoord - line_segment[0], s = 100, c = 'red', label = 'Cluster 1')\n plt.ylim(ymin=0) \n plt.ylim(ymax=lenOfYcoord) \n plt.show()\n '''\n X = np.array([line_segment[1]])\n Y = lenOfYcoord - np.array(line_segment[0]) # 換成左下方為起點的座標\n\n poly_reg= PolynomialFeatures(degree = 2) # degree 2 hypothesis, 其實就是 ... + ax + b = y....\n X_ = poly_reg.fit_transform(X.T) # 跟data X fit => compute 就是把 x 值帶入hypothesis中\n regr = LinearRegression() # regreesion\n regr.fit(X_, Y) \n\n X2 = np.array([[i for i in range(0, images_detect.shape[1])]]) # 預測座標\n X2_ = poly_reg.fit_transform(X2.T) # 算出函數值\n\n newimg = clone\n\n for ele in np.column_stack([regr.predict(X2_).round(0), X2[0] ,]):\n pos = lenOfYcoord - int(ele[0]) # coordinate y (array x) \n up, down = find_bound(newimg, pos, int(ele[1]))\n \n if (up + down + 1) < 7: # 太細代表這column只有線段而已\n newimg[pos - up : pos + down + 1, int(ele[1])] = 255 - newimg[pos - up : pos + down + 1, int(ele[1])] # slice要多+1\n else:\n newimg[pos - 2 : pos + 2, int(ele[1])] = 255 - newimg[pos - 2 : pos + 2, int(ele[1])]\n \n\n #newimg = cv2.fastNlMeansDenoising(newimg, None, 40, 7, 21) # 降躁會使字母擴大 => distortion\n '''\n plt.subplot(121)\n plt.imshow(gray)\n plt.subplot(122)\n plt.imshow(newimg)\n plt.show()\n '''\n return newimg.copy()\n\n\ndef takeOne(elem):\n return elem[0]\n\n\ndef deleCurve_and_create_pieces(img): \n h, w = img.shape # x, y軸的大小\n\n Data_list = [(h - x, y) for x in range(h) for y in range(w) if img[x][y]] # 紀錄 pixel = 255 的點座標\n\n Data = np.array(Data_list) # 換成 len(Data_list) x 2 的矩陣\n n_clusters = 4 # k\n\n k_means = KMeans(init='k-means++', n_clusters = n_clusters)\n k_means.fit(Data) # compute k means\n k_means_labels = k_means.labels_ # 回傳每個座標屬於k means的哪一類\n k_means_cluster_centers = k_means.cluster_centers_ # 回傳 k means 的群中心 \n\n colors = ['#4EACC5', '#FF9C34', '#4E9A06', '#FF3300']\n \n #plt.figure()\n #plt.hold(True)\n \n for k, col in zip(range(n_clusters), colors):\n my_members = k_means_labels == k # 找除屬於k類的座標,存成bool矩陣\n cluster_center = k_means_cluster_centers[k]\n '''\n plt.plot(Data[my_members, 1], Data[my_members, 0], 'w', # 畫出資料\n markerfacecolor = col, marker = '.')\n \n plt.plot(cluster_center[1], cluster_center[0], 'o', markerfacecolor = col, # 畫出群中心\n markeredgecolor = 'k', markersize = 6)\n '''\n '''\n plt.title('KMeans') \n plt.grid(True)\n plt.show()\n '''\n center_list = list()\n for i in range(k + 1):\n y, x = k_means_cluster_centers[i]\n x = int(round(x))\n center_list.append((x, y))\n\n center_list.sort(key = takeOne) \n\n bound_r1 = int(round(abs(center_list[1][0] + center_list[0][0])) / 2) \n bound_l1 = int(round(abs(center_list[0][0] * 2 - bound_r1)))\n\n #print(bound_l1)\n #print(bound_r1)\n\n bound_r2 = int(round(abs(center_list[1][0] + center_list[2][0])) / 2) \n bound_l2 = bound_r1\n\n #print(bound_l2)\n #print(bound_r2)\n\n bound_r3 = int(round(abs(center_list[2][0] + center_list[3][0])) / 2) \n bound_l3 = bound_r2\n\n #print(bound_l3)\n #print(bound_r3)\n\n bound_r4 = int(round(abs(center_list[3][0] * 2 - bound_r3))) \n bound_l4 = bound_r3\n\n #print(bound_l4)\n #print(bound_r4)\n \n cv2.imwrite('p1.png', img[:, bound_l1 : bound_r1 + 1])\n cv2.imwrite('p2.png', img[:, bound_l2 : bound_r2 + 1])\n cv2.imwrite('p3.png', img[:, bound_l3 : bound_r3 + 1])\n cv2.imwrite('p4.png', img[:, bound_l4 : bound_r4 + 1])\n \n return img[:, bound_l1 : bound_r1 + 1], img[:, bound_l2 : bound_r2 + 1], img[:, bound_l3 : bound_r3 + 1], img[:, bound_l4 : bound_r4 + 1]\n\n","sub_path":"model/eliminate_curve.py","file_name":"eliminate_curve.py","file_ext":"py","file_size_in_byte":10243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"181322250","text":"import nltk\r\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer, TfidfVectorizer\r\nfrom sklearn.model_selection import train_test_split, cross_val_score\r\nfrom sklearn.neural_network import MLPClassifier\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.svm import LinearSVC\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.feature_extraction.text import TfidfTransformer\r\nfrom src.utils import Utils\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom nltk.corpus import stopwords\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns; sns.set()\r\nimport numpy as np\r\nimport pickle\r\nimport pandas as pd\r\nfrom mlxtend.plotting import plot_confusion_matrix\r\n\r\nnltk.download('stopwords')\r\nenglish_stemmer = nltk.stem.SnowballStemmer('english')\r\n\r\nclass StemmedCountVectorizer(CountVectorizer):\r\n def build_analyzer(self):\r\n analyzer = super(StemmedCountVectorizer, self).build_analyzer()\r\n return lambda doc: ([english_stemmer.stem(w) for w in analyzer(doc)])\r\n\r\n\r\nclass PreBuiltClassifier:\r\n classes = {'hockey': 0, 'nba': 1, 'leagueoflegends': 2, 'soccer': 3, 'funny': 4, 'movies': 5, 'anime': 6,\r\n 'Overwatch': 7, 'trees': 8, 'GlobalOffensive': 9,\r\n 'nfl': 10, 'AskReddit': 11, 'gameofthrones': 12,\r\n 'conspiracy': 13, 'worldnews': 14, 'wow': 15, 'europe': 17, 'canada': 18, 'Music': 19, 'baseball': 20}\r\n utils = Utils()\r\n stopwords = stopwords.words('english')\r\n\r\n def naive_bayes_sickit(self, df_train):\r\n \"\"\"\r\n alpha=0.005 -> 0.53\r\n alpha=0.00005 -> 0.51\r\n alpha= 0.5 -> 0.547\r\n 0.5434857142857142\r\n tf_idf:\r\n alpha =0.5 -> 0.56\r\n alpha= 0.005 -> 0.7620571428571429\r\n :param train:\r\n :param test\r\n :return:\r\n \"\"\"\r\n\r\n from sklearn.naive_bayes import MultinomialNB\r\n from sklearn.model_selection import train_test_split\r\n X_train, X_test, y_train, y_test = train_test_split(df_train['post'], df_train['class'], random_state=53)\r\n\r\n nb = Pipeline([('vect', StemmedCountVectorizer(\r\n stop_words='english', # works\r\n )),\r\n ('tfidf', TfidfTransformer(sublinear_tf=True, smooth_idf=False)),\r\n\r\n ('clf', MultinomialNB(alpha=0.25)),\r\n ])\r\n\r\n nb.fit(X_train, y_train)\r\n\r\n scores = cross_val_score(nb, X_train, y_train, cv=5)\r\n print(\"Accuracy: %0.2f (+/- %0.2f)\" % (scores.mean(), scores.std() * 2))\r\n\r\n preds = nb.predict(X_test)\r\n UTILS.generate_submission_csv(preds)\r\n print(\"Accuracy against test data:\" + str(accuracy_score(y_test, preds)))\r\n self.heatmap(preds, y_test)\r\n\r\n def linear_svc(self, df):\r\n # 0.4758008658008658\r\n # preprocessed : 0.47935064935064936\r\n\r\n from sklearn.feature_extraction.text import CountVectorizer\r\n model = LinearSVC()\r\n\r\n from sklearn.model_selection import train_test_split\r\n X_train, X_test, y_train, y_test, indices_train, indices_test = train_test_split(df['post'], df['class'],\r\n df.index,\r\n test_size=0.33, random_state=0)\r\n vect = CountVectorizer().fit(X_train)\r\n # X_train_vectorized = vect.transform(X_train)\r\n # model.fit(X_train_vectorized, y_train)\r\n nb = Pipeline([('vect', StemmedCountVectorizer(stop_words='english')),\r\n ('tfidf', TfidfTransformer(sublinear_tf=True, smooth_idf=False)),\r\n ('clf', LinearSVC()),\r\n ])\r\n nb.fit(X_train, y_train)\r\n y_pred = nb.predict(vect.transform(X_test))\r\n # UTILS.generate_submission_csv(y_pred)\r\n print(accuracy_score(y_test, y_pred))\r\n\r\n def logistic_regression(self, df):\r\n \"\"\"\r\n penalty \"l2\" -> 0.5415584415584416 cross validation (CV=5) Accuracy: 0.54 (+/- 0.01)\r\n penalty \"l1\" -> :0.5235930735930736 cross validation (CV=5) Accuracy: 0.52 (+/- 0.01)\r\n :param df:\r\n :return:\r\n \"\"\"\r\n\r\n from sklearn.model_selection import train_test_split\r\n X_train, X_test, y_train, y_test, indices_train, indices_test = train_test_split(df['post'], df['class'],\r\n df.index,\r\n test_size=0.33, random_state=0)\r\n\r\n\r\n nb = Pipeline([('vect', StemmedCountVectorizer(stop_words='english')),\r\n ('tfidf', TfidfTransformer(sublinear_tf=True, smooth_idf=False)),\r\n ('logistic-regression', LogisticRegression(penalty=\"l2\")),\r\n ])\r\n nb.fit(X_train, y_train)\r\n scores = cross_val_score(nb, X_train, y_train, cv=5)\r\n print(\"Accuracy: %0.2f (+/- %0.2f)\" % (scores.mean(), scores.std() * 2))\r\n # UTILS.generate_submission_csv(preds)\r\n preds = nb.predict(X_test)\r\n print(\"Accuracy against test data:\" + str(accuracy_score(y_test, preds)))\r\n\r\n # draw a heat map\r\n self.heatmap(preds, y_test)\r\n\r\n def heatmap(self, preds, y_test):\r\n preds_labels = np.unique(preds.tolist())\r\n print('preds_labels: ', preds_labels)\r\n conf_mat = confusion_matrix(y_test, preds, labels=np.unique(preds_labels))\r\n annot_kws = {'fontsize': 10,\r\n 'fontstyle': 'italic',\r\n 'color': \"k\",\r\n 'alpha': 0.6,\r\n 'rotation': \"vertical\",\r\n 'verticalalignment': 'center'}\r\n sns.heatmap(conf_mat, annot=True, annot_kws=annot_kws, cmap=\"YlGnBu\", fmt=\"d\", linewidths=.5)\r\n plt.ylabel('True label')\r\n plt.xlabel('Predicted label')\r\n plt.title('Confusion Matrix')\r\n plt.show()\r\n\r\n def mlp_predict_test_to_file(self, df_train, df_test):\r\n nb = Pipeline([('vect', CountVectorizer(stop_words=self.stopwords)),\r\n ('tfidf', TfidfTransformer(sublinear_tf=True, smooth_idf=False)),\r\n ('clf', MLPClassifier(verbose=True, early_stopping=True)),\r\n ])\r\n X_train, X_test, y_train, y_test = train_test_split(df_train['post'], df_train['class'], random_state=53)\r\n nb.fit(X_train, y_train)\r\n y_pred = nb.predict(X_test)\r\n # df = pd.read_pickle(\"data_test.pkl\")\r\n # data = {'post': list(df)[0], 'class': list(df)[1]}\r\n # nb.fit(df_train['post'], df_train['class'])\r\n # y_pred = nb.predict(df_test['post'])\r\n # UTILS.generate_submission_csv(y_pred)\r\n # self.heatmap(y_pred, data['class'])\r\n self.heatmap(y_pred, y_test)\r\n\r\nif __name__ == \"__main__\":\r\n UTILS = Utils()\r\n PRE_BUILD_CLASSIFIER = PreBuiltClassifier()\r\n\r\n df_train = UTILS.get_train_data()\r\n df_test = UTILS.get_test_data()\r\n\r\n # PRE_BUILD_CLASSIFIER.naive_bayes_sickit(df_train)\r\n # PRE_BUILD_CLASSIFIER.logistic_regression(df_train)\r\n PRE_BUILD_CLASSIFIER.mlp_predict_test_to_file(df_train, df_test)","sub_path":"src/prebuiltclassifier.py","file_name":"prebuiltclassifier.py","file_ext":"py","file_size_in_byte":7309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"250922155","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# NCTR, Nile Center for Technology Research\n# Copyright (C) 2011-2012 NCTR (<http://www.nctr.sd>).\n#\n##############################################################################\n\n\nfrom osv import osv\nfrom osv import fields\nfrom tools.translate import _\n\n\nclass foreign_purchase(osv.osv):\n \"\"\" \n To manage purchase orders wich related to purchase contract \"\"\"\n\n _inherit = 'purchase.order'\n _columns = {\n 'contract_id': fields.many2one('purchase.contract','Purchase Contract',readonly=True),\n\n }\n\n def action_picking_create(self,cr, uid, ids, *args):\n \"\"\"\n Override to read account id from purchase contract object\n if the purchase order related to acontract.\n\n @return: picking id \n \"\"\"\n res = {}\n account = None\n picking_obj = self.pool.get('stock.picking')\n picking_id = super(foreign_purchase, self).action_picking_create(cr, uid, ids, *args)\n picking = picking_obj.browse(cr, uid, picking_id)\n purchase_obj = picking.purchase_id\n if purchase_obj:\n if purchase_obj.purchase_type == 'foreign':\n if purchase_obj.contract_id:\n account = purchase_obj.contract_id.contract_account\n if not account:\n raise osv.except_osv(_('NO Account !'), _('no account defined for purchase foreign.'))\n else:\n res = { \n 'account_id': account.id or False,\n }\n picking.write(res)\n return picking_id\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"v_7/NISS/shamil_v3/purchase_contracts/purchase.py","file_name":"purchase.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"413982628","text":"\"\"\"\r\nModified on Feb 20 2020\r\n@author: lbg@dongseo.ac.kr \r\n\"\"\"\r\n\r\nbackground_image_filename = 'image/curve_pattern.png'\r\nsprite_image_filename = 'image/icon_speech.png'\r\n\r\nimport pygame\r\nfrom pygame.locals import *\r\nfrom sys import exit\r\nimport numpy as np\r\n \r\n# Define the colors we will use in RGB format\r\nBLACK = ( 0, 0, 0)\r\nWHITE = (255, 255, 255)\r\nBLUE = ( 0, 0, 255)\r\nGREEN = ( 0, 255, 0)\r\nRED = (255, 0, 0)\r\n\r\npygame.init()\r\nscreen = pygame.display.set_mode((640, 480), 0, 32)\r\nbackground = pygame.image.load(background_image_filename).convert()\r\nsprite = pygame.image.load(sprite_image_filename).convert_alpha()\r\nold_pt = np.array([0, 0])\r\ncur_pt = np.array([0, 0])\r\n\r\nfont= pygame.font.SysFont(\"consolas\",20) \r\npygame.display.set_caption(\"Game Title\")\r\n \r\n#Loop until the user clicks the close button.\r\ndone = False\r\nflag = None\r\nbutton = 0\r\nclock= pygame.time.Clock()\r\n \r\n# print text function\r\ndef printText(msg, color='BLACK', pos=(50,50)):\r\n textSurface = font.render(msg, True, pygame.Color(color), None)\r\n textRect = textSurface.get_rect()\r\n textRect.topleft = pos\r\n screen.blit(textSurface, textRect)\r\n\r\nwhile not done: \r\n # This limits the while loop to a max of 10 times per second.\r\n # Leave this out and we will use all CPU we can.\r\n time_passed = clock.tick(10)\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.KEYDOWN: # If user release what he pressed.\r\n pressed= pygame.key.get_pressed()\r\n buttons= [pygame.key.name(k) for k,v in enumerate(pressed) if v]\r\n flag= True\r\n elif event.type == pygame.KEYUP:# If user press any key.\r\n flag= False\r\n elif event.type == pygame.MOUSEBUTTONDOWN:\r\n button = -1 \r\n elif event.type == pygame.MOUSEBUTTONUP:\r\n button = 1 \r\n elif event.type == pygame.QUIT:\r\n done = True\r\n else:\r\n button = 0 \r\n \r\n# screen.blit(background, (0,0))\r\n# screen.blit(sprite, old_pt)\r\n time_passed_seconds = time_passed / 1000.0\r\n \r\n x, y = pygame.mouse.get_pos()\r\n cur_pt = np.array([x, y])\r\n vector_pt = cur_pt - old_pt\r\n pygame.draw.line(screen, GREEN, old_pt, cur_pt, 3)\r\n # print(\"x:\"+repr(x)+\" y:\"+repr(y))\r\n # print(cur_pt)\r\n \r\n \r\n # All drawing code happens after the for loop and but\r\n # inside the main while done==False loop.\r\n \r\n # Clear the screen and set the screen background\r\n # screen.fill(WHITE)\r\n pygame.draw.rect(screen, WHITE, (50, 50, 400, 100))\r\n\r\n # Print red text if user pressed any key.\r\n if flag== True:\r\n printText('you just key down!!','RED')\r\n printText('--> you pressed any key.','RED', (50,70))\r\n printText('Pressed Key : ' + buttons[0],'RED', (50,90))\r\n \r\n # Print blue text if user released any key.\r\n elif flag== False:\r\n printText('you just key up!!','BLUE')\r\n printText('--> released what you pressed.','BLUE', (50,70))\r\n \r\n # Print default text if user do nothing.\r\n else:\r\n printText('Please press any key.')\r\n \r\n printText(\"x:\"+repr(x)+\" y:\"+repr(y)+\" button:\"+repr(button), 'GREEN', (50,110))\r\n \r\n# vector_to_mouse = vector_to_mouse/np.linalg.norm(vector_to_mouse)\r\n# destination = Vector2( *pygame.mouse.get_pos() ) - Vector2( *sprite.get_size() )/2\r\n# vector_to_mouse = Vector2.from_points(position, destination)\r\n# vector_to_mouse.normalize()\r\n\r\n old_pt = cur_pt \r\n # Go ahead and update the screen with what we've drawn.\r\n # This MUST happen after all the other drawing commands.\r\n pygame.display.flip()\r\n pygame.display.update()\r\n\r\npygame.quit()\r\n","sub_path":"mouseKey.py","file_name":"mouseKey.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"327277181","text":"import pytest\nfrom .pages.product_page import ProductPage\nfrom .pages.basket_page import BasketPage\nfrom .pages.login_page import LoginPage\nimport time\n\nURL_PRODUCT_NewYear = [\"http://selenium1py.pythonanywhere.com/catalogue/the-shellcoders-handbook_209/?promo=newYear\",\n \"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/?promo=newYear2019\"]\n\n\"\"\"\nxfile - номер страницы, на которой тест падает с ошибкой \"AssertionError: Product name is no the same\"\nmask - шаблон URL\nlinks - с помощью генератора формируем список урлов для параметризации теста, исключая ошибочный\nxlink - ошибочный урл с доп.параметром с отметкой XFAIL (ожидаемо падает)\nвставляем в список links ошибочный урл xlink на место xfile\n\"\"\"\nxfile = 7\nmask = 'http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/?promo=offer'\nlinks = [mask+str(i) for i in range(10) if i != xfile]\nxlink = pytest.param(mask+str(xfile), marks=pytest.mark.xfail(reason=\"mistake on page\"))\nlinks.insert(xfile, xlink)\n\n\n@pytest.mark.need_review\n@pytest.mark.parametrize('link', links)\ndef test_guest_can_add_product_to_basket(browser, link):\n page = ProductPage(browser, link)\n page.open()\n page.guest_can_add_product_to_basket()\n\n\n@pytest.mark.parametrize('link', URL_PRODUCT_NewYear)\ndef test_guest_can_add_product_to_basket_promo_newyear(browser, link):\n page = ProductPage(browser, link)\n page.open()\n page.guest_can_add_product_to_basket()\n\n\ndef test_guest_can_add_product_to_basket_without_promo(browser):\n link = \"http://selenium1py.pythonanywhere.com/catalogue/the-shellcoders-handbook_209\"\n page = ProductPage(browser, link)\n page.open()\n page.add_product_to_basket()\n page.guest_can_see_message_product_add_to_basket()\n page.guest_can_see_same_product_name()\n page.guest_can_see_message_price_basket()\n page.guest_can_see_correct_price_basket()\n\n\n@pytest.mark.xfail(reason=\"Success message show.\")\ndef test_guest_cant_see_success_message_after_adding_product_to_basket(browser):\n link = \"http://selenium1py.pythonanywhere.com/catalogue/the-shellcoders-handbook_209\"\n page = ProductPage(browser, link)\n page.open()\n page.add_product_to_basket()\n page.should_not_be_success_message()\n\n\ndef test_guest_cant_see_success_message(browser):\n link = \"http://selenium1py.pythonanywhere.com/catalogue/the-shellcoders-handbook_209\"\n page = ProductPage(browser, link)\n page.open()\n page.should_not_be_success_message()\n\n\n@pytest.mark.xfail(reason=\"Success message not close.\")\ndef test_message_disappeared_after_adding_product_to_basket(browser):\n link = \"http://selenium1py.pythonanywhere.com/catalogue/the-shellcoders-handbook_209\"\n page = ProductPage(browser, link)\n page.open()\n page.add_product_to_basket()\n page.should_be_disappear_success_message()\n\n\ndef test_guest_should_see_login_link_on_product_page(browser):\n link = \"http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/\"\n page = ProductPage(browser, link)\n page.open()\n page.should_be_login_link()\n\n\n@pytest.mark.need_review\ndef test_guest_can_go_to_login_page_from_product_page(browser):\n link = \"http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-city-and-the-stars_95/\"\n page = ProductPage(browser, link)\n page.open()\n page.go_to_login_page()\n\n\n@pytest.mark.need_review\ndef test_guest_cant_see_product_in_basket_opened_from_product_page(browser):\n link = \"http://selenium1py.pythonanywhere.com/en-gb/catalogue/the-shellcoders-handbook_209/\"\n page = BasketPage(browser, link)\n page.open()\n page.go_to_basket_page()\n page.guest_cant_see_product_in_basket()\n page.guest_can_see_message_basket_is_empty()\n\n\nclass TestUserAddToBasketFromProductPage():\n\n @pytest.fixture(scope=\"function\", autouse=True)\n def setup(self, browser):\n link = \"http://selenium1py.pythonanywhere.com/catalogue/the-shellcoders-handbook_209\"\n email = str(time.time()) + \"@newuseremail.edu\"\n password = \"new_user_pass_\" + str(time.time())\n self.new_user = LoginPage(browser, link)\n # self.link = self.link\n self.new_user.open()\n self.new_user.register_new_user(email, password)\n\n def test_user_cant_see_success_message(self, browser):\n link = \"http://selenium1py.pythonanywhere.com/catalogue/the-shellcoders-handbook_209\"\n page = ProductPage(browser, link)\n page.open()\n page.should_not_be_success_message()\n\n @pytest.mark.need_review\n def test_user_can_add_product_to_basket(self, browser):\n link = \"http://selenium1py.pythonanywhere.com/catalogue/the-shellcoders-handbook_209\"\n page = ProductPage(browser, link)\n page.open()\n page.guest_can_add_product_to_basket()\n\n","sub_path":"test_product_page.py","file_name":"test_product_page.py","file_ext":"py","file_size_in_byte":4984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"522483672","text":"import json\nfrom schemas import ensure_schema, ensure_logged_in_user, ensure_role\nimport pymongo\nfrom config import *\nfrom util import *\n\nqr_input = {\n \"type\" : \"object\",\n \"Properties\" : {\n \"auth_email\" : {\"type\" : \"string\", \"format\" : \"email\"},\n\t\"token\" : {\"type\" : \"string\"},\n\t\"email\" : {\"type\" : \"string\"},\n\t\"qr_code\" : {\"type\" : \"string\"}\n },\n \"required\" : [\"auth_email\", \"token\", \"email\", \"qr_code\"]\n}\n\ndef dbinfo():\n collection = coll(\"users\")\n print(\"collection name: \" + str(collection.name))\n print(\"collection database: \" + str(collection.database))\n print(\"collection document count: \" + str(collection.count_documents))\n\n@ensure_schema(qr_input)\n@ensure_logged_in_user(email_key = \"auth_email\")\n@ensure_role([['director', 'organizer', 'volunteer']])\ndef qr_match(event, context, user=None):\n collection = coll('users')\n\n result = collection.update_one({'email' : event[\"email\"]}, {'$push' : {'qrcode' : event[\"qr_code\"]}})\n if result.matched_count == 1:\n return {\n \"statusCode\" : 200,\n \"body\" : \"success\"\n }\n else:\n return {\n \"statusCode\" : 404,\n \"body\" : \"User not found\"\n }\n\n@ensure_schema({\n 'type': 'object',\n 'properties': {\n 'auth_email': {'type': 'string', 'format': 'email'},\n 'token': {'type': 'string'},\n 'qr': {'type': 'string'},\n 'event': {'type': 'string'},\n 'again': {'type': 'boolean'}\n },\n 'required': ['auth_email', 'token', 'qr', 'event']\n})\n@ensure_logged_in_user(email_key='auth_email')\n@ensure_role([['director', 'organizer', 'volunteer']])\ndef attend_event(aws_event, context, user=None):\n users = coll('users')\n qr = aws_event['qr']\n event = aws_event['event']\n again = aws_event.get('again', False)\n\n def attend(user):\n if not again and user['day_of'].get(event, 0) > 0:\n return {'statusCode': 402, 'body': 'user already checked into event'}\n new_user = users.find_one_and_update({'email': user['email']},\n {'$inc': {'day_of.' + event: 1}},\n return_document=pymongo.ReturnDocument.AFTER)\n\n return {'statusCode': 200, 'body': {\n 'email': user['email'],\n 'new_count': new_user['day_of'][event]\n }}\n\n user = users.find_one({'email': qr})\n if user:\n return attend(user)\n\n user = users.find_one({'qrcode': qr})\n if user:\n return attend(user)\n\n return {'statusCode': 404, 'body': 'user not found'}\n","sub_path":"qrscan.py","file_name":"qrscan.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"37980601","text":"# This file is part of Tryton. The COPYRIGHT file at the top level of\n# this repository contains the full copyright notices and license terms.\n\nimport datetime\nfrom dateutil.relativedelta import relativedelta\nimport itertools\n\nfrom sql import Null\nfrom sql.aggregate import Sum\nfrom sql.conditionals import Coalesce\n\nfrom trytond.i18n import gettext\nfrom trytond.model import ModelView, Workflow, ModelSQL, fields, Unique\nfrom trytond.model.exceptions import AccessError\nfrom trytond.wizard import Wizard, StateView, StateTransition, Button\nfrom trytond.pyson import Not, Equal, Eval, Or, Bool, If\nfrom trytond.transaction import Transaction\nfrom trytond.pool import Pool\nfrom trytond.tools import reduce_ids, grouped_slice\n\nfrom .exceptions import ForecastValidationError\n\n\nclass Forecast(Workflow, ModelSQL, ModelView):\n \"Stock Forecast\"\n __name__ = \"stock.forecast\"\n\n _states = {\n 'readonly': Not(Equal(Eval('state'), 'draft')),\n }\n _depends = ['state']\n\n warehouse = fields.Many2One(\n 'stock.location', 'Location', required=True,\n domain=[('type', '=', 'warehouse')], states={\n 'readonly': Or(Not(Equal(Eval('state'), 'draft')),\n Bool(Eval('lines', [0]))),\n },\n depends=['state'])\n destination = fields.Many2One(\n 'stock.location', 'Destination', required=True,\n domain=[('type', 'in', ['customer', 'production'])], states=_states,\n depends=_depends)\n from_date = fields.Date(\n \"From Date\", required=True,\n domain=[('from_date', '<=', Eval('to_date'))],\n states=_states, depends=_depends + ['to_date'])\n to_date = fields.Date(\n \"To Date\", required=True,\n domain=[('to_date', '>=', Eval('from_date'))],\n states=_states, depends=_depends + ['from_date'])\n lines = fields.One2Many(\n 'stock.forecast.line', 'forecast', 'Lines', states=_states,\n depends=_depends)\n company = fields.Many2One(\n 'company.company', 'Company', required=True, states={\n 'readonly': Or(Not(Equal(Eval('state'), 'draft')),\n Bool(Eval('lines', [0]))),\n },\n depends=['state'])\n state = fields.Selection([\n ('draft', \"Draft\"),\n ('done', \"Done\"),\n ('cancelled', \"Cancelled\"),\n ], \"State\", readonly=True, select=True)\n active = fields.Function(fields.Boolean('Active'),\n 'get_active', searcher='search_active')\n\n del _states, _depends\n\n @classmethod\n def __setup__(cls):\n super(Forecast, cls).__setup__()\n cls._order.insert(0, ('from_date', 'DESC'))\n cls._order.insert(1, ('warehouse', 'ASC'))\n cls._transitions |= set((\n ('draft', 'done'),\n ('draft', 'cancelled'),\n ('done', 'draft'),\n ('cancelled', 'draft'),\n ))\n cls._buttons.update({\n 'cancel': {\n 'invisible': Eval('state') != 'draft',\n 'depends': ['state'],\n },\n 'draft': {\n 'invisible': Eval('state') == 'draft',\n 'depends': ['state'],\n },\n 'confirm': {\n 'invisible': Eval('state') != 'draft',\n 'depends': ['state'],\n },\n 'complete': {\n 'readonly': Eval('state') != 'draft',\n 'depends': ['state'],\n },\n })\n cls._active_field = 'active'\n\n @classmethod\n def __register__(cls, module_name):\n cursor = Transaction().connection.cursor()\n sql_table = cls.__table__()\n\n super(Forecast, cls).__register__(module_name)\n\n # Add index on create_date\n table = cls.__table_handler__(module_name)\n table.index_action('create_date', action='add')\n\n # Migration from 5.0: remove check_from_to_date\n table.drop_constraint('check_from_to_date')\n\n # Migration from 5.6: rename state cancel to cancelled\n cursor.execute(*sql_table.update(\n [sql_table.state], ['cancelled'],\n where=sql_table.state == 'cancel'))\n\n @staticmethod\n def default_state():\n return 'draft'\n\n @classmethod\n def default_destination(cls):\n Location = Pool().get('stock.location')\n locations = Location.search(cls.destination.domain)\n if len(locations) == 1:\n return locations[0].id\n\n @staticmethod\n def default_company():\n return Transaction().context.get('company')\n\n def get_active(self, name):\n pool = Pool()\n Date = pool.get('ir.date')\n return self.to_date >= Date.today()\n\n @classmethod\n def search_active(cls, name, clause):\n pool = Pool()\n Date = pool.get('ir.date')\n\n today = Date.today()\n operators = {\n '=': '>=',\n '!=': '<',\n }\n reverse = {\n '=': '!=',\n '!=': '=',\n }\n if clause[1] in operators:\n if clause[2]:\n return [('to_date', operators[clause[1]], today)]\n else:\n return [('to_date', operators[reverse[clause[1]]], today)]\n else:\n return []\n\n def get_rec_name(self, name):\n return self.warehouse.rec_name\n\n @classmethod\n def search_rec_name(cls, name, clause):\n return [('warehouse.rec_name',) + tuple(clause[1:])]\n\n @classmethod\n def validate(cls, forecasts):\n super(Forecast, cls).validate(forecasts)\n for forecast in forecasts:\n forecast.check_date_overlap()\n\n def check_date_overlap(self):\n if self.state != 'done':\n return\n transaction = Transaction()\n connection = transaction.connection\n transaction.database.lock(connection, self._table)\n forcast = self.__table__()\n cursor = connection.cursor()\n cursor.execute(*forcast.select(forcast.id,\n where=(((forcast.from_date <= self.from_date)\n & (forcast.to_date >= self.from_date))\n | ((forcast.from_date <= self.to_date)\n & (forcast.to_date >= self.to_date))\n | ((forcast.from_date >= self.from_date)\n & (forcast.to_date <= self.to_date)))\n & (forcast.warehouse == self.warehouse.id)\n & (forcast.destination == self.destination.id)\n & (forcast.company == self.company.id)\n & (forcast.id != self.id)))\n forecast_id = cursor.fetchone()\n if forecast_id:\n second = self.__class__(forecast_id[0])\n raise ForecastValidationError(\n gettext('stock_forecast.msg_forecast_date_overlap',\n first=self.rec_name,\n second=second.rec_name))\n\n @classmethod\n def delete(cls, forecasts):\n # Cancel before delete\n cls.cancel(forecasts)\n for forecast in forecasts:\n if forecast.state != 'cancelled':\n raise AccessError(\n gettext('stock_forecast.msg_forecast_delete_cancel',\n forecast=forecast.rec_name))\n super(Forecast, cls).delete(forecasts)\n\n @classmethod\n @ModelView.button\n @Workflow.transition('draft')\n def draft(cls, forecasts):\n pass\n\n @classmethod\n @ModelView.button\n @Workflow.transition('done')\n def confirm(cls, forecasts):\n pass\n\n @classmethod\n @ModelView.button\n @Workflow.transition('cancelled')\n def cancel(cls, forecasts):\n pass\n\n @classmethod\n @ModelView.button_action('stock_forecast.wizard_forecast_complete')\n def complete(cls, forecasts):\n pass\n\n @staticmethod\n def create_moves(forecasts):\n 'Create stock moves for the forecast ids'\n pool = Pool()\n Line = pool.get('stock.forecast.line')\n to_save = []\n for forecast in forecasts:\n if forecast.state == 'done':\n for line in forecast.lines:\n line.moves += tuple(line.get_moves())\n to_save.append(line)\n Line.save(to_save)\n\n @staticmethod\n def delete_moves(forecasts):\n 'Delete stock moves for the forecast ids'\n Line = Pool().get('stock.forecast.line')\n Line.delete_moves([l for f in forecasts for l in f.lines])\n\n\nclass ForecastLine(ModelSQL, ModelView):\n 'Stock Forecast Line'\n __name__ = 'stock.forecast.line'\n _states = {\n 'readonly': Eval('forecast_state') != 'draft',\n }\n _depends = ['forecast_state']\n\n product = fields.Many2One('product.product', 'Product', required=True,\n domain=[\n ('type', '=', 'goods'),\n ('consumable', '=', False),\n ],\n states=_states, depends=_depends)\n product_uom_category = fields.Function(\n fields.Many2One('product.uom.category', 'Product Uom Category'),\n 'on_change_with_product_uom_category')\n uom = fields.Many2One('product.uom', 'UOM', required=True,\n domain=[\n If(Bool(Eval('product_uom_category')),\n ('category', '=', Eval('product_uom_category')),\n ('category', '!=', -1)),\n ],\n states=_states,\n depends=['product', 'product_uom_category'] + _depends)\n unit_digits = fields.Function(fields.Integer('Unit Digits'),\n 'get_unit_digits')\n quantity = fields.Float(\n \"Quantity\", digits=(16, Eval('unit_digits', 2)), required=True,\n domain=[('quantity', '>=', 0)],\n states=_states, depends=['unit_digits'] + _depends)\n minimal_quantity = fields.Float(\n \"Minimal Qty\", digits=(16, Eval('unit_digits', 2)), required=True,\n domain=[('minimal_quantity', '<=', Eval('quantity'))],\n states=_states, depends=['unit_digits', 'quantity'] + _depends)\n moves = fields.Many2Many('stock.forecast.line-stock.move',\n 'line', 'move', 'Moves', readonly=True)\n forecast = fields.Many2One(\n 'stock.forecast', 'Forecast', required=True, ondelete='CASCADE',\n states={\n 'readonly': ((Eval('forecast_state') != 'draft')\n & Bool(Eval('forecast'))),\n },\n depends=['forecast_state'])\n forecast_state = fields.Function(\n fields.Selection('get_forecast_states', 'Forecast State'),\n 'on_change_with_forecast_state')\n quantity_executed = fields.Function(fields.Float('Quantity Executed',\n digits=(16, Eval('unit_digits', 2)), depends=['unit_digits']),\n 'get_quantity_executed')\n\n del _states, _depends\n\n @classmethod\n def __setup__(cls):\n super(ForecastLine, cls).__setup__()\n t = cls.__table__()\n cls._sql_constraints += [\n ('forecast_product_uniq', Unique(t, t.forecast, t.product),\n 'stock_forecast.msg_forecast_line_product_unique'),\n ]\n\n @classmethod\n def __register__(cls, module_name):\n super().__register__(module_name)\n\n table_h = cls.__table_handler__(module_name)\n\n # Migration from 5.0: remove check on quantity\n table_h.drop_constraint('check_line_qty_pos')\n table_h.drop_constraint('check_line_minimal_qty')\n\n @staticmethod\n def default_unit_digits():\n return 2\n\n @staticmethod\n def default_minimal_quantity():\n return 1.0\n\n @fields.depends('product')\n def on_change_product(self):\n self.unit_digits = 2\n if self.product:\n self.uom = self.product.default_uom\n self.unit_digits = self.product.default_uom.digits\n\n @fields.depends('product')\n def on_change_with_product_uom_category(self, name=None):\n if self.product:\n return self.product.default_uom_category.id\n\n @fields.depends('uom')\n def on_change_uom(self):\n self.unit_digits = 2\n if self.uom:\n self.unit_digits = self.uom.digits\n\n def get_unit_digits(self, name):\n return self.product.default_uom.digits\n\n @classmethod\n def get_forecast_states(cls):\n pool = Pool()\n Forecast = pool.get('stock.forecast')\n return Forecast.fields_get(['state'])['state']['selection']\n\n @fields.depends('forecast', '_parent_forecast.state')\n def on_change_with_forecast_state(self, name=None):\n if self.forecast:\n return self.forecast.state\n\n def get_rec_name(self, name):\n return self.product.rec_name\n\n @classmethod\n def search_rec_name(cls, name, clause):\n return [('product.rec_name',) + tuple(clause[1:])]\n\n @classmethod\n def get_quantity_executed(cls, lines, name):\n cursor = Transaction().connection.cursor()\n pool = Pool()\n Move = pool.get('stock.move')\n Location = pool.get('stock.location')\n Uom = pool.get('product.uom')\n Forecast = pool.get('stock.forecast')\n LineMove = pool.get('stock.forecast.line-stock.move')\n\n move = Move.__table__()\n location_from = Location.__table__()\n location_to = Location.__table__()\n line_move = LineMove.__table__()\n\n result = dict((x.id, 0) for x in lines)\n\n def key(line):\n return line.forecast.id\n lines.sort(key=key)\n for forecast_id, lines in itertools.groupby(lines, key):\n forecast = Forecast(forecast_id)\n product2line = dict((line.product.id, line) for line in lines)\n product_ids = product2line.keys()\n for sub_ids in grouped_slice(product_ids):\n red_sql = reduce_ids(move.product, sub_ids)\n cursor.execute(*move.join(location_from,\n condition=move.from_location == location_from.id\n ).join(location_to,\n condition=move.to_location == location_to.id\n ).join(line_move, 'LEFT',\n condition=move.id == line_move.move\n ).select(move.product, Sum(move.internal_quantity),\n where=red_sql\n & (location_from.left >= forecast.warehouse.left)\n & (location_from.right <= forecast.warehouse.right)\n & (location_to.left >= forecast.destination.left)\n & (location_to.right <= forecast.destination.right)\n & (move.state != 'cancelled')\n & (Coalesce(move.effective_date, move.planned_date)\n >= forecast.from_date)\n & (Coalesce(move.effective_date, move.planned_date)\n <= forecast.to_date)\n & (line_move.id == Null),\n group_by=move.product))\n for product_id, quantity in cursor.fetchall():\n line = product2line[product_id]\n result[line.id] = Uom.compute_qty(line.product.default_uom,\n quantity, line.uom)\n return result\n\n @classmethod\n def copy(cls, lines, default=None):\n if default is None:\n default = {}\n else:\n default = default.copy()\n default.setdefault('moves', None)\n return super(ForecastLine, cls).copy(lines, default=default)\n\n def get_moves(self):\n 'Get stock moves for the forecast line'\n pool = Pool()\n Move = pool.get('stock.move')\n Uom = pool.get('product.uom')\n Date = pool.get('ir.date')\n\n assert not self.moves\n\n today = Date.today()\n from_date = self.forecast.from_date\n if from_date < today:\n from_date = today\n to_date = self.forecast.to_date\n if to_date < today:\n return []\n\n delta = to_date - from_date\n delta = delta.days + 1\n nb_packet = ((self.quantity - self.quantity_executed)\n // self.minimal_quantity)\n distribution = self.distribute(delta, nb_packet)\n unit_price = None\n if self.forecast.destination.type == 'customer':\n unit_price = self.product.list_price\n unit_price = Uom.compute_price(self.product.default_uom,\n unit_price, self.uom)\n\n moves = []\n for day, qty in distribution.items():\n if qty == 0.0:\n continue\n move = Move()\n move.from_location = self.forecast.warehouse.storage_location\n move.to_location = self.forecast.destination\n move.product = self.product\n move.uom = self.uom\n move.quantity = qty * self.minimal_quantity\n move.planned_date = from_date + datetime.timedelta(day)\n move.company = self.forecast.company\n move.currency = self.forecast.company.currency\n move.unit_price = unit_price\n moves.append(move)\n return moves\n\n @classmethod\n def delete_moves(cls, lines):\n 'Delete stock moves of the forecast line'\n Move = Pool().get('stock.move')\n Move.delete([m for l in lines for m in l.moves])\n\n def distribute(self, delta, qty):\n 'Distribute qty over delta'\n range_delta = list(range(delta))\n a = {}.fromkeys(range_delta, 0)\n while qty > 0:\n if qty > delta:\n for i in range_delta:\n a[i] += qty // delta\n qty = qty % delta\n elif delta // qty > 1:\n i = 0\n while i < qty:\n a[i * delta // qty + (delta // qty // 2)] += 1\n i += 1\n qty = 0\n else:\n for i in range_delta:\n a[i] += 1\n qty = delta - qty\n i = 0\n while i < qty:\n a[delta - ((i * delta // qty) + (delta // qty // 2)) - 1\n ] -= 1\n i += 1\n qty = 0\n return a\n\n\nclass ForecastLineMove(ModelSQL):\n 'ForecastLine - Move'\n __name__ = 'stock.forecast.line-stock.move'\n _table = 'forecast_line_stock_move_rel'\n line = fields.Many2One('stock.forecast.line', 'Forecast Line',\n ondelete='CASCADE', select=True, required=True)\n move = fields.Many2One('stock.move', 'Move', ondelete='CASCADE',\n select=True, required=True)\n\n\nclass ForecastCompleteAsk(ModelView):\n 'Complete Forecast'\n __name__ = 'stock.forecast.complete.ask'\n from_date = fields.Date(\n \"From Date\", required=True,\n domain=[('from_date', '<', Eval('to_date'))],\n depends=['to_date'])\n to_date = fields.Date(\n \"To Date\", required=True,\n domain=[('to_date', '>', Eval('from_date'))],\n depends=['from_date'])\n\n\nclass ForecastCompleteChoose(ModelView):\n 'Complete Forecast'\n __name__ = 'stock.forecast.complete.choose'\n products = fields.Many2Many('product.product', None, None, 'Products')\n\n\nclass ForecastComplete(Wizard):\n 'Complete Forecast'\n __name__ = 'stock.forecast.complete'\n start_state = 'ask'\n ask = StateView('stock.forecast.complete.ask',\n 'stock_forecast.forecast_complete_ask_view_form', [\n Button('Cancel', 'end', 'tryton-cancel'),\n Button('Choose Products', 'choose', 'tryton-forward'),\n Button('Complete', 'complete', 'tryton-ok', default=True),\n ])\n choose = StateView('stock.forecast.complete.choose',\n 'stock_forecast.forecast_complete_choose_view_form', [\n Button('Cancel', 'end', 'tryton-cancel'),\n Button('Choose Dates', 'ask', 'tryton-back'),\n Button('Complete', 'complete', 'tryton-ok', default=True),\n ])\n complete = StateTransition()\n\n def default_ask(self, fields):\n \"\"\"\n Forecast dates shifted by one year.\n \"\"\"\n default = {}\n for field in (\"to_date\", \"from_date\"):\n default[field] = (\n getattr(self.record, field) - relativedelta(years=1))\n return default\n\n def _get_product_quantity(self):\n pool = Pool()\n Product = pool.get('product.product')\n\n with Transaction().set_context(\n stock_destinations=[self.record.destination.id],\n stock_date_start=self.ask.from_date,\n stock_date_end=self.ask.to_date):\n return Product.products_by_location([self.record.warehouse.id],\n with_childs=True)\n\n def default_choose(self, fields):\n \"\"\"\n Collect products for which there is an outgoing stream between\n the given location and the destination.\n \"\"\"\n if getattr(self.choose, 'products', None):\n return {'products': [x.id for x in self.choose.products]}\n pbl = self._get_product_quantity()\n products = []\n for (_, product), qty in pbl.items():\n if qty < 0:\n products.append(product)\n return {'products': products}\n\n def transition_complete(self):\n pool = Pool()\n ForecastLine = pool.get('stock.forecast.line')\n Product = pool.get('product.product')\n\n forecast = self.record\n prod2line = {}\n forecast_lines = ForecastLine.search([\n ('forecast', '=', forecast.id),\n ])\n for forecast_line in forecast_lines:\n prod2line[forecast_line.product.id] = forecast_line\n\n pbl = self._get_product_quantity()\n product_ids = [x[1] for x in pbl]\n prod2uom = {}\n for product in Product.browse(product_ids):\n prod2uom[product.id] = product.default_uom.id\n\n if getattr(self.choose, 'products', None):\n products = [x.id for x in self.choose.products]\n else:\n products = None\n\n to_save = []\n for key, qty in pbl.items():\n _, product = key\n if products and product not in products:\n continue\n if -qty <= 0:\n continue\n if product in prod2line:\n line = prod2line[product]\n else:\n line = ForecastLine()\n line.product = product\n line.quantity = -qty\n line.uom = prod2uom[product]\n line.forecast = forecast\n line.minimal_quantity = min(1, -qty)\n to_save.append(line)\n\n ForecastLine.save(to_save)\n return 'end'\n","sub_path":"stock_forecast/forecast.py","file_name":"forecast.py","file_ext":"py","file_size_in_byte":22567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"222560311","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport pickle\nfrom matplotlib import animation\nfrom PIL import Image\nfrom PIL import ImageEnhance\n\n\"\"\"\nINFO\ncv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) == return Numpy arrays of (x,y)\ncv2.drawContours(IMG, arrays, DRAWINGMODE, COLOR, THICKNESS)\n\"\"\"\n\nn = 3\n#image = 'sampleT.jpg'\nimage = 'letterImage.png'\n\n#crop image to focus on letter\ndef reduceImage():\n\tim = Image.open(image)\n\timArray = im.load()\n\twidth,height = im.size\n\treducX = 80\n\treducY = 55\n\tbox = (reducX,reducY, width-reducX,height-reducY) #box(left,upper,right,lower)\n\tim = im.crop(box)\n\tim.save('text'+str(n)+'.png')\n\treturn im\n\t'''newImg = Image.new('RGB', (width-10,height-10))\n\tnewArray = newImg.load()\n\tfor y in range(10,height):\n\t\tfor x in range(10,width):\n\t\t\tnewArray[x-10,y-10] = (imArray[x,y])\n\t\t\t#print(imArray[x,y])\n\t\t\t#print(newArray[x,y])\n\t#img= Image.fromarray(newArray)'''\n\n#increase saturation of pixels. Returns a numpy array\t\n# NOT USED FOR NOW because loosing data rather than gaining some\ndef histoEqual(inputImg): \n\timgArray = np.array(inputImg) \n\t#convert letter to BW so clahe can be applied to it\n\timgray = cv2.cvtColor(imgArray,cv2.COLOR_BGR2GRAY) \n\t# create a CLAHE object (Arguments are optional).\n\tclahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))\n\tcl1 = clahe.apply(imgray)\n\n\tclahename = 'equalized'+str(n)+'.png'\n\tcv2.imwrite(clahename,cl1)\n\treturn cl1\n\n#Inhance the saturation of picture to increase darkness of black pixels\n# NOT USE EITHER. Barely increases the saturation of the back pixels\ndef enhanceColor(inputImg):\n\tconverter = ImageEnhance.Color(inputImg)\n\timg2 = converter.enhance(2)\n\tnewname = 'inhanced'+str(n)+'.png'\n\timg2.save(newname)\n\treturn img2\n\n#Isolate the dark pixels in image to isolate the letter\n#Takes an Image, returns a numpy array\ndef isolateDarkPix(inputImg):\t\t\t\n\timgArray = np.array(inputImg) \t\t\t\t\t\t#turn PIL image into numpy array for opencv functions\n\t#iterate through numpy array of img. If img.pixel value is greater than 50 (so if it's anything else than pure black), change it to 255 (white)\n\timgArray[imgArray > 60] = 255\t\n\tnewname = 'isolated'+str(n)+'.png'\n\tcv2.imwrite(newname,imgArray)\n\treturn imgArray\n\n\ndef contoursOfImage(inputArray):\n\timgray = cv2.cvtColor(inputArray,cv2.COLOR_BGR2GRAY) \n\tret,thresh = cv2.threshold(imgray,127,255,cv2.THRESH_BINARY_INV) #apply threshold, use binary inverse to focus on black part rather than white part. RETURN AN IMG\n\tcv2.imwrite('threshold3.png',thresh)\n\tcontours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #gets only important corners (in case straight lines). Consumes less space\n\t#contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE) #gets all points. RETURN \n\n\tcv2.drawContours(inputArray, contours, -1, (0,255,0), 3) #draw contours\n\t#cv2.drawContours(inputArray, contours, -1, (0,255,0), -1) #fill inside edges\n\n\t#cv2.imwrite('object'+str(n)+'.png',inputArray)\n\tcv2.imwrite('object3NotIsolated.png',inputArray)\n\t#contours is a Python list of all the contours in the image. Each individual contour is a Numpy array of (x,y) coordinates of boundary points of the object.\n\treturn contours\n\n\t\n#Test function to give me information about the contour Array\ndef arrayInfo(list):\n\t#EACH ELEMENT IN LIST[N] IS A NUMPARY ARRAY OF X,Y POINTS\n\t\n\tf = open(\"Array.txt\",\"w\")\n\ti = 0\n\tfor numpyArray in list:\n\t\tprint(\"Contour\"+str(i))\n\t\tf.write(\"Contour\"+str(i)+\"\\n\")\n\t\t#print type(numpyArray)\n\t\tprint(\"shape of array: \"+ str(numpyArray.shape))\n\t\tprint(\"ndim of array: \"+ str(numpyArray.ndim))\n\t\tprint(\"size of array: \"+ str(numpyArray.size))\n\t\tf.write(\"shape of array: \"+ str(numpyArray.shape)+\"\\n\" )\n\t\tf.write(\"ndim of array: \"+ str(numpyArray.ndim)+\"\\n\")\n\t\tf.write(\"size of array: \"+ str(numpyArray.size)+\"\\n\")\n\t\t#print(\"itemSize of array: \"+ str(numpyArray.itemSize))\n\t\tprint (\"---------------\")\n\t\tf.write(\"--------------- \\n\")\n\t\ti+=1\n\n\t\n\t#for numpyArray in list:\t\n\t#for v, value in np.ndenumerate(list[4]):\n\t\t#print value\n\t\n\tf.close()\n\n#run through list of contours and return contour that contains the most points/data.\n#returns a numpy array\ndef findRelevantContour(list):\n\ti = 0 #keep track of index in list\n\tmaxValue,indexOfMax=0,0\n\tfor numpyArray in list:\n\t\tif (numpyArray.shape[0]>maxValue):\n\t\t\tmaxValue = numpyArray.shape[0]\n\t\t\tindexOfMax=i\n\t\ti+=1\n\tprint(\"the Contour with the most points is contour: \"+str(indexOfMax)+\" with n.point: \"+str(maxValue))\n\t\n\treturn list[indexOfMax]\n\t\t\n\n#clusterize the points of contour into boxes to get reduce the actual contour into one single line\t\n#Contour is a numpy array of (x,y)points (numpyArray as well)\ndef clusterizeArray(contour):\n\t#holds the value of reference of each box to compare to value that needs to be placed in box.\n\treferencesPerBox = []\n\tlistOfPoints = []\n\tlistOfBoxes = []\n\tr = open(\"1-clusterisationProcess.txt\",\"w\")\n\tx = open(\"2-clusterisedArray.txt\",\"w\")\n\n\t#for x,y in (contoursList[4].flatten().reshape(-1,2)):\n\t#slicing array : array[start:stop:step]\t\n\t#contoursList[4].flatten().reshape(-1,2))[0:300:1] IN CASE WE WANT TO FRAGMENT THE LIST\n\tshowPoints((contour.flatten().reshape(-1,2)))\n\tfor value in ( (contour.flatten().reshape(-1,2)) ):\n\t\t#Base case: List of Boxes is empty\n\t\t#Creates the first box and puts the first point from our numpArray in it\n\t\tif (not listOfBoxes):\n\t\t\tlistOfPoints.append(value)\n\t\t\treferencesPerBox.append(value)\n\t\t\tlistOfBoxes.append(listOfPoints)\n\t\t\n\t\t\n\t\t#List of Boxes has more than one box\n\t\telif (len(listOfBoxes)>0):\t\t\n\t\t\tneedNewBox = True\n\t\t\t#I'm using indexes here because it represents the number of the box\n\t\t\tfor i in range(len(referencesPerBox)):\n\t\t\t\t#keep adding points that belong to box 0 into it. We use reference value of box for that: if the new value is greater or less than reference by 20, it belongs to a new box\n\t\t\t\t#create a new cluster everytime the diff between 2 points is bigger than 30 (the bigger the value, the less clusters)\n\t\t\t\tif ( (abs(value-referencesPerBox[i]) < 30).all() ):\n\t\t\t\t\tlistOfBoxes[i].append(value)\n\t\t\t\t\t#print(\"value \"+str(value)+\" goes to box: \"+str(i))\n\t\t\t\t\tr.write(\"value \"+str(value)+\" goes to box: \"+str(i)+\"\\n\")\n\t\t\t\t\tneedNewBox = False\n\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\t#print (\"value \"+str(value)+\"doesn't fit in box:\"+str(i))\n\t\t\t\t\tr.write(\"value \"+str(value)+\"doesn't fit in box:\"+str(i)+\"\\n\")\n\t\t\t\n\t\t\tif needNewBox == True:\n\t\t\t\t#print(\"\\nWe need a new box\")\n\t\t\t\tr.write(\"We need a new box \\n\")\n\t\t\t\t#We came out of loop without finding a match so we create a new box. Then we get to next value (thanks to value loop), which will get access to new reference\n\t\t\t\tlistOfPoints=[]\n\t\t\t\tlistOfPoints.append(value)\n\t\t\t\treferencesPerBox.append(value) #new reference for box 1\n\t\t\t\tlistOfBoxes.append(listOfPoints)\n\t\t\t\t#print (\"length of Box list is NOW: \"+ str(len(listOfBoxes)))\n\t\t\t\tr.write(\"length of Box list is NOW: \"+ str(len(listOfBoxes))+\"\\n\")\n\t\t\t\t#print(\"Reference list is now: \"+str(len(referencesPerBox))+\"\\n\")\n\t\t\t\tr.write(\"Reference list is now: \"+str(len(referencesPerBox))+\"\\n\")\n\t\t\t\t\n\tprint(\"\\n\")\n\t#print(listOfBoxes)\t\n\tfor i in range (len(listOfBoxes)):\n\t\tx.write(\"Box \"+str(i)+\": \"+str(listOfBoxes[i])+\"\\n\")\n\t\n\tx.close()\n\tr.close()\n\treturn listOfBoxes\t\t\n\t\t\n\t\t\ndef averagingClusters(list):\n\t# new list to hold average point for each box/cluster\n\tnewClusterList = []\n\tfor i in range(len(list)):\n\t\tprint(\"averaging points at box:\"+str(i))\n\t\t#reset var\n\t\ttotalX,totalY,averageX,averageY=0,0,0,0\n\t\tfor x,y in list[i]:\n\t\t\ttotalX+=x\n\t\t\ttotalY+=y\n\t\taverageX=totalX/len(list[i])\n\t\taverageY=totalY/len(list[i])\n\t\tprint(averageX,averageY)\n\t\t#create a new numpy array to store the x,y points and add it a new list of boxes (at right index, as index is the number of the box)\n\t\tpoint = np.array([averageX,averageY])\n\t\tnewClusterList.insert(i,point)\n\t\n\t#print(newClusterList)\n\tf = open(\"3-averagedClusterisedArray.txt\",\"w\")\n\tfor i in range (len(newClusterList)):\n\t\tf.write(\"Box \"+str(i)+\": \"+str(newClusterList[i])+\"\\n\")\n\tf.close()\n\treturn newClusterList\n\n#mirror the points on the x axis to flip the letter in the correct position\ndef mirrorPoints(list,imageWidth,imageHeight):\n\tmirroredArray = list #making a copy just in case\n\tfor value in mirroredArray:\n\t\tnewX = imageWidth-value[0]\n\t\t#newY = imageHeight-value[1]\n\t\tvalue[0]=newX\n\t\t#value[1]=newY\n\t\n\tf = open(\"4-averagedArrayMirrored.txt\",\"w\")\n\tfor value in mirroredArray:\n\t\tf.write(str(value)+\"\\n\")\n\tf.close()\n\t\n\t#save array into a file that the robot can use\n\tpickle.dump(mirroredArray, open( \"letter.p\", \"wb\" ) )\n\n\treturn mirroredArray\n\t\n\ndef showPoints(list):\n\tfor x,y in list:\n\t\tplt.scatter(x, y)\n\tplt.show()\n\ndef drawLetter(list):\n\tplt.axes()\n\tfor i in range(len(list)):\n\t\tprint(i)\n\t\tif(i!=(len(list)-1)):\n\t\t\tprint(\"x are: \",str((list[i])[0]),\" \",str((list[i+1])[0]),\" y are: \", str((list[i])[1]), \" \", str((list[i+1])[1]))\n\t\t\tprint(\"drawing line between points \",str(list[i]), \" \",str(list[i+1]))\n\t\t\tdotted_line = plt.Line2D(( (list[i])[0], (list[i+1])[0]), ((list[i])[0], (list[i+1])[1]), lw=5., \n\t\t\t\t\t\t\t ls='-.', marker='.', \n\t\t\t\t\t\t\t markersize=50, \n\t\t\t\t\t\t\t markerfacecolor='r', \n\t\t\t\t\t\t\t markeredgecolor='r', \n\t\t\t\t\t\t\t alpha=0.5)\n\t\t\tplt.gca().add_line(dotted_line)\n\t\t\t#plt.scatter(x, y)\t\n\tplt.axis('scaled')\n\tplt.show()\n\n\t\n\t\n\nif __name__ == '__main__':\t\n\tcroppedImg = reduceImage()\t\t\t\t#image\n\t#enhanceImg = enhanceColor(croppedImg) #image\n\tblackPixArray = isolateDarkPix(croppedImg) #array\n\tcont = contoursOfImage(blackPixArray)\t\t#contour is a list of numpyArrays(which contain (x,y) numparray)\n\t#Give us info about what the list of contours contains\n\tarrayInfo(cont)\n\t#Get the contour with the most points, to discard contours that are just noise in the picture\n\trelevantContour = findRelevantContour(cont)\n\t\n\t\n\t#Arrange the array into clusters to find the average points that constitute the letter (and trajectory)\n\tclusters = clusterizeArray(relevantContour)\n\taveragedClusters = averagingClusters(clusters)\n\t#drawLetter(averagedClusters)\n\t#reverse letter for robot\n\timWidth, imHeight = croppedImg.size\t\n\tmirroredClusters = mirrorPoints(averagedClusters,imWidth,imHeight)\n\tshowPoints(mirroredClusters)\n\tdrawLetter(mirroredClusters)\n\t\n\t\n\t\n\n\t\n\t\n\t\n","sub_path":"P_OK/getContours.py","file_name":"getContours.py","file_ext":"py","file_size_in_byte":10179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"576455025","text":"import xbmc\nimport xbmcgui\n\nimport os\n\nfrom resources.libs.common.config import CONFIG\nfrom resources.libs.common import directory\nfrom resources.libs.common import logging\nfrom resources.libs.common import tools\nfrom resources.libs.gui import window\n\n\ndef view_current():\n window.show_text_box(CONFIG.ADDONTITLE, tools.read_from_file(CONFIG.ADVANCED).replace('\\t', ' '))\n\n\ndef remove_current():\n dialog = xbmcgui.Dialog()\n ok = dialog.yesno(CONFIG.ADDONTITLE, \"[COLOR {0}]Estas seguro de eliminr el actual advancedsettings.xml?[/COLOR]\".format(CONFIG.COLOR2),\n yeslabel=\"[B][COLOR springgreen]Yes[/COLOR][/B]\",\n nolabel=\"[B][COLOR red]No[/COLOR][/B]\")\n\n if ok:\n if os.path.exists(CONFIG.ADVANCED):\n tools.remove_file(CONFIG.ADVANCED)\n logging.log_notify(\"[COLOR {0}]{1}[/COLOR]\".format(CONFIG.COLOR1, CONFIG.ADDONTITLE),\n \"[COLOR {0}]advancedsettings.xml eliminado[/COLOR]\".format(CONFIG.COLOR2))\n xbmc.executebuiltin('Container.Refresh()')\n else:\n logging.log_notify(\"[COLOR {0}]{1}[/COLOR]\".format(CONFIG.COLOR1, CONFIG.ADDONTITLE),\n \"[COLOR {0}]advancedsettings.xml no encontrado[/COLOR]\".format(CONFIG.COLOR2))\n else:\n logging.log_notify(\"[COLOR {0}]{1}[/COLOR]\".format(CONFIG.COLOR1, CONFIG.ADDONTITLE),\n \"[COLOR {0}]advancedsettings.xml no eliminado[/COLOR]\".format(CONFIG.COLOR2))\n\n\ndef _write_setting(category, tag, value):\n from xml.etree import ElementTree\n\n exists = os.path.exists(CONFIG.ADVANCED)\n\n if exists:\n root = ElementTree.parse(CONFIG.ADVANCED).getroot()\n else:\n root = ElementTree.Element('advancedsettings')\n\n tree_category = root.find('./{0}'.format(category))\n if tree_category is None:\n tree_category = ElementTree.SubElement(root, category)\n\n category_tag = tree_category.find(tag)\n if category_tag is None:\n category_tag = ElementTree.SubElement(tree_category, tag)\n\n category_tag.text = '{0}'.format(value)\n\n tree = ElementTree.ElementTree(root)\n\n logging.log('Writing {0} - {1}: {2} to advancedsettings.xml'.format(category, tag, value), level=xbmc.LOGDEBUG)\n tree.write(CONFIG.ADVANCED)\n\n xbmc.executebuiltin('Container.Refresh()')\n\n\nclass AdvancedMenu:\n def __init__(self):\n self.dialog = xbmcgui.Dialog()\n\n self.tags = {}\n\n def show_menu(self, url=None):\n directory.add_dir('Configuracion rapida de advancedsettings.xml',\n {'mode': 'advanced_settings', 'action': 'quick_configure'}, icon=CONFIG.ICONMAINT,\n themeit=CONFIG.THEME3)\n\n if os.path.exists(CONFIG.ADVANCED):\n directory.add_file('Ver configuracion actual de advancedsettings.xml',\n {'mode': 'advanced_settings', 'action': 'view_current'}, icon=CONFIG.ICONMAINT,\n themeit=CONFIG.THEME3)\n directory.add_file('Eliminar configuracion actual de advancedsettings.xml',\n {'mode': 'advanced_settings', 'action': 'remove_current'}, icon=CONFIG.ICONMAINT,\n themeit=CONFIG.THEME3)\n \n response = tools.open_url(CONFIG.ADVANCEDFILE)\n url_response = tools.open_url(url)\n local_file = os.path.join(CONFIG.ADDON_PATH, 'resources', 'text', 'advanced.json')\n\n if url_response:\n TEMPADVANCEDFILE = url_response.text\n elif response:\n TEMPADVANCEDFILE = response.text\n elif os.path.exists(local_file):\n TEMPADVANCEDFILE = tools.read_from_file(local_file)\n else:\n TEMPADVANCEDFILE = None\n logging.log(\"[Advanced Settings] No hay presets establecidos\")\n \n if TEMPADVANCEDFILE:\n import json\n\n directory.add_separator(icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n \n try:\n advanced_json = json.loads(TEMPADVANCEDFILE)\n except:\n advanced_json = None\n logging.log(\"[Advanced Settings] ERROR: Formato no valido para {0}.\".format(TEMPADVANCEDFILE))\n \n if advanced_json:\n presets = advanced_json['presets']\n if presets and len(presets) > 0:\n for preset in presets:\n name = preset.get('name', '')\n section = preset.get('section', False)\n preseturl = preset.get('url', '')\n icon = preset.get('icon', CONFIG.ADDON_ICON)\n fanart = preset.get('fanart', CONFIG.ADDON_FANART)\n description = preset.get('description', '')\n\n if not name:\n logging.log('[Advanced Settings] Falta el tag \\'name\\'', level=xbmc.LOGDEBUG)\n continue\n if not preseturl:\n logging.log('[Advanced Settings] Falta el tag \\'url\\'', level=xbmc.LOGDEBUG)\n continue\n \n if section:\n directory.add_dir(name, {'mode': 'advanced_settings', 'url': preseturl},\n description=description, icon=icon, fanart=fanart, themeit=CONFIG.THEME3)\n else:\n directory.add_file(name,\n {'mode': 'advanced_settings', 'action': 'write_advanced', 'name': name,\n 'url': preseturl},\n description=description, icon=icon, fanart=fanart, themeit=CONFIG.THEME2)\n else:\n logging.log(\"[Advanced Settings] URL no validad: {0}\".format(CONFIG.ADVANCEDFILE))\n\n def quick_configure(self):\n directory.add_file('Los cambios no se aplicaran hasta que reinicies Kodi.', icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n directory.add_file('Click aqui para reiniciar Kodi.', {'mode': 'forceclose'}, icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n directory.add_file('Mas categorias proximamente ;) ', icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n directory.add_separator(middle='CATEGORIAS')\n # directory.add_dir('Troubleshooting', {'mode': 'advanced_settings', 'action': 'show_section', 'tags': 'loglevel|jsonrpc'}, icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n # directory.add_dir('Playback', {'mode': 'advanced_settings', 'action': 'show_section', 'tags': 'skiploopfilter|video|audio|edl|pvr|epg|forcedswaptime'}, icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n # directory.add_dir('Video Library', {'mode': 'advanced_settings', 'action': 'show_section', 'tags': 'videoextensions|discstubextensions|languagecodes|moviestacking|folderstacking|cleandatetime|cleanstrings|tvshowmatching|tvmultipartmatching'}, icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n directory.add_dir('Red y cache', {'mode': 'advanced_settings', 'action': 'show_section', 'tags': 'cache|network'}, icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n\n def show_section(self, tags):\n from xml.etree import ElementTree\n\n split_tags = tags.split('|')\n logging.log(split_tags)\n\n exists = os.path.exists(CONFIG.ADVANCED)\n\n if exists:\n root = ElementTree.parse(CONFIG.ADVANCED).getroot()\n\n for category in root.findall('*'):\n name = category.tag\n if name not in split_tags:\n continue\n\n values = {}\n\n for element in category.findall('*'):\n values[element.tag] = element.text\n\n self.tags[name] = values\n\n if len(self.tags) == 0:\n directory.add_file('No hay opciones para esta categoria de advancedsettings.xml file.', icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n directory.add_separator()\n \n for category in self.tags:\n directory.add_separator(category.upper())\n\n for tag in self.tags[category]:\n value = self.tags[category][tag]\n\n if value is None:\n value = ''\n\n directory.add_file('{0}: {1}'.format(tag, value), {'mode': 'advanced_settings', 'action': 'set_setting',\n 'category': category, 'tag': tag, 'value': value},\n icon=CONFIG.ICONMAINT, themeit=CONFIG.THEME3)\n\n def set_setting(self, category, tag, current):\n value = None\n \n if category == 'cache':\n value = self._cache(tag, current)\n elif category == 'network':\n value = self._network(tag, current)\n \n if value:\n _write_setting(category, tag, value)\n \n def _cache(self, tag, current):\n value = None\n \n if tag == 'buffermode':\n values = ['Buffer para todos los archivos de internet',\n 'Buffer para todos los archivos',\n 'Buffer solo para los archivos reales de internet',\n 'Sin buffer',\n 'Todos los archivos de red']\n \n items = []\n for i in range(len(values)):\n items.append(xbmcgui.ListItem(label=str(i), label2=values[i]))\n \n value = self.dialog.select('Selecciona un valor', items, preselect=int(current), useDetails=True)\n elif tag == 'memorysize':\n free_memory = tools.get_info_label('System.Memory(free)')\n free_converted = tools.convert_size(int(float(free_memory[:-2])) * 1024 * 1024)\n \n recommended = int(float(free_memory[:-2]) / 3) * 1024 * 1024\n recommended_converted = tools.convert_size(int(float(free_memory[:-2]) / 3) * 1024 * 1024)\n \n value = tools.get_keyboard(default='{0}'.format(recommended), heading='Tamano de memoria en Bytes\\n(Recomendado: {0} = {1})'.format(recommended_converted, recommended))\n elif tag == 'readfactor':\n value = tools.get_keyboard(default='{0}'.format(current), heading='Tasa de bits en Cache\\n(Cuanto mas alto el numero mas uso de red!)')\n \n return value\n \n def _network(self, tag, current):\n msgs = {'curlclienttimeout': 'Timeout en segundos para conexiones libcurl (http/ftp)',\n 'curllowspeedtime': 'Timeout en segundos para que libcurl lenta a una conexion',\n 'curlretries': 'Cantidad de intentos para ciertos archivos de operaciones con libcurl',\n 'httpproxyusername': 'Nombre de usuario para Proxy Basico',\n 'httpproxypassword': 'Password para Proxy Basico'}\n \n value = tools.get_keyboard(default='{0}'.format(current), heading=msgs[tag])\n \n return value\n \n def write_advanced(self, name, url):\n response = tools.open_url(url)\n\n if response:\n if os.path.exists(CONFIG.ADVANCED):\n choice = self.dialog.yesno(CONFIG.ADDONTITLE,\n \"[COLOR {0}]Quieres sobreescribir tu Advanced Settings with [COLOR {1}]{2}[/COLOR]?[/COLOR]\".format(\n CONFIG.COLOR2, CONFIG.COLOR1, name),\n yeslabel=\"[B][COLOR springgreen]Sobreescribir[/COLOR][/B]\",\n nolabel=\"[B][COLOR red]Cancelar[/COLOR][/B]\")\n else:\n choice = self.dialog.yesno(CONFIG.ADDONTITLE,\n \"[COLOR {0}]Quieres descargar e instalar [COLOR {1}]{2}[/COLOR]?[/COLOR]\".format(\n CONFIG.COLOR2, CONFIG.COLOR1, name),\n yeslabel=\"[B][COLOR springgreen]Instalar[/COLOR][/B]\",\n nolabel=\"[B][COLOR red]Cancelar[/COLOR][/B]\")\n\n if choice == 1:\n tools.write_to_file(CONFIG.ADVANCED, response.text)\n tools.kill_kodi(msg='[COLOR {0}]El nuevo advancedsettings.xml se ha escrito correctamente, pero los cambios no se aplicaran hasta que cierres Kodi.[/COLOR]'.format(\n CONFIG.COLOR2))\n else:\n logging.log(\"[Advanced Settings] instalacion canceleda\")\n logging.log_notify('[COLOR {0}]{1}[/COLOR]'.format(CONFIG.COLOR1, CONFIG.ADDONTITLE),\n \"[COLOR {0}]Escritura cancelada![/COLOR]\".format(CONFIG.COLOR2))\n return\n else:\n logging.log(\"[Advanced Settings] URL no valida: {0}\".format(url))\n logging.log_notify('[COLOR {0}]{1}[/COLOR]'.format(CONFIG.COLOR1, CONFIG.ADDONTITLE),\n \"[COLOR {0}]URL no valida[/COLOR]\".format(CONFIG.COLOR2))\n","sub_path":"plugin.program.hiddensd-matrix/resources/libs/advanced.py","file_name":"advanced.py","file_ext":"py","file_size_in_byte":13225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"275345263","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 24 16:28:52 2015\n\n@author: Lichao\n\"\"\"\n\n# %% import \nimport numpy as np\nimport re\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.metrics import roc_curve, auc\nhome = 'Y:/vault/pami/stat/airplane'\n# %% read and processing data\nnames = ['car','airplane','face','motorbike']\ncolors = ['c','b','y','g']\nt = dict()\nn_cat = 4\nfor i in range(4):\n fn = home+'/single_airplane_{0}.txt'.format(names[i])\n t[names[i]] = pd.read_csv(fn,sep='\\t',header=None, names=['indicator','filename','gid','pid','nid'])\n\n# %% read and processing data\np = dict()\nn_cat = 4\nplt.figure(figsize=(18,8.5))\nplt.title('Part activation')\nwidth = 0.2 \nfor i in range(4): \n tt = t[names[i]].groupby('pid').size()/t[names[i]].shape[0]\n p[names[i]]=plt.bar(tt.index+width*i,tt,color=colors[i],width=width, alpha=0.3)\nplt.legend(names)\nplt.show()\n# %% generate avg patches per part\ndef avgNodePerPart(t,names,n_cat):\n plt.figure(figsize=(18,8.5))\n plt.title('Part activation')\n width = 0.2 \n for i in range(n_cat):\n a = t[names[i]].groupby(['filename','gid','pid']).size()\n table1 = pd.DataFrame([(e[0][2],e[1]) for e in a.iteritems()],columns=['gid','pcount'])\n tt=table1.groupby('gid').mean()\n plt.bar(tt.index+width*i,tt.pcount,color=colors[i],width=width, alpha=0.3)\n plt.legend(names)\n plt.show()\n\navgNodePerPart(t,names,n_cat)\n\n# %% filtering hard images in airplane category\ngroupfn = r'Y:\\vault\\pami\\groups\\airplane_old\\single_airplane_400_airplane.txt'\nt1 = pd.read_csv(groupfn,sep='\\t',header=None, names=['filename','gid','quality'])\nt1c = t1.groupby('filename').max()['quality']\nfiles = t1c[t1c<10].index\nt_trimed = t.copy()\nt_trimed['airplane']=t_trimed['airplane'][t_trimed['airplane'].filename.isin(files)]\n\navgNodePerPart(t_trimed,names,n_cat)","sub_path":"script/pyroc/part_hist.py","file_name":"part_hist.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"575411679","text":"# From public key to address\n# Reference: https://medium.freecodecamp.org/how-to-create-a-bitcoin-wallet-address-from-a-private-key-eca3ddd9c05f\n# https://docs.python.org/2/library/hashlib.html\n# https://jun-wang-2018.github.io/MyBlog/en/ECDSA-and-Bitcoin-III/\nimport codecs #If not installed: \"pip3 install codecs\"\nimport hashlib\n# UK0 is a demo public key.\nUK0 = ['3a56bd64573c28050bfe202c57e56b46c63744a253d1430e2b737876fa883b19','73c2f565444dc62151562993ff4b566c826010befb289fa2fc749293266066c0']\nUK1 = \"04\" + UK0[0] + UK0[1]\nUK2 = hashlib.sha256(codecs.decode(UK1, 'hex'))\nh = hashlib.new('ripemd160')\nh.update(UK2.digest())\nUK3 = h.hexdigest()\nUK4 = \"00\" + UK3\nUK5 = hashlib.sha256(codecs.decode(UK4, 'hex'))\nUK6 = hashlib.sha256(UK5.digest())\nchecksum = codecs.encode(UK6.digest(), 'hex')[0:8]\nUK7 = UK4 + str(checksum)[2:10] #I know it looks wierd\n\n# Define base58\ndef base58(address_hex):\n alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n b58_string = ''\n # Get the number of leading zeros\n leading_zeros = len(address_hex) - len(address_hex.lstrip('0'))\n # Convert hex to decimal\n address_int = int(address_hex, 16)\n # Append digits to the start of string\n while address_int > 0:\n digit = address_int % 58\n digit_char = alphabet[digit]\n b58_string = digit_char + b58_string\n address_int //= 58\n # Add ‘1’ for each 2 leading zeros\n ones = leading_zeros // 2\n for one in range(ones):\n b58_string = '1' + b58_string\n return b58_string\n\nAddress = base58(UK7)\nprint(Address)","sub_path":"publickey_address.py","file_name":"publickey_address.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"645964533","text":"#!/home/romi/anaconda3/bin/python3\n\nimport torch, torchvision\nimport torch.nn as nn\nfrom torchvision import models\nfrom torchsummary import summary\nimport numpy as np\nfrom PIL import Image\nimport os\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\nimport time\n\n\n\n\n# In[11]:\n\n\nclass Classifier(nn.Module):\n def __init__(self,n_classes):\n super(Classifier, self).__init__()\n self.resnet = models.resnet34(pretrained = False)\n self.l1 = nn.Linear(1000 , 256)\n self.dropout = nn.Dropout(0.5)\n self.l2 = nn.Linear(256,n_classes) # 6 is number of classes\n self.relu = nn.LeakyReLU()\n def forward(self, input):\n x = self.resnet(input)\n x = x.view(x.size(0),-1)\n x = self.dropout(self.relu(self.l1(x)))\n x = self.l2(x)\n return x\n#device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n#print('Device: ',device)\n#classifier = Classifier(n_classes).to(device)\n#summary(classifier,(3,150,150)) #summary is used to create summary of our model similar to keras summary.\n\n\ndef main():\n\n \n im_size=256\n mean=0.5\n std=0.5\n batch_size=16\n model_dir='/home/romi/'\n #base_dir='/content/drive/My Drive/'\n valid_percentage=0.2\n criterion = nn.CrossEntropyLoss()\n n_classes=6\n\n init_instant = time.time()\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n #print('Device: ',device)\n classifier = Classifier(n_classes).to(device)\n classifier.load_state_dict(torch.load(model_dir+'checkpoint.pt'))\n model_loaded_instant =time.time()\n\n # In[57]:\n\n\n start_image_path='/home/romi/ORB_SLAM/bin/Tracking.jpg'\n end_image_path='/home/romi/ORB_SLAM/bin/TrackLost.png'\n\n\n # In[58]:\n\n\n start_image=Image.open(start_image_path)\n start_image_gray=start_image.convert(mode='L')\n\n end_image=Image.open(end_image_path)\n end_image_gray=end_image.convert(mode='L')\n image_loaded_instant = time.time()\n\n dummy_channel=Image.new(mode='L',size=end_image_gray.size)\n\n merged_image=Image.merge(mode='RGB',bands=(start_image_gray,end_image_gray,dummy_channel))\n \n test_transforms = transforms.Compose([\n transforms.Resize(size=im_size),\n transforms.CenterCrop(size=im_size), # Image net standards\n transforms.ToTensor(),\n transforms.Normalize((mean, mean, mean), (std, std, std))])\n\n\n # In[35]:\n\n\n labels={\n #0: 'To recover track , Please move in the forward direction',\n #1: 'To recover track , Please do Clockwise rotation',\n #2: 'To recover track , Please do Anti-Clockwise rotation',\n #3: 'To recover track , Please move in the backward direction',\n #4: 'To recover track , Please move Right',\n #5: 'To recover track , Please move Left'\n 0: 'Forward',\n 1: 'CW',\n 2: 'CCW',\n 3: 'Back',\n 4: 'Right',\n 5: 'Left'\n }\n\n\n # In[59]:\n\n\n sm = nn.Softmax(dim = 1)\n\n data=test_transforms(merged_image)\n data.unsqueeze_(0)\n data=Variable(data)\n data = data.type(torch.cuda.FloatTensor)\n image_preprocessed_instant = time.time()\n\n classifier.eval()\n output = classifier(data)\n image_classified_instant = time.time()\n #print('Here')\n print(\"\\n\\nClassifier commands the agent to move : \",labels[output.cpu().data.numpy().argmax()])\n fd = \"/home/romi/abc2.txt\"\n file = open(fd, 'w') \n file.write(labels[output.cpu().data.numpy().argmax()]) \n file.close() \n file = open(fd, 'r') \n text = file.read() \n #print(text) \n #print('End')\n print('Model Loading Time: ',model_loaded_instant-init_instant,' seconds')\n print('Image Loading Time: ',image_loaded_instant-model_loaded_instant,' seconds')\n print('Image Preprocessing Time: ',image_preprocessed_instant-image_loaded_instant,' seconds')\n print('Image Classification Time: ',image_classified_instant-image_preprocessed_instant,' seconds')\n\nif __name__== \"__main__\":\n main()\n\n","sub_path":"ImageClassifier.py","file_name":"ImageClassifier.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"425789627","text":"from random import randrange\n\n\ndef cross_val_split(dataset, n_folds):\n\tdataset_split = list()\n\tdataset_copy = list(dataset)\n\tfold_size = int(len(dataset) / n_folds)\n\tfor i in range(n_folds):\n\t\tfold = list()\n\t\twhile len(fold) < fold_size:\n\t\t\tindex = randrange(len(dataset_copy))\n\t\t\tfold.append(dataset_copy.pop(index))\n\t\tdataset_split.append(fold)\n\treturn dataset_split\n\n\ndef accuracy_metric(actual, pred):\n\tcorrect = 0\n\tfor i in range(len(actual)):\n\t\tif actual[i] == pred[i]:\n\t\t\tcorrect += 1\n\treturn correct/float(len(actual)) * 100.0\n\n\nclass Dataset:\n\tdef __init__(self, data):\n\t\tself.dataset = data\n\n\n\n\tdef str_col_to_float(self, col):\n\t\tfor row in self.dataset:\n\t\t\trow[col] = float(row[col].strip())\n\n\n\tdef str_col_to_int(self, col):\n\t\tclass_values = [row[col] for row in self.dataset]\n\t\tunique = set(class_values)\n\t\tlookup = dict()\n\t\tfor i, val in enumerate(unique):\n\t\t\tlookup[val]=i\n\t\tfor row in self.dataset:\n\t\t\trow[col] = lookup[row[col]]\n\t\treturn lookup\n\n\n\tdef minmax(self):\n\t\tminmax = list()\n\t\tstats = [[min(col), max(col)] for col in zip(*self.dataset)]\n\t\treturn stats\n\n\n\tdef normalize(self, minmax):\n\t\tfor row in self.dataset:\n\t\t\tfor i in range(len(row)-1):\n\t\t\t\trow[i] = (row[i]-1 - minmax[i][0]) / (minmax[i][1] - minmax[i][0])\n\n\n\tdef cross_val_split(self, n_folds):\n\t\tdataset_split = list()\n\t\tdataset_copy = list(self.dataset)\n\t\tfold_size = int(len(self.dataset) / n_folds)\n\t\tfor i in range(n_folds):\n\t\t\tfold = list()\n\t\t\twhile len(fold) < fold_size:\n\t\t\t\tindex = randrange(len(dataset_copy))\n\t\t\t\tfold.append(dataset_copy.pop(index))\n\t\t\tdataset_split.append(fold)\n\t\treturn dataset_split\n\n\n\t\n\n\n\tdef eval_algo(self, algo, n_folds, *args):\n\t\tfolds = cross_val_split(self.dataset, n_folds)\n\t\tscores = list()\n\t\tfor fold in folds:\n\t\t\ttrain_set = list(folds)\n\t\t\ttrain_set.remove(fold)\n\t\t\ttrain_set = sum(train_set, [])\n\t\t\ttest_set = list()\n\t\t\tfor row in fold:\n\t\t\t\trow_copy = list(row)\n\t\t\t\ttest_set.append(row_copy)\n\t\t\t\trow_copy[-1] = None\n\t\t\tpred = algo(train_set, test_set, *args)\n\t\t\tactual = [row[-1] for row in fold]\n\t\t\tacc = accuracy_metric(actual, pred)\n\t\t\tscores.append(acc)\n\t\treturn scores\n","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"115806787","text":"class Library:\n def __init__(self, list, name):\n self.booksList = list\n self.name = name\n self.lendDict = {}\n\n def displaybooks(self):\n print(f'We Have Following Books in Our Library: {self.name}\\n')\n for book in self.booksList:\n print(book)\n\n def lendBooks(self, user, book):\n if book not in self.lendDict.keys():\n self.lendDict.update({book:user})\n print('Lander-Book Has been Updated. You Can take the book now.\\n')\n else:\n print(f'Book is already being used by {self.lendDict[book]}')\n \n def addBooks(self, book):\n self.booksList.append(book)\n print('Book Has been added Successfully...\\n')\n\n def returnBook(self, book):\n self.lendDict.pop(book)\n\n\nif __name__ == '__main__':\n shazzy = Library(['Python', 'Java', 'Data Structure', 'C++', 'Pak Study'], \"Shahzaib RInd\")\n\n while(True):\n print(f'\\t\\tWelcome to the {shazzy.name} Library. Enter your Choice to Continue: \\n')\n print('1. Display Books: ')\n print('2. Lend a Book: ')\n print('3. Add a Book: ')\n print('4. Return a Book: \\n')\n\n choice = input('Enter Your Choice: ')\n if choice not in ['1', '2', '3', '4']:\n print('\\nPlease Enter A valid Option.\\n')\n continue\n else:\n choice = int(choice)\n if choice == 1:\n shazzy.displaybooks()\n\n elif choice == 2:\n book = input(\"Enter the Name of the book you want to lend: \")\n user = input('Enter your Name: ')\n shazzy.lendBooks(user, book)\n\n elif choice == 3:\n book = input('Enter the Name of the book you want to Add: ')\n shazzy.addBooks(book)\n\n elif choice == 4:\n book = input('Enter the Name of the book you want to Return: \\n')\n shazzy.returnBook(book)\n print(\"Book has been Returned Successfully...\\n\")\n\n else:\n print('Not a Valid Option!!!\\n')\n\n print('Press q to Quit and c to Continue: ')\n choice2 = ''\n while(choice2 != 'c' and choice2 != 'q'):\n choice2 = input()\n if choice2 == 'q':\n exit()\n if choice2 == 'c':\n continue","sub_path":"LMS.py","file_name":"LMS.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"279841382","text":"\n\nimport csv\nimport math\nimport os\nimport sys\nimport time\n\nimport pygame\nfrom .button import Button\nfrom conf.settings import *\n\n\nclass Manager:\n \"\"\" 游戏管理类 \"\"\"\n\n def __init__(self, lev_obj):\n self.dir = os.path.abspath(os.path.dirname(__file__))\n self.clock = pygame.time.Clock() # 时间管理对象\n self.running = True # 游戏运行开关\n self.img_init() # 图片初始化\n self.button = Button(self)\n self.lev_obj = lev_obj # 游戏等级类对象\n # {0: 终止状态, 1: \"运行状态\", 2: \"暂停状态\" }\n self.state = 0 # 游戏状态\n self.success_switch = False # 成功页面开关\n self.score_dict = {} # 得分字典\n self.high_score_dict = {} # 最高得分字典\n\n def img_init(self):\n \"\"\" 全局设置 \"\"\"\n self.image = pygame.image.load(PUZZLE_IMG)\n # 拼接图 Sur\n if self.image.get_width() >= IMG_WIDTH and self.image.get_height() > IMG_WIDTH * 0.5:\n self.game_img = pygame.transform.scale(self.image, \\\n (IMG_WIDTH, math.ceil(self.image.get_height() * (IMG_WIDTH / self.image.get_width()))))\n self.show_img = pygame.transform.scale(self.image, \\\n (math.ceil(IMG_WIDTH * 0.4), \\\n math.ceil(self.game_img.get_height() * 0.4)))\n else:\n raise(\"This picture is too small (W > \" + str(IMG_WIDTH) + \", H > \" + \\\n str(IMG_WIDTH * 0.5) + \")! Please get me a bigger one .....\")\n self.game_rect = self.game_img.get_rect()\n self.show_rect = self.show_img.get_rect()\n self.show_rect.topleft = (10, 100)\n self.game_rect.topleft = (self.show_rect.width + 20, 100)\n\n # 窗口 Sur\n self.screen_size = (self.game_rect.width + self.show_rect.width + 30, \\\n self.game_rect.height + 110)\n self.screen = pygame.display.set_mode(self.screen_size)\n self.screen_rect = self.screen.get_rect()\n # 主界面背景图Sur\n self.background_sur = pygame.image.load(BG_IMG)\n # 等级步数背景图Sur\n self.control_sur = pygame.image.load(CONTROL_IMG)\n\n # 通关图 Sur\n self.success_sur = pygame.image.load(GOOD_IMG)\n self.success_rec = self.success_sur.get_rect()\n self.success_rec.center = self.screen_rect.center\n # 结束页面背景图Sur\n self.over_sur = pygame.image.load(GRADE_IMG)\n\n def page_reset(self):\n \"\"\" 页面数据重置 \"\"\"\n self.state = 0 # 设为游游戏为终止状态\n self.success_switch = True # 打开成功拼图开关\n self.button.start_text = self.button.button_text[\"stop\"]\n self.button.button_bg_color = \"yellow\"\n self.button.stop_time = pygame.time.get_ticks()\n self.record_grade() # 记录得分\n\n # 游戏页面绘制初始化\n def init_page(self):\n \"\"\" 游戏页面绘制初始化 \"\"\"\n\n # 拼图成功判断\n if not self.success_switch:\n if self.lev_obj.is_success():\n self.page_reset()\n # 绘制背景图\n self.screen.blit(self.background_sur, (0, 0))\n # 绘制等级步数背景图\n self.screen.blit(self.control_sur, (10, self.show_rect.bottom))\n # 绘制标题\n self.draw_text(\"简 易 拼 图 游 戏\", 44, (0, 0, 0), \\\n self.screen_rect.width, 15, True)\n # 绘制参考图\n self.screen.blit(self.show_img, self.show_rect)\n # 绘制矩阵拼图 button_text\n for row, li in enumerate(self.lev_obj.frame):\n for col, val in enumerate(li):\n posi = (col * self.lev_obj.grid_width + self.game_rect[0], \\\n row * self.lev_obj.grid_height + self.game_rect[1])\n if val == -1:\n if not self.success_switch:\n pygame.draw.rect(self.screen, (255, 255, 255), \\\n (posi[0], posi[1], self.lev_obj.grid_width, \\\n self.lev_obj.grid_height))\n else:\n self.lev_obj.frame[row][col] = self.lev_obj.blank[0] * \\\n self.lev_obj.col_num + \\\n self.lev_obj.blank[1]\n sub_row = self.lev_obj.frame[row][col] // self.lev_obj.col_num\n sub_col = self.lev_obj.frame[row][col] % self.lev_obj.col_num\n sub_posi = (sub_col * self.lev_obj.grid_width, sub_row * \\\n self.lev_obj.grid_height, self.lev_obj.grid_width, \\\n self.lev_obj.grid_height)\n self.screen.blit(self.game_img, posi, sub_posi)\n if not self.success_switch:\n # 绘制分隔线_横线\n for i in range(self.lev_obj.row_num + 1):\n start_pos = [self.game_rect[0], self.game_rect[1] + \\\n i * self.lev_obj.grid_height]\n end_pos = [self.game_rect[0] + self.game_rect.width, \\\n self.game_rect[1] + i * self.lev_obj.grid_height]\n pygame.draw.line(self.screen, (0, 0, 0.5), start_pos, end_pos, 1)\n # 绘制分隔线_竖线\n for i in range(self.lev_obj.col_num + 1):\n start_pos = [self.game_rect[0] + i * self.lev_obj.grid_width, \\\n self.game_rect[1]]\n end_pos = [self.game_rect[0] + i * self.lev_obj.grid_width, \\\n self.game_rect[1] + self.game_rect.height]\n pygame.draw.line(self.screen, (0, 0, 0.5), start_pos, end_pos, 1)\n # 绘制等级\n self.draw_text(\"等 级:%d\"% self.lev_obj.game_level, 26, (255, 255, 255), \\\n self.show_rect.width, self.show_rect.bottom + 32, True)\n # 绘制步数\n self.draw_text(\"步 数:%d\"% self.lev_obj.step, 26, (255, 255, 255), \\\n self.show_rect.width, self.show_rect.bottom + 82, True)\n # 绘制时间\n self.draw_text(\"时 间:%d s\"% round(self.button.running_time // 1000), \\\n 26, (255, 255, 255), self.show_rect.width, \\\n self.show_rect.bottom + 132, True)\n pygame.draw.rect(self.screen, (255, 255, 255), \\\n (0, self.screen_rect.bottom - 10, self.screen_rect.width, 10))\n # 绘制按钮\n self.button.draw_button()\n # 绘制成功页面\n if self.success_switch:\n self.success_page()\n\n # 矩阵事件监听\n def listen_event(self, event):\n \"\"\" 事件监听 \"\"\"\n if not self.success_switch:\n # 矩阵事件监听\n if self.state == 1:\n # 键盘事件\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n sys.exit()\n \"\"\" {上: 1, 右:2, 下:3, 左:4 } \"\"\"\n if event.key in [K_UP, K_w, K_w - 62]:\n self.lev_obj.operate(1)\n elif event.key in [K_RIGHT, K_d, K_d - 62]:\n self.lev_obj.operate(2)\n elif event.key in [K_DOWN, K_s, K_s - 62]:\n self.lev_obj.operate(3)\n elif event.key in [K_LEFT, K_a, K_a - 62]:\n self.lev_obj.operate(4)\n # 鼠标按下事件\n if event.type == MOUSEBUTTONDOWN and event.button == 1:\n mouse_x, mouse_y = event.pos\n row = int(mouse_y - self.game_rect[1]) // self.lev_obj.grid_height\n col = int(mouse_x - self.game_rect[0]) // self.lev_obj.grid_width\n row_diff = row - self.lev_obj.blank[0]\n col_diff = col - self.lev_obj.blank[1]\n if row_diff == 1 and col_diff == 0:\n self.lev_obj.operate(1)\n elif row_diff == -1 and col_diff == 0:\n self.lev_obj.operate(3)\n elif row_diff == 0 and col_diff == 1:\n self.lev_obj.operate(4)\n elif row_diff == 0 and col_diff == -1:\n self.lev_obj.operate(2)\n # 按钮事件监听\n self.button.listen_event(event)\n else:\n # 监听成绩页面事件\n self.success_page(event)\n\n def success_page(self, event = False):\n \"\"\" 通关恭喜页面事件监听与绘制 \"\"\"\n if event:\n if event.type == KEYDOWN:\n # 下一关, 组合键(Ctrl + n)\n if event.key in [K_n, K_n - 62]:\n if event.mod in [KMOD_LCTRL, KMOD_RCTRL]:\n self.lev_obj.reset()\n self.success_switch = False\n # 退出, 进入成绩界面。组合键(Ctrl + q)\n if event.key in [K_q, K_n - 62]:\n if event.mod in [KMOD_LCTRL, KMOD_RCTRL]:\n self.show_quit_screen()\n if event.type == MOUSEBUTTONDOWN and event.button == 1:\n mouse_x, mouse_y = event.pos\n if (mouse_x - self.success_rec.left) in range(60, 320):\n # 下一关\n if (mouse_y - self.success_rec.top) in range(210, 260):\n self.lev_obj.reset()\n self.success_switch = False\n # 退出\n if (mouse_y - self.success_rec.top) in range(260, 310):\n self.show_quit_screen()\n # 页面绘制\n else:\n # 绘制恭喜通关图\n self.screen.blit(self.success_sur, self.success_rec)\n\n def draw_text(self, text, size, color, x, y, center = False):\n \"\"\" 文本绘制 \"\"\"\n font = pygame.font.Font(FONT_FILE, size)\n text_surface = font.render(text, True, color)\n text_rect = text_surface.get_rect()\n if center:\n text_rect.topleft = (x // 2 - text_rect.width // 2, y)\n else:\n text_rect.topleft = (x, y)\n self.screen.blit(text_surface, text_rect)\n\n def write_data(self, data):\n \"\"\" 向文件写入数据 \"\"\"\n if type(data) != dict:\n raise(\" 写入文件数据:\", data, \"类型不为字典.......\")\n file_path = os.path.join(self.dir, \"grade.csv\")\n with open(file_path, 'w', newline='') as f:\n writer = csv.writer(f)\n for lev, dic in data.items():\n writer.writerow([str(lev), str(dic[\"time\"]), str(dic[\"step\"])])\n\n def load_data(self):\n \"\"\" 加载数据 \"\"\"\n file_path = os.path.join(self.dir, \"grade.csv\")\n res = {}\n if not os.path.exists(file_path):\n raise (file_path, \"文件不存在, 读取数据失败!\")\n with open(file_path, 'r') as f:\n reader = csv.reader(f)\n for li in list(reader):\n res[int(li[0])] = {}\n res[int(li[0])][\"time\"] = int(li[1])\n res[int(li[0])][\"step\"] = int(li[2])\n return res\n\n def record_grade(self):\n \"\"\" 记录得分 \"\"\"\n self.score_dict[self.lev_obj.game_level] = {}\n self.score_dict[self.lev_obj.game_level][\"time\"] = self.button.cul_time()\n self.score_dict[self.lev_obj.game_level][\"step\"] = self.lev_obj.step\n\n def show_quit_screen(self):\n \"\"\" 游戏退出页面 \"\"\"\n self.screen.fill((54, 59, 64))\n # 绘制背景图\n self.screen.blit(self.over_sur, (0, 0))\n # 读取最高分文件数据\n self.high_score_dict = self.load_data()\n line = 1\n # 只展示最后 8 关的 有游戏数据\n if len(self.score_dict) > 8:\n for i in range(1, len(self.score_dict) - 8 + 1):\n self.score_dict.pop(i)\n # 绘制各关卡游戏数据\n for lev, dic in self.score_dict.items():\n now = dic[\"time\"] * 0.4 + dic[\"step\"] * 0.6\n try:\n ago = self.high_score_dict[lev][\"time\"] * 0.4 + self.high_score_dict[lev][\"step\"] * 0.6\n except Exception as e:\n ago = 0\n self.high_score_dict[lev] = {}\n self.high_score_dict[lev][\"time\"] = dic[\"time\"]\n self.high_score_dict[lev][\"step\"] = dic[\"step\"]\n time_list = time.ctime(round(dic[\"time\"] / 1000)).split(\" \")[4].split(\":\")\n time_list[0] = str(int(time_list[0]) - 8)\n time_str = \":\".join(time_list).center(22)\n # 创造历史\n if now < ago or ago == 0:\n self.draw_text(str(lev).center(26) + time_str + str(dic[\"step\"]).center(22) + \"Yes\".center(44), \\\n 26, (255, 0, 0), 150, 155 + 40 * line)\n # 如果得分出现新记录,保存下来\n if ago != 0:\n self.high_score_dict[lev][\"time\"] = dic[\"time\"]\n self.high_score_dict[lev][\"step\"] = dic[\"step\"]\n else:\n self.draw_text(str(lev).center(26) + time_str + str(dic[\"step\"]).center(22) + \"No\".center(44), \\\n 26, (0, 0, 0), 150, 155 + 40 * line)\n line += 1\n # 将最好成绩记录文件\n self.write_data(self.high_score_dict)\n self.draw_text(\"Press a key to play again\", 30, (255, 255, 255), self.screen_rect.width, \\\n self.screen_rect.bottom - 60, True)\n pygame.display.update()\n self.wait_for_key()\n\n def wait_for_key(self):\n \"\"\" 程序退出循环 \"\"\"\n waiting = True\n while waiting:\n self.clock.tick(FPS)\n for event in pygame.event.get():\n if event.type in [KEYDOWN, QUIT]:\n waiting = False\n self.running = False\n\n","sub_path":"core/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":14242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"203450945","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win-amd64\\egg\\responder3\\__main__.py\n# Compiled at: 2019-08-15 18:46:23\n# Size of source mod 2**32: 514 bytes\nimport sys, asyncio\nfrom responder3.core.responder3 import Responder3\n\ndef main():\n loop = asyncio.get_event_loop()\n parser = Responder3.get_argparser()\n if len(sys.argv) < 2:\n parser.print_usage()\n return\n responder3 = Responder3.from_args(parser.parse_args())\n if responder3:\n loop.run_until_complete(responder3.run())\n print('Responder finished!')\n\n\nif __name__ == '__main__':\n main()","sub_path":"pycfiles/Responder3-0.0.1-py3.7/__main__.cpython-37.py","file_name":"__main__.cpython-37.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"274346628","text":"import dash\r\nfrom dash import dcc\r\nfrom dash import html\r\nfrom dash.dependencies import Input, Output\r\nimport plotly.express as px\r\nimport requests\r\nimport pandas as pd\r\n\r\n\r\napp = dash.Dash(__name__)\r\nserver=app.server\r\n\r\nurl = 'https://covid19.schoolkidrich.repl.co/api/state=cases'\r\nreq = requests.get(url)\r\nstates = list(req.json().get('valid_states'))\r\noptions = ['ALL'] + sorted(states)\r\nchoices = [{'label': i, 'value': i} for i in options]\r\n\r\napp.layout = html.Div(children=[\r\n html.H1(children='Covid 19 Tracker'),\r\n html.H3(children='Daily Plot'),\r\n html.Label('Select Plot'),\r\n dcc.RadioItems(\r\n id='plot_type',\r\n options=[\r\n {'label': 'Cases', 'value': 'Cases'},\r\n {'label': 'Deaths', 'value': 'Deaths'}\r\n ],\r\n value='Cases'\r\n ),\r\n html.Br(),\r\n html.Label('Select State'),\r\n dcc.Dropdown(\r\n id='case_state',\r\n options=choices,\r\n value='ALL',\r\n clearable=False\r\n ),\r\n dcc.Graph(\r\n id='daily_plot'\r\n ),\r\n html.Br(),\r\n html.H3(children='Cumulative Plot'),\r\n html.Label('Select Plot'),\r\n dcc.RadioItems(\r\n id='plot_type2',\r\n options=[\r\n {'label': 'Cases', 'value': 'Cases'},\r\n {'label': 'Deaths', 'value': 'Deaths'}\r\n ],\r\n value='Cases'\r\n ),\r\n html.Br(),\r\n html.Label('Select State'),\r\n dcc.Dropdown(\r\n id='cumulative_state',\r\n options=choices,\r\n value='ALL',\r\n clearable=False\r\n ),\r\n dcc.Graph(\r\n id='cumulative_plot'\r\n )\r\n])\r\n\r\n\r\ndef get_data(state):\r\n link = f'https://covid19.schoolkidrich.repl.co/api/state={state}'\r\n request = requests.get(link)\r\n df = pd.DataFrame(request.json())\r\n return df\r\n\r\n\r\ndef get_cumulative(df):\r\n df = df.set_index('date').cumsum()\r\n return df.reset_index()\r\n\r\n\r\n#fig 1 (num cases)\r\n@app.callback(\r\n Output('daily_plot', 'figure'),\r\n [Input('case_state', 'value'),\r\n Input('plot_type', 'value')]\r\n)\r\ndef plot_daily(case_state, plot_type):\r\n if plot_type == 'Cases':\r\n color = '#2ca02c'\r\n else:\r\n color = '#d62728'\r\n\r\n df = get_data(case_state)\r\n fig = px.line(df, title=f'Daily Number of {plot_type} [{case_state}]',\r\n x='date', y=plot_type.lower())\r\n fig.update_traces(line_color=color)\r\n return fig\r\n\r\n\r\n#fig 2 (cumulative cases)\r\n@app.callback(\r\n Output('cumulative_plot', 'figure'),\r\n [Input('cumulative_state', 'value'),\r\n Input('plot_type2', 'value')]\r\n)\r\ndef plot_cumulative(cumulative_state, plot_type2):\r\n if plot_type2 == 'Cases':\r\n color = '#2ca02c'\r\n else:\r\n color = '#d62728'\r\n\r\n df = get_data(cumulative_state)\r\n cumulative = get_cumulative(df)\r\n fig = px.line(cumulative, title=f'Total Number of {plot_type2} [{cumulative_state}]',\r\n x='date', y=plot_type2.lower())\r\n fig.update_traces(line_color=color)\r\n return fig\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run_server(debug=True)\r\n","sub_path":"DATA_608/final/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"297896282","text":"\"\"\"\ninput: 121\noutput:True because reverse(121) == 123,if input = 123,return False\nauthor:yqtong@stu.xmu.edu.cn\ndata:2019-09-13\n\"\"\"\n\n\nclass Solution:\n def isPalindrome(self, x: int) -> bool:\n result = str(x)\n first_str = result\n second_str = ''\n for idx in range(len(result), 0, -1):\n second_str += result[idx - 1]\n\n if first_str == second_str:\n return True\n else:\n return False","sub_path":"Algorithm/9_palindrome_number.py","file_name":"9_palindrome_number.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"92016265","text":"from rest_framework import serializers\nfrom project.models import Project\n\nfrom django.contrib.auth.models import User\n\nclass ProjectSerializer(serializers.HyperlinkedModelSerializer):\n owner = serializers.ReadOnlyField(source='owner.username')\n class Meta:\n model = Project\n fields = ('url', 'id', 'title', 'description', 'owner')\n\nclass UserSerializer(serializers.HyperlinkedModelSerializer):\n # projects = serializers.PrimaryKeyRelatedField(many=True, queryset=Project.objects.all())\n projects = serializers.HyperlinkedRelatedField(many=True, view_name='project-detail', read_only=True)\n \n class Meta:\n model = User\n fields = ('url', 'id', 'username', 'projects')\n","sub_path":"project/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"1685613","text":"def count_char(my_text,letter):\n out = my_text.lower()\n number_lower = out.count(letter)\n\n out1 = my_text.upper()\n number_upper = out1.count(letter)\n\n number_sum = number_lower + number_upper\n\n return (number_sum)\n\n\n\n\nn = count_char(\"Ala ma kotA\",'a')\nprint(n) # 4\nn = count_char(\"ala ma kota\",'A')\nprint(n) # 4\nn = count_char(\"Python is easy\",'a')\nprint(n) # 1","sub_path":"exercise_5.py","file_name":"exercise_5.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"41874680","text":"'''\nAI for dodgey_dodgey.\n'''\n\nimport numpy as np, random, time\nimport dodgey_dodgey_framework as ddf\nimport genetic_framework as gf\n\n\n#Rate the AI by how \"safe\" it is: ie, tree looks forward 3-4 turns, assigns a threat to each outcome\n#Genetic algorithm, regresses on underlying grid\n\ndef manhattan_distance(x1,y1,x2,y2):\n return abs(x1-x2) + abs(y1-y2)\n\ndef print_char(x):\n if (x == np.array([0,0,0,0,1])).all():\n return 'P'\n if sum(x) == 0:\n return ' '\n if x[-1] == 1 and sum(x) >= 2:\n return 'O'\n if sum(x) >= 2:\n return 'X'\n else:\n return 'v^><'[x.argmax()]\n\ndef construct_subgrid(grid, view = 2):\n y, x = list(zip(*np.where(grid[...,-1] == 1)))[0]\n base = np.zeros((2*view + 1, 2*view + 1,5))\n sub = grid[max(0,y-view):y+view+1, max(0,x-view):x+view+1,:]\n ypos, xpos = list(zip(*np.where(sub[...,-1] == 1)))[0]\n #should only use ypos and xpos\n lower_y, lower_x = max(0, view - ypos), max(0, view - xpos)\n upper_y, upper_x = lower_y + sub.shape[0], lower_x + sub.shape[1]\n base[lower_y:upper_y, lower_x:upper_x,:] = sub\n '''\n try: base[lower_y:upper_y, lower_x:upper_x,:] = sub\n except ValueError:\n print(base[lower_y:upper_y, lower_x:upper_x,:],sub, sep = '\\n')\n raise ValueError\n '''\n return base\n\ndef sum_around(y, x, grid):\n directions = [(0,0),(0,1),(0,-1),(1,0),(-1,0)]\n total = 0\n for d in directions:\n try:\n total += grid[y+d[0], x+d[1]] \n except IndexError:\n continue\n return total\n\ndef star_sum(y, x, grid, stars = 2, weights = None):\n directions = [(0,1),(0,-1),(1,0),(-1,0)]\n if weights is None:\n weights = [1] * stars + 2\n if stars == 1:\n return weights[0] * sum_around(y, x, grid) \n else:\n return weights[0] * sum(star_sum(y+d[0],x+d[1],grid,stars=stars-1, weights = weights[1:]) for d in directions)\n\n\n#Create threat grid: for each arrow, add some value based off of decider coeffs to the locations in the direction of the arrow. \n\n'''\nNOTE: AI ONLY HAS TO CALCULATE EVERY OTHER SPACE FOR DANGER! Arrows directly next to it do not have the ability to harm it.\n'''\n\nclass DirectionalRegressor:\n def __init__(self, grid_size, mutation_rate = 0.1, stars = 2):\n self.coeffs = np.random.rand(grid_size) * 200 - 100\n self.grid_size = grid_size\n self.mutation_rate = mutation_rate\n self.stars = stars\n self.star_weights = np.random.rand(stars + 2) * 200 - 100 \n self.prev_pos = (0,0)\n self.curr_pos = (0,0)\n self.prev = '--'\n self.limit = 1\n\n def threat_grid(self, v_subgrid):\n threat = np.zeros(v_subgrid.shape[:-1])\n center = len(v_subgrid)//2; center = (center, center)\n transformer = np.array([[1,0],[-1,0],[0,1],[0,-1]])\n locations = lambda v, xy: [[tuple(transformer[k]*l + xy) for l in range(1, len(self.coeffs))] for k in range(4) if v[k] == 1]\n for i in range(len(v_subgrid[0])):\n for j in range(len(v_subgrid)):\n if manhattan_distance(i,j,*center) % 2 == 0 and sum(v_subgrid[j,i]) != 0:\n locs = locations(v_subgrid[j,i], (j,i))\n for row in locs:\n for m in range(len(row)):\n try:\n threat[row[m]] += self.coeffs[m]\n except IndexError:\n break\n #print(threat)\n return threat\n\n def decider(self, board): \n self.curr_pos = (board.player.y, board.player.x)\n threat = self.threat_grid(construct_subgrid(board.grid, view = self.stars))\n x = y = len(threat) // 2\n directions = [(0,1),(0,-1),(1,0),(-1,0)]\n moves = 'swda'\n levels = np.array([star_sum(y+d[1], x+d[0], threat,self.stars,\n weights = self.star_weights[:-1]) for d in directions])\n #[print('v^><'[i],levels[i]) for i in range(4)]\n new = levels.argmin()\n while self.prev_pos == self.curr_pos and moves[new] in self.prev[self.limit:]:\n levels[new] = levels.max() + 1\n new = levels.argmin()\n self.limit -= 1\n self.prev_pos = self.curr_pos\n self.limit = 1\n self.prev = self.prev[-1] + moves[new]\n return moves[new]\n\n def mate(self, other):\n new = DirectionalRegressor(self.grid_size, self.mutation_rate, self.stars)\n if random.random() <= self.mutation_rate:\n return new\n else:\n new.coeffs = (self.coeffs + other.coeffs) / 2\n new.star_weights = (self.star_weights + other.star_weights) / 2\n return new\n\n def fitness(self, grid_size = 7):\n board = ddf.GameGrid(grid_size)\n return ddf.play_game(board, self.decider, printing = False)\n\n#===================================================================================\ndef main():\n GRIDSIZE = 7\n fitness = lambda x: sum(DirectionalRegressor.fitness(x, GRIDSIZE) for i in range(30))/30\n algo = gf.Evolution(GRIDSIZE, fitness, DirectionalRegressor.mate, species=DirectionalRegressor)\n ls = []\n for i in range(20):\n prime, score = algo.evolve(30, 1, 0.5)\n ls.append(score)\n #time.sleep(5)\n ddf.play_game(ddf.GameGrid(GRIDSIZE), prime.decider, sleep = 0, printing = False)\n #time.sleep(15)\n print(ls)\n\nif __name__ == '__main__':\n main()\n\n\n\n\n","sub_path":"ai/dodgey_dodgey/genetic_dodgey_AI.py","file_name":"genetic_dodgey_AI.py","file_ext":"py","file_size_in_byte":5542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"601417815","text":"from utils import parser\nimport csv\nimport os\nbasepath = os.path.dirname(os.path.abspath(__file__))\npathname = '/dist/'\ndata_dict = dict()\nfilenames = parser.getFiles(basepath + pathname)\nfor filename in filenames:\n data = parser.getDataFile(filename)\n close_prices = [x['Close'] for x in data]\n data_dict[parser.removeExtension(filename)] = close_prices\n\nparser.generateSummary(data_dict, 'summary.csv', basepath + '/build/')","sub_path":"summary.py","file_name":"summary.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"23919162","text":"import glob\nfrom nltk.corpus import wordnet as wn\nfrom nltk.wsd import lesk\nfrom nltk.parse import CoreNLPParser\n\n\ndef hypernym_of(synset1, synset2):\n \"\"\" Returns True if synset2 is a hypernym of \n synset1, or if they are the same synset. \n Returns False otherwise. \"\"\"\n if synset1 == synset2:\n return True\n for hypernym in synset1.hypernyms():\n if synset2 == hypernym: \n return True\n if hypernym_of(hypernym, synset2): \n return True\n for inst_hypernym in synset1.instance_hypernyms():\n if synset2 == inst_hypernym: \n return True\n if hypernym_of(inst_hypernym, synset2): \n return True\n return False\n\n\ndef tag_named_entities(tokens):\n return nec_tokens\n\n\ndef main():\n path_list = glob.glob('dev/*/*/*.tok.off.pos')\n print(path_list)\n for path in path_list:\n print(path)\n with open(path) as f:\n ner_tagger = CoreNLPParser(url='http://localhost:9000', tagtype='ner')\n rawText = f.read()\n\n sents = rawText.split('\\n') # tokenize rawText to sentences\n sents.pop() # remove useless newline at end of every file\n tokens = [sent.split()[3] for sent in sents]\n nec_tokens = ner_tagger.tag(tokens)\n #print(\"Tokens: {}\".format(len(tokens)))\n #print(\"NEC: {}\".format(len(nec_tokens)))\n j = 0\n for i in range(len(tokens)):\n token = nec_tokens[j][0]\n token = token.replace('`', \"'\")\n token = token.replace('-LRB-', '(')\n token = token.replace('-RRB-', ')')\n token = token.replace(\"''\", '\"')\n while token != tokens[i]:\n #print(\"Merging tokens!\")\n j += 1\n token += nec_tokens[j][0]\n token = token.replace('`', \"'\")\n token = token.replace('LBR', '(')\n token = token.replace('RBR', ')')\n token = token.replace(\"''\", '\"')\n #print(tokens[i])\n #print(token)\n #print(token == tokens[i])\n #print(token)\n #print(tokens[i])\n nec = nec_tokens[j][1]\n #if nec != 'O':\n # print(token)\n # print(nec)\n pos = sents[i].split()[4]\n if nec == 'PERSON':\n sents[i] += ' PER'\n elif nec == 'ORGANIZATION':\n sents[i] += ' ORG'\n elif nec == 'COUNTRY' or nec == 'STATE_OR_PROVINCE':\n sents[i] += ' COU'\n elif nec == 'CITY':\n sents[i] += ' CIT'\n elif nec == 'LOCATION':\n lesk_synset = lesk(tokens, token, 'n')\n if lesk_synset and (hypernym_of(lesk_synset, wn.synset('country.n.02')) or hypernym_of(lesk_synset, wn.synset('state.n.01'))):\n sents[i] += ' COU'\n elif lesk_synset and (hypernym_of(lesk_synset, wn.synset('city.n.01')) or hypernym_of(lesk_synset, wn.synset('town.n.01'))):\n sents[i] += ' CIT'\n else:\n sents[i] += ' NAT'\n elif pos == 'NN' or pos == 'NNS':\n lesk_synset = lesk(tokens, token, 'n')\n if lesk_synset and hypernym_of(lesk_synset, wn.synset('animal.n.01')):\n sents[i] += ' ANI'\n elif lesk_synset and hypernym_of(lesk_synset, wn.synset('sport.n.01')):\n sents[i] += ' SPO'\n elif (pos == 'NNP' or pos == 'NNPS') and not lesk(tokens, token):\n sents[i] += ' ENT'\n j += 1\n \n \n #pos_tokens = nltk.pos_tag(tokens)\n #for i in range(len(sents)):\n # sents[i] += \" \" + pos_tokens[i][1]\n out_text = \"\\n\".join(sents)\n\n f = open(path + \".wncorenlp\", \"w\")\n print(out_text, file = f)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"final_project/final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":4172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"18215387","text":"import plugins\nfrom commands import command\nimport sqlite3\n\ndef _initialize():\n plugins.register_admin_command(['approve'])\n\ndef approve(bot, event, *args):\n conn = sqlite3.connect('bot.db')\n request = args[0]\n request_number = str(args[1])\n if request.lower() == 'poll':\n if not bot.memory.exists([\"requests\"]):\n yield from bot.coro_send_message(event.conv, _(\"No requests\"))\n return\n else:\n path = bot.memory.get_by_path(\n [\"requests\", \"polls\", str(request_number)])\n conversation_id = path.split()[0]\n command_to_run = path.split()[2:]\n yield from command.run(bot, event, *command_to_run)\n yield from bot.coro_send_message(conversation_id, _(\"Poll {} approved\").format(request_number))\n return\n elif request.lower() == 'quote':\n c = conn.cursor()\n c.execute('SELECT * FROM unapp_quotes WHERE id = ?', [request_number])\n q = c.fetchone() \n c.execute(\"INSERT INTO quotes(author, quote) VALUES (?, ?)\", [q[0], q[1]])\n conn.commit()\n yield from bot.coro_send_message(event.conv, _(\"Quote {} approved\").format(c.lastrowid))\n else:\n yield from bot.coro_send_message(event.conv, _(\"Approval for that not yet supported\"))\n","sub_path":"hangupsbot/plugins/approve.py","file_name":"approve.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"647851896","text":"def juhuslik_bingo():\r\n from random import sample\r\n e = []\r\n for a in range(5):\r\n arvud = sample(range(a*15+1, a*15+16), 5)\r\n e.append(arvud)\r\n tabel = zip(*e)\r\n o = []\r\n for u in tabel:\r\n i = []\r\n for w in u:\r\n i.append(w)\r\n o.append(i)\r\n return o\r\n","sub_path":"Tarkvaraarendus (VG-1)/5.3b Juhuslik Bingo tabel.py","file_name":"5.3b Juhuslik Bingo tabel.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"234806681","text":"from collections import defaultdict\nimport math\n\ndef euclidean_distance(list1, list2):\n distance_list = [ e1 - e2 for e1 in list1 for e2 in list2 ]\n return math.sqrt(sum(distance_list) ** 2)\n\n# THIS ONLY WORKS FOR THE DEMO:\ndef format_name(name):\n no_file_path = name.split('/')[-1]\n name_only = no_file_path.split('_')[0:2]\n return ' '.join(name_only)\n\n# Compares the weights for facial recognition\ndef compare_coefficients(train_gallery, test_gallery, results=False):\n # Counts occurences of each person\n total_occurences = defaultdict(int)\n\n # Counts times name is in top 1\n rank1 = defaultdict(int)\n\n # Counts times name is in top 3\n rank3 = defaultdict(int)\n\n # Loop through each image in the test set\n for test_image, test_image_coefficients in test_gallery.iteritems():\n image_distances = []\n # Loop through each image in the trained model\n for train_image, train_image_coefficients in train_gallery.iteritems():\n # Calculate distance\n distance = euclidean_distance(test_image_coefficients, train_image_coefficients)\n # Store in a list for sorting to get top 3\n image_distances += [ (distance, train_image) ]\n\n if results:\n # Trim name to have only the name without the cruft\n test_person = format_name(test_image)\n # Get the trimmed names of those in the top 3\n top3 = [ format_name(name) for distance, name in sorted(image_distances)[0:3] ]\n \n # If the first guess is correct, add to the first rank count\n if top3[0] == test_person:\n rank1[test_person] += 1\n\n # Check for the correct guess to be in the top 3\n if test_person in top3:\n rank3[test_person] += 1\n\n total_occurences[test_person] += 1\n\n return (rank1, rank3, total_occurences)\n","sub_path":"hw3/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"514745600","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.db import migrations\nimport datetime\n\n\ndef convert_commission_data(apps, schema_editor):\n Commission = apps.get_model(\"commissions\", \"Commission\")\n\n for c in Commission.objects.all():\n if c.paid:\n c.status = 'PAID'\n else :\n c.status = 'NEW'\n c.comments=\"Last updated on %s by conversion\" % datetime.datetime.now().strftime('%Y-%m-%d')\n c.save()\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('commissions', '0004_auto_20161018_1418'),\n ]\n\n operations = [\n migrations.RunPython(convert_commission_data),\n ]\n","sub_path":"furnidashboard/commissions/migrations/0005_convert_commissions.py","file_name":"0005_convert_commissions.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"514396277","text":"\"\"\"\n다익스트라 알고리즘 - heap사용\n\"\"\"\n\"\"\"\n1. 출발 노드를 설정한다.\n2. 최단 거리 테이블을 초기화한다.\n3. 우선순위 큐를 pop한다.\n4. 큐에서 뽑은 거리(dist)가 최단거리 테이블(distance[now])보다 크면 무시(continue)\n5. 해당 노드를 거쳐 다른 노드로 가는 비용을 계산하여 최단 거리 테이블을 갱신한다.\n6. heapq에 (거리,��드)를 push한다.\n\"\"\"\nimport heapq\nimport sys\n\ninput = sys.stdin.readline\nINF = int(1e9)\n\nn,m = map(int,input().split())\ndistance = [INF]*(n+1)\n\ngraph = [[] for i in range(n+1)]\nstart = int(input())\n\nfor _ in range(m):\n a,b,c = map(int,input().split())\n graph[a].append((b,c))\n\ndef dijkstra(start):\n q = []\n # Heapq 노드번호 start로 초기화\n heapq.heappush(q,(0,start)) \n # distance 0으로 초기화\n distance[start] = 0\n \n while q:\n # 거리가 짧은 순으로 거리,노드를 Heapq에서 뽑은 후,\n dist, now = heapq.heappop(q)\n # Heapq에서 뽑은 노드의 거리가 거리 테이블의 값보다 작으면 무시하고, heapq에서 다시 뽑는 시행으로 돌아감 \n if dist > distance[now]:\n continue\n \n for i in graph[now]:\n cost = dist+i[1]\n if distance[i[0]] > cost:\n distance[i[0]] = cost\n heapq.heappush(q,(cost,i[0]))\n\ndijkstra(start)\n\nfor i in range(1,n+1):\n if distance[i] == INF:\n print(\"INFINITY\")\n else:\n print(distance[i])\n\n\n","sub_path":"Python/Algorithms/ShortDistance/dijkstra_rev.py","file_name":"dijkstra_rev.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"316416346","text":"import numpy as np\nfrom sklearn import preprocessing\nimport os\nfrom sklearn import svm\nimport scipy.stats as st\nfrom sklearn.linear_model import LogisticRegression\n\n\n\nTRAIN_PATH_NAME = \"C:\\\\Users\\\\nca150130\\\\PycharmProjects\\\\data_generation\\\\data\\\\cmc\\\\train\\\\\"\nTEST_PATH_NAME = \"C:\\\\Users\\\\nca150130\\\\PycharmProjects\\\\data_generation\\\\data\\\\cmc\\\\test\\\\\"\nSYNTHETIC_PATH_NAME = \"C:\\\\Users\\\\nca150130\\\\Desktop\\\\privbayes-changed\\\\data\\\\cmc\\\\generated\\\\\"\n\n\nRUN_NUMBER = 10\nCOLUMN = -1\n\nsvm_score = []\nsynthetic_svm_score = []\nagreement_rate_svm_score = []\n\nparameter_dict = {\n 0 : dict({'eps':0.8, \"sigma\":6, \"sigma_cl_1\":52, \"sigma_cl_2\":52}),\n 1 : dict({'eps':1.2, \"sigma\":5, \"sigma_cl_1\":34, \"sigma_cl_2\":34}),\n 2 : dict({'eps':1.6, \"sigma\":4, \"sigma_cl_1\":26, \"sigma_cl_2\":26}),\n 3 : dict({'eps':2.4, \"sigma\":3, \"sigma_cl_1\":17, \"sigma_cl_2\":17}),\n 4 : dict({'eps':3.2, \"sigma\":2, \"sigma_cl_1\":13, \"sigma_cl_2\":13})\n}\n\n\nresult_file = SYNTHETIC_PATH_NAME + \"_aggrement_rate_\" + \".txt\"\n\n\ndef findAccuracyForSyntheticClassifiers(synthetic_data, trainData, testData):\n\n synthetic_label = synthetic_data[:, -1]\n synthetic_data = synthetic_data[:, 0:COLUMN - 1]\n\n test_data = testData[:, 0:COLUMN - 1]\n train_label = trainData[:, -1]\n\n\n train_data = trainData[:, 0:COLUMN - 1]\n if len(np.unique(synthetic_label)) == 2:\n scaler = preprocessing.StandardScaler()\n scaler.fit(synthetic_data)\n scaled_synthetic_data = scaler.transform(synthetic_data)\n scaled_s_test_data = scaler.transform(test_data)\n\n\n scaler = preprocessing.StandardScaler()\n scaler.fit(train_data)\n scaled_train_data = scaler.transform(train_data)\n scaled_test_data = scaler.transform(test_data)\n\n svc = svm.SVC(kernel='linear', C=1).fit(scaled_synthetic_data, synthetic_label)\n synthetic_nb_salary = svc.predict(scaled_s_test_data)\n\n svc = svm.SVC(kernel='linear', C=1).fit(scaled_train_data, train_label)\n train_nb_salary = svc.predict(scaled_test_data)\n\n agreement_rate_svm_score.append(sum(synthetic_nb_salary == train_nb_salary) / len(train_nb_salary))\n\n\nif os.path.exists(result_file):\n os.remove(result_file)\n\nresult_opener = open(result_file, 'a')\n\nfor step in parameter_dict:\n evalParameter = parameter_dict.get(step)\n EPSILON_FOR_AUTOENCODER = evalParameter.get('eps')\n SIGMA_FOR_AUTOENCODER = evalParameter.get('sigma')\n\n svm_score.clear()\n synthetic_svm_score.clear()\n agreement_rate_svm_score.clear()\n\n for j in range(RUN_NUMBER):\n synthetic_file_name = SYNTHETIC_PATH_NAME + format(EPSILON_FOR_AUTOENCODER, '.6f') + \"_\" + str(j + 1) + \".txt\"\n trainFile = TRAIN_PATH_NAME + str(j + 1) + \".txt\"\n testFile = TEST_PATH_NAME + str(j + 1) + \".txt\"\n if(os.path.exists(synthetic_file_name)):\n synthetic_data = np.genfromtxt(synthetic_file_name, delimiter=' ').astype(np.float32)\n test_data = np.genfromtxt(testFile, delimiter=',').astype(np.float32)\n train_data = np.genfromtxt(trainFile, delimiter=',').astype(np.float32)\n COLUMN = train_data.shape[1]\n findAccuracyForSyntheticClassifiers(synthetic_data, train_data, test_data)\n\n score = float(np.round(sum(agreement_rate_svm_score)/(len(agreement_rate_svm_score) + 0.0000001),2))*100\n if np.isnan(score):\n pass\n else:\n result_opener.write(\"epsilon_for_autoencoder: \" + str(EPSILON_FOR_AUTOENCODER) + \" sigma: \" + str(SIGMA_FOR_AUTOENCODER) + \"\\n\")\n result_opener.write(\"agreement_rate_mean: \" + str(score) + \"\\n\")\n result_opener.write(\"agreement_rate_std: \" + str(st.tstd(agreement_rate_svm_score)*100) + \"\\n\")\n","sub_path":"src/aggrement_rate/aggrement_rate.py","file_name":"aggrement_rate.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"321581440","text":"import sys\r\nimport os\r\nimport threading\r\nimport Pyro4\r\nfrom shark import *\r\nimport time\r\nfrom datetime import datetime\r\nimport subprocess\r\nimport multiprocessing as mp\r\nimport signal\r\nimport socket\r\nimport random\r\nimport signal\r\nfrom functools import reduce\r\n\r\n# Semaphores and state variables\r\nboardLock = threading.Semaphore(0)\r\nprocesses = []\r\nboard = ''\r\nrunning = True\r\n\r\nclass SharkManager(threading.Thread):\r\n def __init__(self, numSharks):\r\n threading.Thread.__init__(self)\r\n\r\n self.numSharks = numSharks\r\n # Contains each iteration of a shark\r\n self.sharks = []\r\n for i in range(self.numSharks):\r\n self.sharks.append(Shark(\"models/shark.txt\",\\\r\n \t\t\t\t\t\t random.randint(1, 28), -55))\r\n\r\n def run(self):\r\n sharksInfo = []\r\n offScreen = False\r\n lastTime = datetime.now()\r\n counter = 0\r\n\r\n # Sharks run until off screen (as long as game is continuing)\r\n while not offScreen and running:\r\n \t# Buffered fps\r\n currTime = datetime.now()\r\n delta = currTime - lastTime\r\n lastTime = currTime\r\n counter += delta.microseconds\r\n\r\n # Clear the board, and then write to it.\r\n if counter >= 1000000/20:\r\n counter = 0\r\n board.clearBoard()\r\n sharksInfo = []\r\n for s in self.sharks:\r\n sharksInfo.append({'row': s.row, 'col': s.col,\\\r\n \t\t\t\t 'vertMove': s.vertMove,\\\r\n \t\t\t\t 'horizMove': s.horizMove,\\\r\n \t\t\t\t 'shark': s.shark})\r\n status = board.writeBoardShark(sharksInfo)\r\n\r\n # Checks if all sharks are off screen\r\n offScreen = reduce((lambda x, y: x and y), status, True)\r\n\r\n for shark in self.sharks:\r\n shark.move(board)\r\n\r\n\r\n\r\n# Launches Pyro4 server, accessible by given IP address\r\ndef startBoard(IP):\r\n command = \"python -m Pyro4.naming -n %s > /dev/null\" % IP\r\n processes.append(subprocess.Popen(command,shell=True,preexec_fn=os.setsid))\r\n time.sleep(3)\r\n command = \"python board.py %s > /dev/null\" % IP\r\n processes.append(subprocess.Popen(command,shell=True,preexec_fn=os.setsid))\r\n time.sleep(3)\r\n boardLock.release()\r\n\r\n# Callback function for signal receiver.\r\ndef endserver(signum, stack):\r\n global running\r\n running = False\r\n\r\n# Main server driver. Launches a Pyro4 using IP of hosting computer,\r\n# Once the server is running, players are kept track of, and sharks\r\n# are spawned from within a while loop that continues until receiving\r\n# the Ctrl-C signal.\r\ndef main(argv):\r\n\t# Retrieve the host's currennt IP.\r\n signal.signal(signal.SIGINT, endserver)\r\n processesStart = []\r\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n s.connect((\"8.8.8.8\", 80))\r\n IP = s.getsockname()[0]\r\n s.close()\r\n # Start server to host board object.\r\n processesStart.append(threading.Thread(target = startBoard, args = [IP]))\r\n for p in processesStart:\r\n p.start()\r\n # Wait for the server to be running.\r\n boardLock.acquire()\r\n boardLock.release()\r\n\r\n # Reciece copy of board object\r\n NS = Pyro4.locateNS(host=IP, port=9090, broadcast=True)\r\n time.sleep(5)\r\n uri = NS.lookup(\"example.board\")\r\n global board\r\n board = Pyro4.Proxy(uri)\r\n\r\n print (\"Running server on \" + IP + \"...let the games begin!\")\r\n prevPlayers = board.numPlayers()\r\n\r\n # Loop which controls game. Spawns sharks (as many as the wave value),\r\n # Only starts sharks spawning once a player has entered the game.\r\n while running:\r\n currPlayers = board.numPlayers()\r\n if currPlayers > prevPlayers:\r\n print (\"Player joined the game!\")\r\n prevPlayers = currPlayers\r\n elif currPlayers < prevPlayers:\r\n print (\"Player has died!\")\r\n prevPlayers = currPlayers\r\n if board.gameStarted():\r\n wave = board.getWave()\r\n sharkManager = SharkManager(wave)\r\n sharkManager.start()\r\n sharkManager.join()\r\n board.updateWave()\r\n\r\n # Ends the server if Ctrl-C is input.\r\n board.endGame()\r\n for process in processes:\r\n os.killpg(os.getpgid(process.pid), signal.SIGTERM)\r\n\r\nif __name__ == \"__main__\":\r\n main(sys.argv)\r\n","sub_path":"src/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"296906245","text":"import pickle\n\nfrom datetime import datetime\nimport click\n\nfrom src.aws import put_object_to_s3\nfrom src.lsh import split_features, train_clusters\nfrom src.elastic import get_random_feature_vectors\n\n\n@click.command()\n@click.option(\n \"-n\", help=\"number of groups to split the feature vectors into\", default=256\n)\n@click.option(\n \"-m\", help=\"number of clusters to find within each feature group\", default=32\n)\n@click.option(\n \"--sample_size\", help=\"number of embeddings to train clusters on\", default=25000\n)\ndef main(n, m, sample_size):\n feature_vectors = get_random_feature_vectors(sample_size)\n\n model_list = [\n train_clusters(feature_group, m)\n for feature_group in split_features(feature_vectors, n)\n ]\n\n model_name = datetime.now().strftime(\"%Y-%m-%d\")\n\n put_object_to_s3(\n binary_object=pickle.dumps(model_list),\n key=f\"lsh_models/{model_name}.pkl\",\n bucket_name=\"model-core-data\",\n profile_name=\"data-dev\",\n )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pipeline/inferrer/feature_training/train_lsh.py","file_name":"train_lsh.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"476198518","text":"import sys\nimport socket\n\nargs = sys.argv\n\n\nargs = ['']\nargs[0] = \"retext.txt\"\n\nadress = \"dbl44.beuth-hochschule.de\"\nport = 44444\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ntry:\n s.connect((adress, port))\n print(\"Connect to server!\")\nexcept:\n print(\"Can't connect to server!\")\n s.close()\n SystemExit()\n#receive message via dslp1.2\ndata = s.recv(1024)\nprint(bytes.decode(data))\n\n\ns.close()\nSystemExit()","sub_path":"receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"201263046","text":"# Randomly fills a grid of size 10 x 10 with 0s and 1s,\n# in an estimated proportion of 1/2 for each,\n# and computes the longest leftmost path that starts\n# from the top left corner -- a path consisting of\n# horizontally or vertically adjacent 1s --,\n# visiting every point on the path once only.\n#\n# Written by Eric Martin for COMP9021\n\n\nimport sys\nfrom random import seed, randint\n\nfrom queue_adt import *\n\n\ndim = 10\ngrid = [[0] * dim for i in range(dim)]\n\ndef display_grid():\n for i in range(dim):\n print(' ', end = '')\n for j in range(dim):\n print(' ', grid[i][j], end = '')\n print()\n print()\ndef new(position,a):\n if a == 'N':\n return (position[0] - 1,position[1])\n if a == 'S':\n return (position[0] + 1,position[1])\n if a == 'E':\n return (position[0], position[1] + 1)\n if a == 'W':\n return (position[0], position[1] - 1)\ndef leftmost_longest_path_from_top_left_corner():\n directions = {'N': (-1, 0),'S': (1, 0), 'E': (0, 1), 'W': (0, -1)}\n next_directions = {'N': ('W', 'N', 'E'), 'S': ('E', 'S', 'W'), 'E': ('N', 'E', 'S'), 'W': ('S', 'W', 'N')}\n if grid[0][0] == 0:\n return []\n paths = Queue()\n path_direction = Queue()\n path_direction.enqueue('E')\n paths.enqueue([(0, 0)])\n result = []\n while not paths.is_empty():\n output = paths.dequeue()\n print(output)\n if len(output) > len(result):\n result = output\n # print(result)\n direction1 = path_direction.dequeue()\n current_position = output[-1]\n if len(output) > 1:\n print('len')\n previous_position = output[-2]\n # print(previous_position)\n if output[-1][0] - output[-2][0] == 1 and output[-1][1] - output[-2][1] == 0:\n d = 'E'\n elif output[-1][0] - output[-2][0] == -1 and output[-1][1] - output[-2][1] == 0:\n d = 'W'\n elif output[-1][0] - output[-2][0] == 0 and output[-1][1] - output[-2][1] == 1:\n d = 'N'\n elif output[-1][0] - output[-2][0] == 0 and output[-1][1] - output[-2][1] == -1:\n print('s')\n d = 'S'\n else:\n print('e')\n d = 'E'\n for e in next_directions[d]:\n # new_position = (current_position[0] + directions[e][0], current_position[1] + directions[e][1])\n new_position = new(current_position, e)\n if new_position[0] < 0 or new_position[0] >9 or new_position[1] < 0 or new_position[1] > 9:\n continue\n if new_position in output:\n continue\n if grid[new_position[0]][new_position[1]] == 0:\n continue\n path_enqueue = list(output)\n path_enqueue.append(new_position) \n paths.enqueue(path_enqueue) \n path_direction.enqueue(e)\n return result\n\n\nprovided_input = input('Enter one integer: ')\ntry:\n seed_arg = int(provided_input)\nexcept:\n print('Incorrect input, giving up.')\n sys.exit()\n\nseed(seed_arg)\n# We fill the grid with randomly generated 0s and 1s,\n# with for every cell, a probability of 1/2 to generate a 0.\nfor i in range(dim):\n for j in range(dim):\n grid[i][j] = randint(0, 1)\nprint('Here is the grid that has been generated:')\ndisplay_grid()\n\npath = leftmost_longest_path_from_top_left_corner()\nif not path:\n print('There is no path from the top left corner')\nelse:\n print('The leftmost longest path from the top left corner is {}'.format(path))\n","sub_path":"quiz8.py","file_name":"quiz8.py","file_ext":"py","file_size_in_byte":3550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"467054997","text":"#!/usr/bin/env python\nimport ecto\n#import ecto_opencv.cv_bp as opencv\nfrom ecto_opencv import highgui, calib, imgproc\n\ndebug = True\n\nplasm = ecto.Plasm()\nrows = 5\ncols = 3\nsquare_size = 0.03 # in millis\n\npattern_show = highgui.imshow(name=\"pattern\", waitKey=10, autoSize=True)\nrgb2gray = imgproc.cvtColor(flag=7)\nvideo = highgui.VideoCapture(video_device=0)\ncircle_detector = calib.PatternDetector(rows=rows, cols=cols, pattern_type=\"acircles\", square_size=square_size)\ncircle_drawer = calib.PatternDrawer(rows=rows, cols=cols)\nposer = calib.FiducialPoseFinder()\npose_drawer = calib.PoseDrawer()\ncamera_intrinsics = calib.CameraIntrinsics(camera_file=\"camera.yml\")\nsplitter = imgproc.ChannelSplitter()\n\nplasm.connect(video[\"image\"] >> (rgb2gray[\"input\"], splitter[\"input\"]),\n splitter[\"out_0\"] >> (circle_detector[\"input\"], circle_drawer[\"input\"])\n )\n \nplasm.connect(circle_detector['out'] >> circle_drawer['points'],\n circle_detector['found'] >> circle_drawer['found'],\n camera_intrinsics['K'] >> poser['K'],\n circle_detector['out'] >> poser['points'],\n circle_detector['ideal'] >> poser['ideal'],\n circle_detector['found'] >> poser['found'],\n poser['R'] >> pose_drawer['R'],\n poser['T'] >> pose_drawer['T'],\n circle_drawer['out'] >> pose_drawer['image'],\n camera_intrinsics['K'] >> pose_drawer['K'],\n pose_drawer['output'] >> pattern_show['input'],\n )\n\n\nif debug:\n ecto.view_plasm(plasm)\n\nsched = ecto.schedulers.Threadpool(plasm)\n\nsched.execute(nthreads=8)\n\n#while(pattern_show.outputs.out != 27):\n# plasm.execute()\n \n\n","sub_path":"samples/rgb_splitter.py","file_name":"rgb_splitter.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"158965406","text":"# -*- coding: utf-8 -*-\nimport os\nimport tornado\nimport tornado.ioloop\nfrom tornado.options import define, options\nfrom src.handler import HomeHandler, FileUploadHandler\n\ndefine(\"port\", default=8888, help=\"run on the given port\", type=int)\ndefine('settings', default='debug', help='tornado settings file', type=str)\ndefine('config', default=None, help='tornado config file', type=dict)\ndefine('mysql_config', default=None, help='mysql config file', type=dict)\n\nif options.settings:\n options.parse_config_file('settings/%s/settings.py' % (options.settings))\n\nclass Application(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r\"/fileupload\", FileUploadHandler),\n (r\"/\", HomeHandler) \n ]\n settings = dict(\n blog_title=u\"Tornado Blog\",\n template_path=os.path.join(os.path.dirname(__file__), \"templates\"),\n static_path=os.path.join(os.path.dirname(__file__), \"static\"),\n # ui_modules={\"Entry\": EntryModule},\n xsrf_cookies=False,\n debug=True,\n )\n super(Application, self).__init__(handlers, **settings)\n\n\n\n\nif __name__ == \"__main__\":\n tornado.options.parse_command_line()\n http_server = tornado.httpserver.HTTPServer(Application())\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.current().start()\n\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"506046650","text":"## 1481.\n## 给你一个整数数组 arr 和一个整数 k 。现需要从数组中恰好移除 k 个元素,请找出移除后数组中不同整数的最少数目\n\n##示例 输入:arr = [5,5,4], k = 1\n##输出:1\n##解释:移除 1 个 4 ,数组中只剩下 5 一种整数。\n\n##输入:arr = [4,3,1,1,3,3,2], k = 3\n##输出:2\n##解释:先移除 4、2 ,然后再移除两个 1 中的任意 1 个或者三个 3 中的任意 1 个,最后剩下 1 和 3 两种整数。\n\n## 自己的做法:\n\nclass Solution:\n def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n vote = {}\n for j in range(len(arr)):\n if arr[j] not in vote:\n vote[arr[j]] = 1\n elif arr[j] in vote:\n vote[arr[j]] += 1 ## 这里主要是将arr放入哈希表中\n ans = list(vote.values()) ## 将vote字典中的value值 数组化,\n ans.sort() ## 再将数组排序\n for i in range(k):\n if ans[0] > 1:\n ans[0] -= 1\n elif ans[0] == 1:\n ans.pop(0)\n return len(ans)\n \n## 别人的优秀做法 值得学习 使用collections库中的自带的Counter去实现\n## 计数器\n\nclass Solution:\n def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n import collections\n count_list = collections.Counter(arr)\n sort_val = sorted(count_list.values())\n for index,val in enumerate(sort_val):\n if(k>=val):\n k = k- val\n else:\n return len(sort_val) - index\n return 0\n","sub_path":"findLeastNumOfUniqueInts.py","file_name":"findLeastNumOfUniqueInts.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"86111193","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport argparse\nimport locale\n\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nfrom banking.institutes.swedbank.collector import login_swedbank\nfrom banking.institutes.swedbank.parser import get_account_saldo\n\nif __name__ == '__main__':\n locale.setlocale(locale.LC_ALL, 'sv_SE.UTF-8')\n parser = argparse.ArgumentParser(description='collect Swedbank account balances')\n parser.add_argument(\"-p\", \"--personnummer\", required=True)\n args = parser.parse_args()\n\n driver = login_swedbank(args.personnummer)\n wait = WebDriverWait(driver, 15)\n\n driver.get(\"https://online.swedbank.se/app/privat/konton-och-kort\")\n wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'swed-page-region')))\n for l, v in get_account_saldo(driver):\n swedish_v = locale.format(\"%12.2f\", v)\n print(f\"{l: <55} {swedish_v:>}\")\n\n driver.get(\"https://online.swedbank.se/app/privat/pension/mitt-innehav\")\n wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'swed-page-region')))\n for l, v in get_account_saldo(driver):\n swedish_v = locale.format(\"%12.2f\", v)\n print(f\"{l: <55} {swedish_v:>}\")\n","sub_path":"bin/get_balance_swedbank.py","file_name":"get_balance_swedbank.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"159644360","text":"from funcionario_model import FuncionarioModel\nmodel = FuncionarioModel()\n\ndef CadastrarFuncionario():\n nome = input('Digite seu nome: ')\n salario = input('Digite o valor do seu salario: ')\n funcao = input('Digite sua função:')\n\n funcionario={\n \"nome\":nome,\n \"salario\":salario,\n \"funcao\":função\n \n }\n if model.salvar(funcionario):\n print(\"Funcionario Cadastrado com sucesso!\")\n return 0\n else:\n print(\"Funcionario não Cadastrado\")\n\ndef ListarFuncionarios():\n funcionarios = model.get.all()\n for funcionario in funcionarios:\n print(funcionario)\n","sub_path":"funcionario_controller.py","file_name":"funcionario_controller.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"92781704","text":"# !/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: J. Massey\n@description: Adapted from\n@contact: jmom1n15@soton.ac.uk\n\"\"\"\n# we import necessary libraries and functions\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import Ridge\nfrom sklearn.linear_model import Lasso\nfrom sklearn.linear_model import ElasticNet\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_squared_error\nimport seaborn as sns\nfrom load_raw import LoadData\nimport _pickle as cPickle\n\n\nreal_data_dir = '/home/masseyjmo/Workspace/Lotus/projects/cylinder_dns/data'\nplt.style.use(['science', 'grid'])\n\n\ndef get_gt(angles=32):\n # Get mean quantities\n with open('fos.pickle', \"rb\") as f:\n fos = cPickle.load(f)\n\n chunk = angles * len(fos['t'])\n p_data = np.load('data.npy').astype(np.float32)\n gt = p_data[0:chunk, -1]\n gt = np.array([gt[i * len(fos['t']):(i + 1) * len(fos['t'])] for i in range(angles)])\n return np.mean(gt), np.var(gt)\n\n\ndef data_loader(D):\n return LoadData(real_data_dir, D)\n\n\ndef get_real_error(data):\n # Get the real data from coarse simulations\n gt_mean, gt_var = get_gt()\n du_2 = data.ground_truth()\n du_1 = data.du_1\n mean_ = {'o2': abs(np.mean(du_2)-gt_mean)/gt_mean,\n 'o1': abs(np.mean(du_1)-gt_mean)/gt_mean}\n rms_ = {'o2': abs(np.var(du_2)-gt_var)/gt_var,\n 'o1': abs(np.var(du_1)-gt_var)/gt_var}\n print(np.mean(du_2), gt_mean)\n return mean_, rms_\n\n\nclass LrModel:\n def __init__(self, poly_n: int):\n self.poly_n = poly_n\n data = np.load('data.npy')\n poly = PolynomialFeatures(poly_n)\n poly = poly.fit_transform(data[:, 0:-1])\n self.data = np.concatenate((poly, data[:, -1][..., np.newaxis]), axis=1)\n self.X_train, self.X_test, self.y_train, self.y_test =\\\n train_test_split(self.data[:, 0:-1], self.data[:, -1], test_size=0.2, shuffle=True)\n\n def straight_linear(self):\n lr = LinearRegression(n_jobs=8)\n lr.fit(self.X_train, self.y_train)\n\n # evaluating the model on training and testing sets\n pred_train_lr = lr.predict(self.X_train)\n print('Lr train', r2_score(self.y_train, pred_train_lr))\n pred_test_lr = lr.predict(self.X_test)\n print('Lr test', r2_score(self.y_test, pred_test_lr))\n return lr\n\n def ridge(self, alpha):\n # here we define a Ridge regression model with lambda(alpha)=0.01\n rr = Ridge(alpha=alpha)\n rr.fit(self.X_train, self.y_train)\n pred_train_rr = rr.predict(self.X_train)\n print('Ridge train', r2_score(self.y_train, pred_train_rr))\n pred_test_rr = rr.predict(self.X_test)\n print('Ridge test', r2_score(self.y_test, pred_test_rr))\n return rr\n\n def lasso(self, alpha):\n # Define lasso\n model_lasso = Lasso(alpha=alpha)\n model_lasso.fit(self.X_train, self.y_train)\n pred_train_lasso = model_lasso.predict(self.X_train)\n print('Lasso train', r2_score(self.y_train, pred_train_lasso))\n\n pred_test_lasso = model_lasso.predict(self.X_test)\n print('Lasso test', r2_score(self.y_test, pred_test_lasso))\n\n return model_lasso\n\n def elastic(self, alpha):\n model_enet = ElasticNet(alpha=alpha)\n model_enet.fit(self.X_train, self.y_train)\n pred_train_enet = model_enet.predict(self.X_train)\n print('Elastic train', r2_score(self.y_train, pred_train_enet))\n\n pred_test_enet = model_enet.predict(self.X_test)\n print('Elastic test', r2_score(self.y_test, pred_test_enet))\n\n return model_enet\n\n\ndef plot_raw():\n fig_m, ax_m = plt.subplots(figsize=(7, 4))\n fig_s, ax_s = plt.subplots(figsize=(7, 4))\n ax_m.tick_params(bottom=\"on\", top=\"on\", right=\"on\", which='both', direction='in', length=2)\n ax_s.tick_params(bottom=\"on\", top=\"on\", right=\"on\", which='both', direction='in', length=2)\n ax_m.set_xlabel(r\"Grid refinement ratio\")\n ax_s.set_xlabel(r\"Grid refinement ratio\")\n\n ax_m.set_ylabel(r'$ \\log $ error')\n ax_s.set_ylabel(r'$ \\log $ error')\n\n ax_m.set_title(r'Mean error of $\\overline{C_{F}}$')\n ax_s.set_title(r'Variance error of $\\overline{C_{F}}$')\n\n ax_m.set_yscale('log')\n ax_s.set_yscale('log')\n ax_m.set_ylim(1e-2, 1e5)\n ax_s.set_ylim(1e-2, 1e9)\n\n Ds = [16, 24, 32, 48, 64, 96]\n\n # ax_m.loglog()\n # ax_s.loglog()\n\n gt_mean, gt_var = get_gt()\n\n poly_n = [7, 2, 1]\n lrs = [LrModel(n).straight_linear() for n in poly_n]\n # ---------------- Plot simulation error -----------------------#\n for d in Ds:\n data = data_loader(d)\n mean_err, var_err = get_real_error(data)\n if d != 96:\n ax_m.scatter(96 / d, mean_err['o2'], color='k', marker='h', label=r'$O(2)$ F-D' if d == Ds[-2] else \"\")\n ax_s.scatter(96 / d, var_err['o2'], color='k', marker='h', label=r'$O(2)$ F-D' if d == Ds[-2] else \"\")\n ax_m.scatter(96 / d, mean_err['o1'], color='k', marker='d', label=r'$O(1)$ F-D' if d == Ds[-1] else \"\")\n ax_s.scatter(96 / d, var_err['o1'], color='k', marker='d', label=r'$O(1)$ F-D' if d == Ds[-1] else \"\")\n\n # ---------------- Plot nn model error -----------------------#\n mkrs = ['*', 'X', 'P', 'p']\n colours = sns.color_palette(\"BuGn_r\", 6)\n for c_id, n in enumerate(poly_n):\n data_test = data.clean_data()\n poly = PolynomialFeatures(n)\n poly = poly.fit_transform(data_test[:, 0:-1])\n data_test = np.concatenate((poly, data_test[:, -1][..., np.newaxis]), axis=1)\n cd_hat = lrs[c_id].predict(data_test[:, 0:-1])\n mean_err, var_err = abs(np.mean(cd_hat) - gt_mean) / gt_mean, abs(np.var(cd_hat) - gt_var) / gt_var\n ax_m.scatter(96 / d, mean_err, color=colours[int(1 + c_id)],\n marker=mkrs[c_id], label=r'poly $O(' + str(n) + ')$' if d == Ds[-1] else \"\")\n ax_s.scatter(96 / d, var_err, color=colours[int(1 + c_id)],\n marker=mkrs[c_id], label=r'poly $O(' + str(n) + ')$' if d == Ds[-1] else \"\")\n\n ax_m.legend(bbox_to_anchor=(1.22, 0.6))\n ax_s.legend(bbox_to_anchor=(1.22, 0.6))\n\n fig_m.savefig('../accuracy_figures/3_poly_mean_err.pdf')\n fig_s.savefig('../accuracy_figures/3_poly_var_err.pdf')\n plt.close()\n\n\ndef plot_ridge():\n fig_m, ax_m = plt.subplots(figsize=(7, 4))\n fig_s, ax_s = plt.subplots(figsize=(7, 4))\n ax_m.tick_params(bottom=\"on\", top=\"on\", right=\"on\", which='both', direction='in', length=2)\n ax_s.tick_params(bottom=\"on\", top=\"on\", right=\"on\", which='both', direction='in', length=2)\n ax_m.set_xlabel(r\"Grid refinement ratio\")\n ax_s.set_xlabel(r\"Grid refinement ratio\")\n\n ax_m.set_ylabel(r'$ \\log $ error')\n ax_s.set_ylabel(r'$ \\log $ error')\n\n ax_m.set_title(r'Mean error of $\\overline{C_{F}}$')\n ax_s.set_title(r'Variance error of $\\overline{C_{F}}$')\n\n ax_m.set_yscale('log')\n ax_s.set_yscale('log')\n ax_m.set_ylim(1e-3, 1e2)\n ax_s.set_ylim(1e-2, 1e4)\n\n Ds = [16, 24, 32, 48, 64, 96]\n\n gt_mean, gt_var = get_gt()\n\n n = 7\n alphas = [1e-4, 1e-5, 1e-6]\n ridges = [LrModel(n).ridge(a) for a in alphas]\n # lassos = [LrModel(n).lasso(a) for a in alphas]\n # elastics = [LrModel(n).elastic(a) for a in alphas]\n # ---------------- Plot O(1) poly -----------------------#\n for d in Ds:\n data = data_loader(d)\n clean = LrModel(1).straight_linear()\n data_t = data.clean_data()\n poly = PolynomialFeatures(1)\n poly = poly.fit_transform(data_t[:, 0:-1])\n data_t = np.concatenate((poly, data_t[:, -1][..., np.newaxis]), axis=1)\n lr = clean.predict(data_t[:, 0:-1])\n\n mean_err, var_err = abs(np.mean(lr) - gt_mean) / gt_mean, abs(np.var(lr) - gt_var) / gt_var\n colours = sns.color_palette(\"BuGn_r\", 7)\n ax_m.scatter(96 / d, mean_err, color=colours[3],\n marker='h', label=r'poly $O(1)$' if d == Ds[-1] else \"\")\n ax_s.scatter(96 / d, var_err, color=colours[3],\n marker='h', label=r'poly $O(1)$' if d == Ds[-1] else \"\")\n\n # ---------------- Plot nn model error -----------------------#\n mkrs = ['*', 'X', 'P', 'p']\n colours = sns.light_palette(\"purple\", 5)\n for c_id, a in enumerate(alphas):\n data_test = data.clean_data()\n poly = PolynomialFeatures(n)\n poly = poly.fit_transform(data_test[:, 0:-1])\n data_test = np.concatenate((poly, data_test[:, -1][..., np.newaxis]), axis=1)\n rr = ridges[c_id].predict(data_test[:, 0:-1])\n mean_err, var_err = abs(np.mean(rr) - gt_mean) / gt_mean, abs(np.var(rr) - gt_var) / gt_var\n ax_m.scatter(96 / d, mean_err, color=colours[int(1 + c_id)],\n marker=mkrs[c_id], label=r'Ridge $\\alpha = ' + str(a) + '$' if d == Ds[-1] else \"\")\n ax_s.scatter(96 / d, var_err, color=colours[int(1 + c_id)],\n marker=mkrs[c_id], label=r'Ridge $\\alpha = ' + str(a) + '$' if d == Ds[-1] else \"\")\n\n ax_m.legend(bbox_to_anchor=(1.01, 0.6))\n ax_s.legend(bbox_to_anchor=(1.01, 0.6))\n\n fig_m.savefig('../accuracy_figures/3_ridge_mean_err.pdf')\n fig_s.savefig('../accuracy_figures/3_ridge_var_err.pdf')\n plt.close()\n\n\nif __name__ == \"__main__\":\n # plot_raw()\n plot_ridge()\n\n","sub_path":"circular_cylinder/Train/poly_feat_model/poly_model_sci.py","file_name":"poly_model_sci.py","file_ext":"py","file_size_in_byte":9532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"201002147","text":"from django.shortcuts import render\nfrom django.views import generic\nfrom django.shortcuts import get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.urls import reverse_lazy\nfrom django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\n\n# Create your views here.\nfrom lendingapp.models import Applicant, Application\nfrom lendingapp.forms import ApplicationForm, CustomGraphForm\nfrom lendingapp.neuralnetwork import process\n\nfrom . import query\n\n@login_required\ndef index(request):\n \"\"\"View function for home page of site.\"\"\"\n # Generate counts of some of the main objects\n num_applicants = Applicant.objects.all().count()\n num_applications = Application.objects.all().count()\n \n context = {\n 'num_applicants': num_applicants,\n 'num_applications': num_applications,\n }\n # Render the HTML template index.html with the data in the context variable\n return render(request, 'index.html', context=context)\n\t\nclass ApplicantListView(LoginRequiredMixin, generic.ListView):\n model = Applicant\n paginate_by = 10\n\t\nclass ApplicantDetailView(LoginRequiredMixin, generic.DetailView):\n model = Applicant\n\nclass ApplicantCreate(CreateView):\n model = Applicant\n template_name_suffix = '_create_form'\n fields = '__all__'\n\t\n@login_required\ndef create_application(request):\n # If this is a POST request then process the Form data\n if request.method == 'POST':\n # Create a form instance and populate it with data from the request (binding):\n form = ApplicationForm(request.POST)\n\t\t\n # Check if the form is valid:\n if form.is_valid():\n form.save()\n # redirect to a new URL:\n return HttpResponseRedirect(reverse('applications') )\n\n # If this is a GET (or any other method) create the default form.\n else:\n form = ApplicationForm()\n\n context = {\n 'form': form,\n }\n return render(request, 'lendingapp/application_create_form.html', context)\n\t\n@login_required\ndef update_application(request, pk):\n application = get_object_or_404(Application, pk=pk)\n\n # If this is a POST request then process the Form data\n if request.method == 'POST':\n # Create a form instance and populate it with data from the request (binding):\n form = ApplicationForm(request.POST)\n\t\t\n # Check if the form is valid:\n if form.is_valid():\n application.applicant = form.cleaned_data['applicant']\n application.loan_amnt = form.cleaned_data['loan_amnt']\n application.funded_amnt = form.cleaned_data['funded_amnt']\n application.int_rate = form.cleaned_data['int_rate']\n application.term = form.cleaned_data['term']\n application.installment = form.cleaned_data['installment']\n application.annual_inc = form.cleaned_data['annual_inc']\n #application.verification_status = form.cleaned_data['verification_status']\n #application.emp_length = form.cleaned_data['emp_length']\n application.home_ownership = form.cleaned_data['home_ownership']\n application.grade = form.cleaned_data['grade']\n application.last_credit_pull_d = form.cleaned_data['last_credit_pull_d']\n #application.inq_last_6mths = form.cleaned_data['inq_last_6mths']\n #application.open_acc = form.cleaned_data['open_acc']\n #application.total_acc = form.cleaned_data['total_acc']\n application.revol_bal = form.cleaned_data['revol_bal']\n #application.revol_util = form.cleaned_data['revol_util']\n application.dti = form.cleaned_data['dti']\n application.acc_now_delinq = form.cleaned_data['acc_now_delinq']\n application.delinq_amnt = form.cleaned_data['delinq_amnt']\n application.delinq_2yrs = form.cleaned_data['delinq_2yrs']\n application.pub_rec = form.cleaned_data['pub_rec']\n #application.tax_liens = form.cleaned_data['tax_liens']\n application.collections_12_mths_ex_med = form.cleaned_data['collections_12_mths_ex_med']\n application.chargeoff_within_12_mths = form.cleaned_data['chargeoff_within_12_mths']\n application.pub_rec_bankruptcies = form.cleaned_data['pub_rec_bankruptcies']\n application.save()\n # redirect to a new URL:\n return HttpResponseRedirect(reverse('applications') )\n\n # If this is a GET (or any other method) create the default form.\n else:\n form = ApplicationForm(initial={'loan_amnt': application.loan_amnt, 'applicant': application.applicant, 'funded_amnt': application.funded_amnt, 'term': application.term, 'int_rate': application.int_rate, 'installment': application.installment, 'annual_inc': application.annual_inc, 'home_ownership': application.home_ownership, 'grade': application.grade, 'last_credit_pull_d': application.last_credit_pull_d, 'revol_bal': application.revol_bal, 'dti': application.dti, 'acc_now_delinq': application.acc_now_delinq, 'delinq_amnt': application.delinq_amnt, 'delinq_2yrs':application.delinq_2yrs, 'collections_12_mths_ex_med': application.collections_12_mths_ex_med, 'chargeoff_within_12_mths': application.chargeoff_within_12_mths, 'pub_rec': application.pub_rec, 'pub_rec_bankruptcies': application.pub_rec_bankruptcies})\n\n context = {\n 'form': form,\n 'application': application,\n }\n return render(request, 'lendingapp/application_update_form.html', context)\n\t\n@login_required\ndef process_application(request, pk):\n application = get_object_or_404(Application, pk=pk)\n approved = process(application)\n application.approved = approved\n application.save()\n context = {\n 'application': application,\n }\n return render(request, 'lendingapp/application_process.html', context)\n \n \nclass ApplicantUpdate(LoginRequiredMixin, UpdateView):\n model = Applicant\n template_name_suffix = '_update_form'\n fields = ['first_name', 'last_name']\n\nclass ApplicantDelete(LoginRequiredMixin, DeleteView):\n model = Applicant\n success_url = reverse_lazy('applicants')\n\t\nclass ApplicationCreate(CreateView):\n model = Application\n template_name_suffix = '_create_form'\n form_class = ApplicationForm\n\t\n\t\nclass ApplicationUpdate(LoginRequiredMixin, UpdateView):\n model = Application\n template_name_suffix = '_update_form'\n fields = ['__all__']\n\nclass ApplicationDelete(LoginRequiredMixin, DeleteView):\n model = Application\n success_url = reverse_lazy('applications')\n\t\n@login_required\ndef applicant_detail_view(request, primary_key):\n applicant = get_object_or_404(Applicant, pk=primary_key)\n return render(request, 'lendingapp/applicant_detail.html', context={'applicant': applicant})\n\nclass ApplicationListView(LoginRequiredMixin, generic.ListView):\n model = Application\n paginate_by = 10\n\t\nclass ApplicationDetailView(LoginRequiredMixin, generic.DetailView):\n model = Application\n\n@login_required\ndef application_detail_view(request, primary_key):\n application = get_object_or_404(Application, pk=primary_key)\n return render(request, 'lendingapp/application_detail.html', context={'application': application})\n\n@login_required\ndef create_graph(request):\n #available_columns = query.get_available_columns()\n # If this is a POST request then process the Form data\n if request.method == 'POST':\n\n # Create a form instance and populate it with data from the request (binding):\n form = CustomGraphForm(request.POST)\n\n # Check if the form is valid:\n if form.is_valid():\n graph_type = title = form.cleaned_data['graph_type']\n title = form.cleaned_data['title']\n xcolumn = form.cleaned_data['xcolumn']\n ycolumn = form.cleaned_data['ycolumn']\n xlabel = form.cleaned_data['xlabel']\n ylabel = form.cleaned_data['ylabel']\n limit = form.cleaned_data['limit']\n # process the data in form.cleaned_data as required\n if graph_type == \"SCATTER\":\n html_graph = query.get_scatter_plot(xcolumn, ycolumn, xlabel, ylabel, title, limit)\n elif graph_type == \"HISTOGRAM\":\n html_graph = query.get_histogram(xcolumn, xlabel, ylabel, title, limit)\n else:\n html_graph = query.get_bar_chart(xcolumn, xlabel, ylabel, title, limit)\n context = {\n 'html_graph': html_graph,\n }\n return render(request, 'lendingapp/graph_result.html', context)\n\n # If this is a GET (or any other method) create the default form.\n else:\n form = CustomGraphForm()\n \n context = {\n 'form': form,\n }\n return render(request, 'lendingapp/graph_create_form.html', context=context)","sub_path":"lendingapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"157436040","text":"import os, subprocess\nimport map_equ_20190429\nimport descur\nimport numpy as np\n\ndescu = descur.descur_fit\neqm = map_equ_20190429.equ_map()\n\n\ndef nemec(A):\n\n vmec_d, tshot, jt = A\n mdescur = int(vmec_d['mdescur'])\n nshot = int(vmec_d['nshot'])\n ed = int(vmec_d['ed'])\n nrho = int(vmec_d['nrho_nem'])\n nthe = int(vmec_d['nthe_nem'])\n expnam = vmec_d['exp']\n dianam = vmec_d['dia']\n\n#=====================\n# Read AUG equilibrium\n#=====================\n\n if not eqm.Open(nshot, diag=dianam, exp=expnam):\n return\n\n j_t = np.argmin(np.abs(eqm.t_eq - tshot))\n print('%s:%s(%d) time:%7.3f' %(expnam, dianam, ed, eqm.t_eq[j_t]))\n nrho = eqm.lpfp[j_t] + 1\n tf = eqm.get_profile('TFLx')[j_t, :nrho]\n q = - eqm.get_profile('Qpsi')[j_t, :nrho]\n pres, _ = eqm.get_mixed('Pres')\n pres = pres[j_t, :nrho]\n\n ns = len(tf)\n tfln = tf/tf[-1]\n\n# Fourier moments of last closed surface\n rhop = 0.999\n r_surf, z_surf = eqm.rho2rz(rhop, t_in=tshot, coord_in='rho_pol', all_lines=False)\n moments = descu((r_surf[0][0], z_surf[0][0], mdescur))\n\n#============================\n# Write ASCII input for NEMEC\n#============================\n\n homdir = os.getenv('HOME')\n dir_in = '%s/AUG_equilibrium/nemec/input' %homdir\n dir_out = '%s/AUG_equilibrium/nemec/output' %homdir\n os.system('mkdir -p %s' %dir_in)\n os.system('mkdir -p %s' %dir_out)\n\n# Iota\n\n fiota = '%s/vmec_iota%d' %(dir_in, jt)\n head_iota = ' iota profile\\n'\n head_iota += ' diota1 diota2 iotaspli\\n'\n head_iota += ' 0.0 0.0 0\\n'\n head_iota += ' niotau\\n %4d' %ns\n np.savetxt(fiota, np.c_[tfln, 1./q], header=head_iota, comments='', fmt='%18.8e %18.8e')\n print('Written file %s' %fiota)\n\n# === Plasma pressure\n\n fpres = '%s/vmec_pres%d' %(dir_in, jt)\n head_pres = ' pressure profile: %4s %4s #%5d v%2d t=%7.3f\\n' %(expnam, dianam, nshot, eqm.ed, tshot)\n head_pres += ' dpres1 dpres2 presspli\\n'\n head_pres += ' 0.0 0.0 0\\n'\n head_pres += ' npresu\\n %4d' %ns\n np.savetxt(fpres, np.c_[tfln, pres - pres[-1]], header=head_iota, comments='', fmt='%18.8e %18.8e')\n print('Written file %s' %fpres)\n\n# Fourier moments of last closed surface\n\n mom_order = mdescur - 1\n momtype = 4\n\n fdesc = '%s/in_vmec_descur%d' %(dir_in, jt)\n\n head_desc = ' mbound nbound\\n'\n head_desc += ' %6d %6d\\n' %(mom_order, 0)\n head_desc += ' m n rbc rbs zbc zbs \\n'\n\n file = open(fdesc, 'w')\n file.write(head_desc)\n for jmom in range(mdescur):\n file.write('%4d%6d' %(jmom, 0))\n for jtyp in range(momtype):\n file.write(' %14.4E' %moments[jmom, jtyp] )\n file.write('\\n')\n file.close()\n print('Written Fourier moments at LCFS in file %s' %fdesc)\n\n# NEMEC input namelist\n\n fnml_in = '%s/input.%d' %(dir_in, jt)\n file = open(fnml_in, 'w')\n file.write( \"&INDATA\\n\" + \\\n \"mgrid_file = 'none'\\n\" + \\\n \"user_pressure = '%s'\\n\" %fpres +\\\n \"user_itor = 'none'\\n\" + \\\n \"user_iota = '%s'\\n\" %fiota + \\\n \"user_fouraxis = 'none'\\n\" + \\\n \"user_fourlcms = '%s'\\n\" %fdesc + \\\n \"lfreeb = .false.\\n\" + \\\n \"vac_1_2 = 1\\n\" + \\\n \"pres_profile = 'user'\\n\" + \\\n \"itor_profile = 'none'\\n\" + \\\n \"iota_profile = 'user'\\n\" + \\\n# \"woutt = 'new'\\n\" + \\\n \"woutt = 'red'\\n\" + \\\n \"woutf = 'ascii'\\n\" + \\\n \"lcont = .false.\\n\" + \\\n \"out_path = '%s/'\\n\" %dir_out + \\\n \"lwr_res = .false.\\n\" + \\\n \"res_file = 'none'\\n\" + \\\n \"ns_array = 23, 47, 77, %d,\\n\" %nrho + \\\n \"ftol_array = 1.e-8, 1.e-10, 1.e-12, 1.e-14,\\n\" + \\\n \"delt = 0.5\\n\" + \\\n \"niter = 10000\\n\" + \\\n \"nstep = 50\\n\" + \\\n \"nvacskip = 1\\n\" + \\\n \"mpol = %3d\\n\" %mdescur + \\\n \"ntor = 0\\n\" + \\\n \"ntheta = %d\\n\" %nthe + \\\n \"nzeta = 1\\n\" + \\\n \"iasym = 1\\n\" + \\\n \"nfp = 1\\n\" + \\\n \"ncurr = 0\\n\" + \\\n \"curtor = 0.\\n\" + \\\n \"phiedge = %12.7f \\n\" %tf[-1] + \\\n \"gamma = 0.\\n\" + \\\n \"betascale = 1.0\\n\" + \\\n \"raxis_co(0) = 1.731,\\n\" + \\\n \"zaxis_co(0) = 0.108,\\n\" + \\\n \"/\\n&END\\n\" ) \n\n file.close()\n print('Written NEMEC input namelist in file %s' %fnml_in)\n\n#==============\n# Running NEMEC\n#==============\n\n nem_dir = '/afs/ipp/home/t/transp/AUG_equilibrium/nemec/bin'\n\n print(' ===== running NEMEC')\n# cmd = '%s/NEMEC_LINUX_OMP %s > %s/nemec%d.log' %(nem_dir, fnml_in, dir_out, jt)\n cmd = '%s/NEMEC_TOKP_OMP_xAVX %s > %s/nemec%d.log' %(nem_dir, fnml_in, dir_out, jt)\n print(cmd)\n process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n process.wait()\n\n os.system('rm threed1.%d' %jt)\n\n# Reading output\n\n fnem_out = '%s/wout.%d' %(dir_out, jt)\n print('Reading NEMEC output file %s' %fnem_out)\n\n if os.path.getctime(fnem_out) < os.path.getctime(fnml_in):\n print('No output file generated, qutting')\n sys.exit()\n\n f = open(fnem_out, 'r')\n line = f.readline().split()\n f.close()\n\n nrho = int(line[0])\n nmod = int(line[1])\n phiedge = float(line[2])\n# Calculation: equispaced in tor. flux\n rho_tor = np.sqrt(np.linspace(0, 1, nrho))\n\n rc, zs, rs, zc = np.loadtxt(fnem_out, skiprows=1, unpack=True)\n\n rc = np.reshape(rc, (nrho, nmod))\n rs = np.reshape(rs, (nrho, nmod))\n zc = np.reshape(zc, (nrho, nmod))\n zs = np.reshape(zs, (nrho, nmod))\n return (rc, rs, zc, zs, rho_tor)\n\nif __name__ == \"__main__\":\n\n vmec_dic = {'mdescur':7, 'time':6., 'exp':'AUGD', 'dia':'EQH', 'ed':0, \\\n 'nshot':26233, 'nrho_nem': 101, 'nthe_nem': 60}\n NEMEC(vmec_dic)\n","sub_path":"nemec.py","file_name":"nemec.py","file_ext":"py","file_size_in_byte":6349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"352796672","text":"def int2hex(value):\n hex = {\n 10: 'A',\n 11: 'B',\n 12: 'C',\n 13: 'D',\n 14: 'E',\n 15: 'F'\n }\n\n if value in hex:\n value = hex[value]\n\n return str(value)\n\n\nprint(int2hex(9))\nprint(int2hex(15))\n","sub_path":"Lesson-3/ex-03.py","file_name":"ex-03.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"596219039","text":"# ------------------\n# User Instructions\n#\n# Hopper, Kay, Liskov, Perlis, and Ritchie live on\n# different floors of a five-floor apartment building.\n#\n# Hopper does not live on the top floor.\n# Kay does not live on the bottom floor.\n# Liskov does not live on either the top or the bottom floor.\n# Perlis lives on a higher floor than does Kay.\n# Ritchie does not live on a floor adjacent to Liskov's.\n# Liskov does not live on a floor adjacent to Kay's.\n#\n# Where does everyone live?\n#\n# Write a function floor_puzzle() that returns a list of\n# five floor numbers denoting the floor of Hopper, Kay,\n# Liskov, Perlis, and Ritchie.\n\nimport itertools\n\n\ndef floor_puzzle():\n floor_assignments = first, second, third, fourth, last = [1, 2, 3, 4, 5]\n orderings = list(itertools.permutations(floor_assignments))\n for (Hopper, Kay, Liskov, Perlis, Ritchie) in orderings:\n if Hopper != last and Kay != first and Liskov != first and Liskov != last and Perlis > Kay and abs(Ritchie - Liskov) != 1 and abs(Liskov - Kay) != 1:\n return [Hopper, Kay, Liskov, Perlis, Ritchie]\n\n\nif __name__ == \"__main__\":\n result = floor_puzzle()\n print(result)\n","sub_path":"Udacity_CS212/floor_puzzle/floor_puzzle.py","file_name":"floor_puzzle.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"101989823","text":"\"\"\" This will read a csv file of any column and row length\"\"\"\n__author__ = 'karic_000'\nimport random\nimport csv\n\n\ndef initialization():\n\n csv_file = open('simple-soccer-database.csv', 'rt')\n\n try:\n reader = csv.reader(csv_file)\n next(reader) # Skip headers.\n stats = [[int(item) for number, item in enumerate(row) if item and (1 <= number <= 100)]\n for row in reader] # Converts string into int\n \"\"\"The maximum number of rows for this program is 100\"\"\"\n print(\"\\nDATA RETRIEVED:\\n\", stats)\n\n row_amount = len(stats)\n print(\"\\nROW AMOUNT:\", row_amount)\n dimensions = 0 # The amount of elements in the data.\n for row in stats:\n for col in row:\n dimensions += 1\n col_amount = dimensions // row_amount\n print(\"COLUMN AMOUNT:\", col_amount, '\\nThe number of total elements:', dimensions)\n\n # Create 5 clusters and assign to each the same amount of elements from the data\n cluster_1, cluster_2, cluster_3, cluster_4, cluster_5 = [], [], [], [], []\n clusters = [cluster_1, cluster_2, cluster_3, cluster_4, cluster_5]\n\n cluster_list_size = row_amount//len(clusters) # Defines how many rows can clusters hold\n print(\"Each cluster should have ->\", cluster_list_size, \"<- rows put into them.\")\n\n assignment_step(stats, row_amount, col_amount, cluster_1, cluster_2, cluster_3, cluster_4,\n cluster_5, cluster_list_size, clusters)\n\n finally:\n csv_file.close()\n\n\ndef assignment_step(stats, row_amount, col_amount, cluster_1, cluster_2, cluster_3, cluster_4,\n cluster_5, cluster_list_size, clusters):\n\n done = False\n index = 0\n while not done:\n if index <= row_amount: # 0 - 20 in this example\n observation = stats[index]\n x = random.randint(0, 4) # Random cluster takes the next observation\n if index < row_amount: # When index hits one before the last row\n # it increments again, adds it to cluster, then it halts\n if x == 0: # x identifies which of the 5 clusters was chosen\n if len(cluster_1) < cluster_list_size: # Checks if cluster is full\n cluster_1.append(observation)\n # Only increments if that row is used\n index += 1\n else:\n # Cluster is full, pick a new random cluster\n x = random.randint(1, 4)\n if x == 1:\n if len(cluster_2) < cluster_list_size:\n cluster_2.append(observation)\n index += 1\n else:\n x = random.randint(0, 4)\n if x == 2:\n if len(cluster_3) < cluster_list_size:\n cluster_3.append(observation)\n index += 1\n else:\n x = random.randint(0, 4)\n if x == 3:\n if len(cluster_4) < cluster_list_size:\n cluster_4.append(observation)\n index += 1\n else:\n x = random.randint(0, 4)\n if x == 4:\n if len(cluster_5) < cluster_list_size:\n cluster_5.append(observation)\n index += 1\n\n if index == row_amount:\n done = True\n print(\"\\nCluster 1:\", cluster_1, \"\\nCluster 2:\", cluster_2, \"\\nCluster 3:\", cluster_3,\n \"\\nCluster 4:\", cluster_4, \"\\nCluster 5:\", cluster_5)\n\n cluster_1trans = [list(a) for a in zip(*cluster_1)]\n cluster_2trans = [list(a) for a in zip(*cluster_2)]\n cluster_3trans = [list(a) for a in zip(*cluster_3)]\n cluster_4trans = [list(a) for a in zip(*cluster_4)]\n cluster_5trans = [list(a) for a in zip(*cluster_5)]\n new_clusters = cluster_1trans, cluster_2trans, cluster_3trans, cluster_4trans, \\\n cluster_5trans\n\n centroid_1trans, centroid_2trans, centroid_3trans, centroid_4trans, centroid_5trans = [], \\\n [], \\\n [], \\\n [], \\\n []\n print(\"\\nNEW REPRESENTATION OF CLUSTERS BY COLUMNS GROUPING:\\nCluster 1:\", cluster_1trans,\n \"\\nCluster 2:\", cluster_2trans, \"\\nCluster 3:\", cluster_3trans,\n \"\\nCluster 4:\", cluster_4trans, \"\\nCluster 5:\", cluster_5trans)\n centroids = centroid_1trans, centroid_2trans, centroid_3trans, centroid_4trans, \\\n centroid_5trans\n\n cluster_dimension = cluster_list_size * col_amount # 44 elements\n clust_index = 0 # Keeps rr\n sums = 0\n ind_i = 0 # every Nth element in a cluster's columns\n next_r = 0 # to keep the row number; 4 max\n limit = 0 # Keep track of \"dimensions\"\n for each in centroids:\n which_clust = clusters[clust_index]\n which_centroid = centroids[clust_index]\n for r in which_clust:\n for c in r:\n while next_r < cluster_list_size: # Cluster size is column amount 11\n sums += which_clust[next_r][ind_i]\n next_r += 1\n limit += 1\n\n if next_r == cluster_list_size and limit != cluster_dimension:\n # limit's max will always be 1 less than cluster_dimensions\n centroid = sums/cluster_list_size\n which_centroid.append(centroid)\n sums = 0\n next_r = 0 # Loop back through every \"N\"th elements .\n ind_i += 1 # After very 4 checks, increase list index\n if next_r == cluster_list_size and limit == cluster_dimension:\n centroid = sums/cluster_list_size\n which_centroid.append(centroid)\n limit = 0\n ind_i, next_r = 0, 0\n clust_index += 1\n\n print(\"\\nCentroid 1:\", centroid_1trans, \"\\nCentroid 2:\", centroid_2trans, \"\\nCentroid 3:\",\n centroid_3trans, \"\\nCentroid 4:\", centroid_4trans, \"\\nCentroid 5:\", centroid_5trans)\n\n #done = False\n update_step(clusters, centroids, col_amount, cluster_list_size) # Old clusters,\n # lists' sizes (11) and centroid from transposed rows/columns\n\n\ndef update_step(clusters, centroids, col_amount, cluster_list_size):\n \"\"\"Get the distance in between a cluster's list elements and each centroid\"\"\"\n\n diff_array = []\n row_in_clust = 0 # Track the list in cluster's indices\n\n centroid_num = 0 # Will know which centroid element to compare distances with\n which_centroid = centroids[centroid_num]\n element_num = 0 # Will keep of the element in centroid\n sum_differences = 0\n\n print(\"\\nThe centroid that all cluster elements will check their distances \"\n \"with will be:\\n\", which_centroid)\n while row_in_clust <= cluster_list_size: # While still in the same cluster\n which_clusters = clusters[row_in_clust]\n\n for cluster_row in which_clusters: # Sees one list per cluster at a time\n #print(cluster_row, \"\\n\", which_centroid)\n\n for element in cluster_row: # Sees one element at a time\n difference = abs(element - which_centroid[element_num])\n sum_differences += difference\n # print(\"centroid element number\", element_num)\n if element_num < col_amount:\n element_num += 1\n #print(sum_differences)\n diff_array.append(sum_differences)\n sum_differences = 0\n #print(element_num)\n element_num = 0 # Reset element number\n if centroid_num < 4: # Used to change cluster\n centroid_num += 1\n #print(\"Which centroids[] it is looking at\", centroid_num)\n\n row_in_clust += 1 # Once all items are seen, change cluster\n\n print(\"The calculated distances from each cluster's columns to their corresponding\"\n \" centroids:\\n\", diff_array)\n\n min_val, index = min((min_val, index) for (index, min_val) in enumerate(diff_array))\n print(\"Minimum value\", min_val, \"found at index:\", index)\n chng_clust, new_index = get_cluster_and_index(min_val, index)\n\n print(\"\\nChanging cluster:\", chng_clust, \"\\nIndex\", new_index)\n\n\ndef get_cluster_and_index(cluster, index):\n\n if 0 <= index <= 3:\n cluster = 0\n # index stays itself\n if 4 <= index <= 8:\n cluster = 1\n index %= 2\n if 9 <= index <= 12:\n cluster = 2\n index %= 3\n if 13 <= index <= 16:\n cluster = 3\n index %= 4\n if 17 <= index <= 20:\n cluster = 4\n index %= 5\n return cluster, index\n\n\ninitialization()\n","sub_path":"kMeansAlg2.py","file_name":"kMeansAlg2.py","file_ext":"py","file_size_in_byte":9529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"436972078","text":"import pandas as pd\nfrom neuralnet import DeepNeuralNetwork\n\n\ndef neuralnet():\n features = pd.read_csv(\"Lab4/data/features.txt\", header=None)\n labels = pd.read_csv(\"Lab4/data/labels.txt\", header=None).replace(10, 0)\n df = features.copy()\n df[\"label\"] = labels\n\n NN = DeepNeuralNetwork(df, [50])\n NN.gradientDescent(alpha=1e-4, threshold=1e-4, epochs=1000)\n print(\"NN 50 neurons\")\n print(\"Train accuracy:\", NN.accuracy(NN.X_train, NN.labels_train))\n print(\"Test accuracy:\", NN.accuracy(NN.X_test, NN.labels_test))\n NN.plotCostAccuracy()\n\n\nneuralnet()\n","sub_path":"test_neuralnet.py","file_name":"test_neuralnet.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"12106974","text":"from domain import Proxy\nfrom lxml import etree\n\nimport requests\nimport chardet\nfrom utils.http import get_ua_header\n\n\nclass Base_Spider():\n # 目标网址列表\n urls = []\n # 分组xpath 大的标签\n group_xpath = ''\n # 组内的xpath 获取细节\n detail_xpath = {}\n\n def __init__(self, urls=[], group_xpath='', detail_xpath={}):\n\n if urls:\n self.urls = urls\n if group_xpath:\n self.group_xpath = group_xpath\n if detail_xpath:\n self.detail_xpath = detail_xpath\n\n def check_list(self, lis):\n return lis[0] if len(lis) != 0 else \"\"\n\n def get_page_from_url(self, url):\n res = requests.get(url=url, headers=get_ua_header(), timeout=10)\n encoding = chardet.detect(res.content)['encoding']\n res.encoding = encoding\n\n return res.text\n\n def get_proxies_from_url(self, page):\n\n html = etree.HTML(page)\n trs = html.xpath(self.group_xpath)\n for i in trs:\n ip = self.check_list(i.xpath(self.detail_xpath['ip']))\n port = self.check_list(i.xpath(self.detail_xpath['port']))\n area = self.check_list(i.xpath(self.detail_xpath['area']))\n p = Proxy(ip=ip, port=port, area=area)\n yield p\n\n # 爬取方法\n def get_proxies(self):\n for i in self.urls:\n try:\n # 发送请求获取页面对象\n page = self.get_page_from_url(url=i)\n # 解析页面 返回的是一个生成器\n proxies = self.get_proxies_from_url(page)\n\n yield from proxies\n except Exception as e:\n pass\n\n\nif __name__ == '__main__':\n config = {\"urls\": [\"http://www.ip3366.net/?stype=1&page={}\".format(i) for i in range(1, 3)],\n \"group_xpath\": '//div[@id=\"list\"]/table/tbody/tr',\n \"detail_xpath\": {\n \"ip\": \"./td[1]/text()\",\n \"port\": \"./td[2]/text()\",\n \"area\": \"./td[6]/text()\"\n }}\n spider = Base_Spider(**config)\n proxy = spider.get_proxies()\n # print(proxy)\n for i in proxy:\n print(i)\n","sub_path":"core/proxy_spider/base_spider.py","file_name":"base_spider.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"605571980","text":"import socket\r\nimport numpy as np\r\nimport pandas as pd\r\nimport math\r\nfrom datetime import datetime\r\n\r\nERROR_DICT = {}\r\nERROR_DICT['00101'] = 'IP address error'\r\nERROR_DICT['00102'] = 'Port number error'\r\nERROR_DICT['00103'] = 'Connection error with license EA'\r\nERROR_DICT['00104'] = 'Undefined answer from license EA'\r\n\r\nERROR_DICT['00301'] = 'Unknown instrument'\r\nERROR_DICT['00302'] = 'No instruments defined/configured'\r\n\r\nERROR_DICT['00501'] = 'No instrument defined/configured'\r\n\r\nERROR_DICT['00601'] = 'Data directory name error'\r\n\r\nERROR_DICT['01001'] = 'Error in account settings'\r\n\r\nERROR_DICT['01101'] = 'Instrument already done'\r\nERROR_DICT['01102'] = 'Error in one of the settings'\r\nERROR_DICT['01103'] = 'Unknown instrument'\r\n\r\nERROR_DICT['01301'] = 'In demo mode not all instruments can be configured'\r\nERROR_DICT['01302'] = 'Reset first the back tester'\r\nERROR_DICT['01303'] = 'Can set instruments only once, first reset the back tester'\r\nERROR_DICT['01304'] = 'Error in creating data factory'\r\nERROR_DICT['01305'] = 'Error in reading the M1 bar data from file'\r\nERROR_DICT['01306'] = 'Data file does not exist'\r\nERROR_DICT['01307'] = 'Invalid demo instrument'\r\n\r\nERROR_DICT['01501'] = 'Wrong low spread value'\r\nERROR_DICT['01502'] = 'Wrong high spread value' \r\nERROR_DICT['01503'] = 'Wrong commissionvalue'\r\nERROR_DICT['01504'] = 'Instrument not defined'\r\n\r\nERROR_DICT['01601'] = 'Index > 0'\r\nERROR_DICT['01602'] = 'Index wrong type'\r\nERROR_DICT['01603'] = 'No instruments defined'\r\nERROR_DICT['01604'] = 'index > max bars'\r\nERROR_DICT['01605'] = 'Undefined error'\r\nERROR_DICT['01606'] = 'Function only possible at start, if no bars are build. First do reset'\r\n\r\nERROR_DICT['01901'] = 'Wrong time frame value'\r\nERROR_DICT['01902'] = 'Time frames already defined, first BT full reset or BT reset pointers'\r\n\r\nERROR_DICT['02001'] = 'Undefined instrument'\r\nERROR_DICT['02002'] = 'No valid instrument'\r\n\r\nERROR_DICT['04101'] = 'Unknown instrument'\r\nERROR_DICT['04102'] = 'Time frame not defined/set'\r\n\r\nERROR_DICT['04201'] = 'History to short for the requested amount of bars'\r\nERROR_DICT['04202'] = 'No data available, instrument not defined!!!'\r\nERROR_DICT['04203'] = 'Error in start bar value' \r\nERROR_DICT['04204'] = 'Error in number of bar value' \r\nERROR_DICT['04205'] = 'Error in max bar value'\r\n\r\nERROR_DICT['04501'] = 'History to short'\r\nERROR_DICT['04502'] = 'No valid index value'\r\nERROR_DICT['04503'] = 'No valid time frame'\r\nERROR_DICT['04504'] = 'Instrument not defined/configured'\r\n\r\nERROR_DICT['07001'] = 'Instrument not defined' \r\nERROR_DICT['07002'] = 'Error unknown' \r\nERROR_DICT['07003'] = 'Wrong lot size' \r\nERROR_DICT['07004'] = 'Order type unknown'\r\nERROR_DICT['07005'] = 'Error in one of the parameters' \r\nERROR_DICT['07006'] = 'Wrong TP value' \r\nERROR_DICT['07007'] = 'Wrong SL value'\r\n\r\nERROR_DICT['07101'] = 'Position not found'\r\n\r\nERROR_DICT['07301'] = 'Order not found'\r\n\r\nERROR_DICT['07501'] = 'Error in sl or tp value, not real values' \r\nERROR_DICT['07502'] = 'Position not found'\r\nERROR_DICT['07506'] = 'Wrong TP value' \r\nERROR_DICT['07507'] = 'Wrong SL value'\r\n\r\nERROR_DICT['07601'] = 'Error in sl or tp value, not real values'\r\nERROR_DICT['07602'] = 'Order not found'\r\nERROR_DICT['07606'] = 'Wrong TP value' \r\nERROR_DICT['07607'] = 'Wrong SL value'\r\n\r\nERROR_DICT['07701'] = 'Error in sl or tp value, not real values'\r\nERROR_DICT['07702'] = 'Position not found'\r\n\r\nERROR_DICT['07801'] = 'Error in sl or tp value, not real values'\r\nERROR_DICT['07802'] = 'Order not found' \r\n\r\nERROR_DICT['10101'] = 'Wrong or not implemeneted bar type'\r\n\r\nERROR_DICT['10201'] = 'Empty list' \r\nERROR_DICT['10202'] = 'Max 3 brick sizes'\r\nERROR_DICT['10203'] = 'No valid brick size value'\r\nERROR_DICT['10204'] = 'Undefined error' \r\n\r\nERROR_DICT['14103'] = 'Unknown brick code/size' \r\nERROR_DICT['14104'] = 'Error in brick code/size' \r\nERROR_DICT['14105'] = 'No brick code/size defined' \r\n\r\nERROR_DICT['14201'] = 'Error instrument name'\r\nERROR_DICT['14202'] = 'Instrument not defined' \r\nERROR_DICT['14203'] = 'Unknown brick code/size' \r\nERROR_DICT['14204'] = 'Error in brick code/size' \r\nERROR_DICT['14205'] = 'Error in number of bars and start bar definition/settings' \r\nERROR_DICT['14206'] = 'Brick code/size not defined'\r\nERROR_DICT['14207'] = 'History to short' \r\nERROR_DICT['14208'] = 'Undefined error'\r\n\r\nERROR_DICT['14501'] = 'History to short'\r\nERROR_DICT['14502'] = 'No valid index value'\r\nERROR_DICT['14503'] = 'No valid brick code'\r\nERROR_DICT['14504'] = 'Brick code not configured'\r\nERROR_DICT['14505'] = 'At least 1 instrument not configured'\r\n\r\nERROR_DICT['15101'] = 'Instrument not defined'\r\nERROR_DICT['15102'] = 'Brick code not valid'\r\nERROR_DICT['15103'] = 'Brick code not active'\r\n\r\nERROR_DICT['50001'] = 'Error in comma/dot function' \r\n\r\nERROR_DICT['50101'] = 'Instrument not defined'\r\nERROR_DICT['50102'] = 'Undefined error'\r\n\r\nERROR_DICT['99901'] = 'Wrong bar type, can not mix bar types' \r\n\r\nclass Pytrader_BT_API:\r\n\r\n def __init__(self):\r\n \r\n self.socket_error: int = 0\r\n self.socket_error_message: str = ''\r\n self.order_return_message: str = ''\r\n self.order_error: int = 0\r\n self.connected: bool = False\r\n self.timeout: bool = False\r\n self.command_OK: bool = False\r\n self.command_return_error: str = ''\r\n self.debug: bool = False\r\n self.version: str = '1.00'\r\n self.max_bars: int = 5000\r\n self.max_ticks: int = 5000\r\n self.timeout_value: int = 120\r\n self.instrument_conversion_list: dict = {}\r\n self.instrument_name_broker: str = ''\r\n self.instrument_name_universal: str = ''\r\n self.date_from: datetime = '2000/01/01, 00:00:00'\r\n self.date_to: datetime = datetime.now()\r\n self.invert_array: bool = False\r\n self.data_directory: str = None\r\n self.brick_code: str = 'B1'\r\n\r\n self.error_dict: dict = {}\r\n self.license: str = 'Demo'\r\n\r\n def Disconnect(self):\r\n \"\"\"\r\n Closes the socket connection to a MT4 or MT5 EA bot.\r\n\r\n Args:\r\n None\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n\r\n self.sock.close()\r\n return True\r\n\r\n def Connect(self,\r\n server: str = '',\r\n port: int = 8888,\r\n instrument_lookup: dict = []) -> bool:\r\n \"\"\"\r\n Connects to BT.\r\n\r\n Args:\r\n server: Server IP address, like -> '127.0.0.1', '192.168.5.1'\r\n port: port number\r\n instrument_lookup: dictionairy with general instrument names and broker intrument names\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n self.sock.setblocking(1)\r\n self.port = port\r\n self.server = server\r\n self.instrument_conversion_list = instrument_lookup\r\n\r\n if (len(self.instrument_conversion_list) == 0):\r\n print('Broker Instrument list not available or empty')\r\n self.socket_error_message = 'Broker Instrument list not available'\r\n return False\r\n\r\n try:\r\n self.sock.connect((self.server, self.port))\r\n try:\r\n data_received = self.sock.recv(1000000).decode()\r\n self.connected = True\r\n self.socket_error = 0\r\n self.socket_error_message = ''\r\n print(data_received)\r\n return True\r\n except socket.error as msg:\r\n self.socket_error = 100\r\n self.socket_error_message = 'Could not connect to server.'\r\n self.connected = False\r\n return False\r\n except socket.error as msg:\r\n print(\r\n \"Couldnt connect with the socket-server: %self.sock\\n terminating program\" %\r\n msg)\r\n self.connected = False\r\n self.socket_error = 101\r\n self.socket_error_message = 'Could not connect to server.'\r\n return False\r\n \r\n def Check_connection(self) -> bool:\r\n\r\n \"\"\"\r\n Checks if connection with MT terminal/Ea bot is still active.\r\n Args:\r\n None\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.command = 'F000#0#'\r\n self.command_return_error = ''\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if (ok == False):\r\n self.command_OK = False\r\n return False\r\n \r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n\r\n if x[2] == 'OK':\r\n self.timeout = True\r\n self.command_OK = True\r\n return True\r\n else:\r\n self.timeout = False\r\n self.command_OK = True\r\n return False\r\n \r\n def Set_timeout(self,\r\n timeout_in_seconds: int = 60\r\n ):\r\n \"\"\"\r\n Set time out value for socket communication with BT.\r\n\r\n Args:\r\n timeout_in_seconds: the time out value\r\n Returns:\r\n True\r\n \"\"\"\r\n self.timeout_value = timeout_in_seconds\r\n return True\r\n\r\n @property\r\n def IsConnected(self) -> bool:\r\n \"\"\"\r\n Returns connection status.\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n return self.connected\r\n\r\n def Set_bartype(self,\r\n bar_type: str = 'OHLC') -> bool:\r\n \"\"\"\r\n Sets the bartype\r\n Args:\r\n type: OHLC, RENKO OHLC is default at start of BT Server\r\n Returns:\r\n bool: True or False\r\n\r\n Remarks, default OHLC, other definitions are additional, seperate retrieve functions\r\n \"\"\"\r\n\r\n self.command = 'F101#1#' + str(bar_type).upper() + \"#\"\r\n self.command_return_error = ''\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if not ok:\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if x[0] != 'F101':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return False\r\n\r\n return True\r\n\r\n def Set_bartype_parameters_for_renko(self,\r\n brick_list_in_pips: list = [10.0, 12.0, 15.0]) -> bool:\r\n\r\n \"\"\"\r\n Sets the bar type parameters\r\n Args:\r\n brick_value: size in pips\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n\r\n self.brick_list_in_pips = brick_list_in_pips\r\n\r\n if (len(self.brick_list_in_pips) == 0):\r\n self.command_return_error = ERROR_DICT['10201']\r\n return False\r\n \r\n if (len(self.brick_list_in_pips) > 3):\r\n self.command_return_error = ERROR_DICT['10202']\r\n return False \r\n\r\n self.command = 'F102#'\r\n self.command = self.command + str(len(self.brick_list_in_pips)) + '#'\r\n for index in range(len(self.brick_list_in_pips)):\r\n self.command = self.command + str(self.brick_list_in_pips[index]) + '#'\r\n\r\n self.command_return_error = ''\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if not ok:\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if x[0] != 'F102':\r\n self.command_return_error = ERROR_DICT[str(x[2])]\r\n self.command_OK = False\r\n return False\r\n\r\n return True\r\n\r\n def Set_comma_or_dot(self,\r\n mode: str = 'comma') -> bool:\r\n \"\"\"\r\n Sets if the BT must see real values as comma or dot string notation\r\n This is country/culture/region dependend\r\n Args:\r\n mode: comma or dot\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.command = 'F500#1#' + str(mode) + \"#\"\r\n self.command_return_error = ''\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if not ok:\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if x[0] != 'F500':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return None\r\n\r\n return True\r\n\r\n def Check_license(self, \r\n server: str = '127.0.0.1',\r\n port: int = 5555) -> bool:\r\n\r\n \"\"\"\r\n Check for license.\r\n\r\n Args:\r\n server: License Server IP address, like -> '127.0.0.1', '192.168.5.1'\r\n port: port number, default 5555\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.license = 'Demo'\r\n self.command = 'F001#2#' + str(server) + \"#\" + str(port) + '#'\r\n self.command_return_error = ''\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if x[0] != 'F001':\r\n self.command_return_error = ERROR_DICT[str(50102)]\r\n self.command_OK = False\r\n return None \r\n\r\n self.license = str(x[3])\r\n if self.license == 'Demo':\r\n return False\r\n \r\n return True\r\n\r\n def Check_trading_allowed(self) -> bool:\r\n\r\n \"\"\"\r\n Check for trading allowed.\r\n\r\n Returns:\r\n bool: True or False. Allways allowed\r\n \"\"\" \r\n return True\r\n\r\n def Set_data_directory(self, \r\n data_directory: str = None) -> bool:\r\n\r\n \"\"\"\r\n Set data directory/folder.\r\n\r\n Args:\r\n data_directory: data directory where BT can find M1 data files\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.data_directory = data_directory\r\n if (self.data_directory != None):\r\n self.command = 'F006#1#' + str(self.data_directory) + '#'\r\n self.command_return_error = ''\r\n ok, dataString = self.send_command(self.command)\r\n if not ok:\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if x[0] != 'F006':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return False\r\n else:\r\n return True \r\n\r\n def Set_bar_date_asc_desc(self,\r\n asc_desc: bool = False) -> bool:\r\n \"\"\"\r\n Sets first row of array as first bar or as last bar\r\n In MT4/5 element[0] of an array is normaliter actual bar/candle\r\n Depending on the math you want to apply, this has to be the opposite\r\n Args:\r\n asc_dec: True = row[0] is oldest bar\r\n False = row[0] is latest bar\r\n Returns:\r\n bool: True or False\r\n \"\"\" \r\n self.invert_array = asc_desc\r\n return True\r\n\r\n def Get_broker_server_time(self) -> datetime:\r\n \"\"\"\r\n Retrieves broker server time.\r\n Args:\r\n None\r\n Returns:\r\n datetime: Boker time, this is the time of the current M1 bar\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.command = 'F005#0#'\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if x[0] != 'F005':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return None\r\n\r\n del x[0:2]\r\n x.pop(-1)\r\n y = x[0].split('-')\r\n d = datetime(int(y[0]), int(y[1]), int(y[2]),\r\n int(y[3]), int(y[4]), int(y[5]))\r\n return d\r\n\r\n def Get_dynamic_account_info(self) -> dict:\r\n \"\"\"\r\n Retrieves dynamic account information.\r\n Returns: Dictionary with:\r\n Account balance,\r\n Account equity,\r\n Account profit\r\n \"\"\"\r\n self.command_return_error = ''\r\n ok, dataString = self.send_command('F002#0#')\r\n if (ok == False):\r\n self.command_OK = False\r\n return None\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if x[0] != 'F002':\r\n self.command_return_error = str(x[2])\r\n self.command_OK = False\r\n return None\r\n\r\n returnDict = {}\r\n del x[0:2]\r\n x.pop(-1)\r\n\r\n returnDict['balance'] = float(x[0])\r\n returnDict['equity'] = float(x[1])\r\n returnDict['profit'] = float(x[2])\r\n\r\n self.command_OK = True\r\n return returnDict\r\n\r\n def Set_instrument_list(self,\r\n instrument_list: list = ['EURUSD']) -> bool:\r\n \r\n \"\"\"\r\n Sets the instruments for the BT\r\n\r\n Args:\r\n instrument_list: list with instruments\r\n Returns:\r\n bool: True or False\r\n Remark: Now the M1 data file contents are imported in the BT for the specified instruments\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.command = 'F013#'\r\n if (len(instrument_list) == 0):\r\n self.command_return_error = 'empty list'\r\n return False\r\n\r\n self.command = self.command + str(len(instrument_list)) + '#'\r\n\r\n for element in instrument_list:\r\n self.command = self.command + element + '#'\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if (ok == False):\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if x[0] != 'F013':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return False \r\n\r\n self.timeout = True\r\n self.command_OK = True\r\n return True\r\n\r\n def Set_timeframes(self,\r\n timeframe_list: list = ['M1', 'H1']) -> bool:\r\n \"\"\"\r\n Set the timeframes for the BT to be used, this is for OHLC bars/candles\r\n\r\n Args:\r\n timeframe_list: List with timeframes\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.command = 'F019#'\r\n if (len(timeframe_list) == 0):\r\n self.command_return_error = 'empty list'\r\n return False\r\n \r\n self.command = self.command + str(len(timeframe_list)) + '#'\r\n for element in timeframe_list:\r\n self.command = self.command + element + '#'\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if (ok == False):\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if x[0] != 'F019':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return False \r\n \r\n if x[2] == 'OK':\r\n self.timeout = True\r\n self.command_OK = True\r\n return True\r\n \r\n def Set_instrument_parameters(self,\r\n instrument: str = 'EURUSD',\r\n digits: int = 5,\r\n max_lotsize: float = 200.0,\r\n min_lotsize: float = 0.01,\r\n lot_stepsize: float = 0.01,\r\n point: float = 0.00001,\r\n tick_size: float = 0.00001,\r\n tick_value: float = 1.0,\r\n swap_long: float = 0.00,\r\n swap_short: float = 0.00) -> bool:\r\n \"\"\"\r\n Set the parameters for an instrument\r\n\r\n Args:\r\n server: instrument\r\n digits: number of digits\r\n max_lotsize: maximum lotsize value\r\n min_lotsize: minimum lotsize value\r\n lot_stepsize: minimum lot stepsize increment\r\n point: poit value\r\n tick_size: tick size or point value\r\n tick_value: tick value\r\n swap_long; swap long/buy value\r\n swap_short: swap short/sell value\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.command_return_error = ''\r\n\r\n self.command = 'F011#10#' + str(instrument) + '#' + str(digits) + '#' + str(max_lotsize) + '#' + str(min_lotsize) + \\\r\n \"#\" + str(lot_stepsize) + \"#\" + str(point) + \"#\" + str(tick_size) + \"#\" + str(tick_value) + \\\r\n '#' + str(swap_long) + '#' + str(swap_short) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if (ok == False):\r\n self.command_OK = False\r\n return False\r\n \r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if x[0] != 'F011':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return False\r\n\r\n if x[2] == 'OK':\r\n self.timeout = True\r\n self.command_OK = True\r\n return True\r\n\r\n def Get_instrument_info(self,\r\n instrument: str = 'EURUSD') -> dict:\r\n \"\"\"\r\n Retrieves instrument information.\r\n\r\n Args:\r\n instrument: instrument name\r\n Returns: Dictionary with:\r\n instrument,\r\n digits,\r\n max_lotsize,\r\n min_lotsize,\r\n lot_step,\r\n point,\r\n tick_size,\r\n tick_value\r\n swap_long\r\n swap_short\r\n \"\"\"\r\n\r\n self.command_return_error = ''\r\n self.instrument_name_universal = instrument.upper()\r\n self.instrument = self.get_broker_instrument_name(self.instrument_name_universal)\r\n if (self.instrument == 'none' or self.instrument == None):\r\n self.command_return_error = 'Instrument not in broker list'\r\n self.command_OK = False\r\n return None\r\n\r\n\r\n self.command = 'F003#1#' + self.instrument + '#'\r\n\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if x[0] != 'F003':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return None\r\n\r\n returnDict = {}\r\n del x[0:2]\r\n x.pop(-1)\r\n\r\n returnDict['instrument'] = str(self.instrument_name_universal)\r\n returnDict['digits'] = int(x[0])\r\n returnDict['max_lotsize'] = float(x[1])\r\n returnDict['min_lotsize'] = float(x[2])\r\n returnDict['lot_step'] = float(x[3])\r\n returnDict['point'] = float(x[4])\r\n returnDict['tick_size'] = float(x[5])\r\n returnDict['tick_value'] = float(x[6])\r\n returnDict['swap_long'] = float(x[7])\r\n returnDict['swap_short'] = float(x[8])\r\n\r\n self.command_OK = True\r\n return returnDict\r\n\r\n def Reset_backtester_pointers(self) -> bool:\r\n \r\n \"\"\"\r\n All pointers in the BT will be resetted\r\n But no new instrument list and no new time frame list can be set\r\n \"\"\"\r\n self.command = 'F009#0#'\r\n self.command_return_error = ''\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if (ok == False):\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n\r\n if x[2] == 'OK':\r\n self.timeout = True\r\n self.command_OK = True\r\n return True\r\n else:\r\n self.timeout = False\r\n self.command_OK = True\r\n return False\r\n \r\n def Reset_backtester(self) -> bool:\r\n \"\"\"\r\n Reset of backtester.\r\n After this reset new instrument list can be set\r\n \"\"\"\r\n self.command = 'F008#0#'\r\n self.command_return_error = ''\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if (ok == False):\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n\r\n if x[2] == 'OK':\r\n self.timeout = True\r\n self.command_OK = True\r\n return True\r\n else:\r\n self.timeout = False\r\n self.command_OK = True\r\n return False\r\n\r\n def Set_account_parameters(self,\r\n balance: float = 10000.0,\r\n max_pendings: int = 50,\r\n margin_call: int = 50) -> bool:\r\n \"\"\"\r\n Set account parameters\r\n\r\n Args:\r\n balance: Start amount of balance, like initial deposit\r\n max_pendings: maximum number op pending orders\r\n margin_call: to be defined, at the moment not used\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n \r\n self.balance = balance\r\n self.max_pendings = max_pendings\r\n self.margin_call = margin_call\r\n\r\n self.command_return_error = ''\r\n\r\n self.command = 'F010#3#' + str(self.balance) + '#' + str(self.max_pendings) + '#' + str(self.margin_call) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if (ok == False):\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n\r\n if x[0] != 'F010':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return False\r\n\r\n if x[2] == 'OK':\r\n self.timeout = True\r\n self.command_OK = True\r\n return True\r\n\r\n def Set_spread_and_commission_in_pips(self,\r\n instrument: str = 'EURUSD',\r\n low_spread_in_pips: float = 1.0,\r\n high_spread_in_pips: float = 1.2,\r\n commission_in_pips: float = 1.10) -> bool:\r\n self.low_spread_in_pips = low_spread_in_pips\r\n self.high_spread_in_pips = high_spread_in_pips\r\n self.commission_in_pips = commission_in_pips\r\n\r\n \"\"\"\r\n Set spread range and commission\r\n\r\n Args:\r\n instrument: instrument name\r\n low_spread_in_pips: minimum spread\r\n high_spread_in_pips: maximum spread\r\n commission_in_pips: commission for opening and closing a trade\r\n Returns:\r\n bool: True or False\r\n Remark:\r\n At opening or closing a trade the spread used will have a value between minimum and maximum spread values (random)\r\n \"\"\"\r\n self.command_return_error = ''\r\n\r\n self.command = 'F015#4#' + str(instrument) + \"#\" + str(self.low_spread_in_pips) + '#' + str(self.high_spread_in_pips) + '#' + str(self.commission_in_pips) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if (ok == False):\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F015':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return False\r\n\r\n if x[2] == 'OK':\r\n self.timeout = True\r\n self.command_OK = True\r\n return True\r\n else:\r\n self.timeout = False\r\n self.command_OK = True\r\n return False\r\n\r\n def Set_index_for_start(self,\r\n index: int = 0) -> bool:\r\n \"\"\"\r\n Set the start index for start using the BT\r\n This is for building some history in TF bars, like MT5, MT15, ....\r\n\r\n Args:\r\n index: moves the pointers in the BT to this value\r\n\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.command = 'F016#1#' + str(index) + '#'\r\n\r\n ok, dataString = self.send_command(self.command)\r\n \r\n if (ok == False):\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if x[0] != 'F016':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return False\r\n\r\n if x[2] == 'OK':\r\n self.timeout = True\r\n self.command_OK = True\r\n return True \r\n \r\n def Go_x_increments_forwards(self,\r\n increments: int = 0) -> bool:\r\n \"\"\"\r\n Moves the index/pointers in the BT forwards\r\n Info of new M1 bars are added to the history\r\n\r\n Args:\r\n increments: pointer for M1 data/bars will be incremented by x\r\n all other pointers depends on the time frame\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.command = 'F017#1#' + str(increments) + '#'\r\n\r\n ok, dataString = self.send_command(self.command)\r\n \r\n if (ok == False):\r\n self.command_OK = False\r\n return False\r\n \r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if x[0] != 'F017':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return False\r\n\r\n if x[2] == 'OK':\r\n self.timeout = True\r\n self.command_OK = True\r\n return True\r\n \r\n def Get_actual_bar_info(self,\r\n instrument: str = 'EURUSD',\r\n timeframe: int = 16408) -> dict:\r\n \"\"\"\r\n Retrieves instrument last actual data.\r\n Args:\r\n instrument: instrument name\r\n timeframe: time frame like H1, H4\r\n Returns: Dictionary with:\r\n instrument name,\r\n date,\r\n open,\r\n high,\r\n low,\r\n close,\r\n volume\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.instrument_name_universal = instrument.upper()\r\n self.command = 'F041#2#' + self.get_broker_instrument_name(\r\n self.instrument_name_universal) + '#' + str(timeframe) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F041':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return None\r\n\r\n del x[0:2]\r\n x.pop(-1)\r\n returnDict = {}\r\n returnDict['instrument'] = str(self.instrument_name_universal)\r\n returnDict['date'] = int(x[0])\r\n returnDict['open'] = float(x[1])\r\n returnDict['high'] = float(x[2])\r\n returnDict['low'] = float(x[3])\r\n returnDict['close'] = float(x[4])\r\n returnDict['volume'] = float(x[5])\r\n\r\n self.command_OK = True\r\n return returnDict\r\n \r\n def Get_last_x_bars_from_now(self,\r\n instrument: str = 'EURUSD',\r\n timeframe: int = 16408,\r\n nbrofbars: int = 1000) -> np.array:\r\n \"\"\"\r\n Retrieves last x bars .\r\n\r\n Args:\r\n instrument: name of instrument like EURUSD\r\n timeframe: timeframe like 'H4'\r\n nbrofbars: Number of bars to retrieve\r\n Returns: numpy array with:\r\n date,\r\n open,\r\n high,\r\n low,\r\n close,\r\n volume\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.instrument_name_universal = instrument.upper()\r\n self.numberofbars = nbrofbars\r\n\r\n dt = np.dtype([('date', np.int64), ('open', np.float64), ('high', np.float64),\r\n ('low', np.float64), ('close', np.float64), ('volume', np.int32)])\r\n rates = np.empty(self.numberofbars, dtype=dt)\r\n\r\n if (self.numberofbars > self.max_bars):\r\n iloop = self.numberofbars / self.max_bars\r\n iloop = math.floor(iloop)\r\n itail = int(self.numberofbars - iloop * self.max_bars)\r\n\r\n for index in range(0, iloop):\r\n self.command = 'F042#5#' + self.get_broker_instrument_name(self.instrument_name_universal) + '#' + \\\r\n str(timeframe) + '#' + str(index * self.max_bars) + '#' + str(self.max_bars) + '#' + str(nbrofbars) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n \r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n if self.debug:\r\n print(dataString)\r\n print('')\r\n print(len(dataString))\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F042':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return None\r\n\r\n del x[0:2]\r\n x.pop(-1)\r\n\r\n for value in range(0, len(x)):\r\n y = x[value].split('$')\r\n\r\n rates[value + index * self.max_bars][0] = int(y[0])\r\n rates[value + index * self.max_bars][1] = float(y[1])\r\n rates[value + index * self.max_bars][2] = float(y[2])\r\n rates[value + index * self.max_bars][3] = float(y[3])\r\n rates[value + index * self.max_bars][4] = float(y[4])\r\n rates[value + index * self.max_bars][5] = float(y[5])\r\n\r\n if (len(x) < self.max_bars):\r\n #rates = np.sort(rates)\r\n rates = np.sort(rates[rates[:]['date']!=0])\r\n self.command_OK = True\r\n if (self.invert_array == True):\r\n rates = np.flipud(rates)\r\n \"\"\" if (self.invert_array == True):\r\n rates = np.sort(rates) \"\"\"\r\n return rates\r\n\r\n if (itail == 0):\r\n #rates = np.sort(rates)\r\n rates = np.sort(rates[rates[:]['date']!=0])\r\n self.command_OK = True\r\n \"\"\" if (self.invert_array == True):\r\n rates = np.sort(rates) \"\"\"\r\n if (self.invert_array == True):\r\n rates = np.flipud(rates)\r\n return rates\r\n\r\n if (itail > 0):\r\n self.command = 'F042#5#' + self.get_broker_instrument_name(\r\n self.instrument_name_universal) + '#' + str(timeframe) + '#' + str(\r\n iloop * self.max_bars) + '#' + str(itail) + '#' + str(nbrofbars) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n if self.debug:\r\n print(dataString)\r\n print('')\r\n print(len(dataString))\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F042':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return None\r\n\r\n del x[0:2]\r\n x.pop(-1)\r\n\r\n for value in range(0, len(x)):\r\n y = x[value].split('$')\r\n\r\n rates[value + iloop * self.max_bars][0] = int(y[0])\r\n rates[value + iloop * self.max_bars][1] = float(y[1])\r\n rates[value + iloop * self.max_bars][2] = float(y[2])\r\n rates[value + iloop * self.max_bars][3] = float(y[3])\r\n rates[value + iloop * self.max_bars][4] = float(y[4])\r\n rates[value + iloop * self.max_bars][5] = float(y[5])\r\n\r\n self.command_OK = True\r\n #rates = np.sort(rates)\r\n rates = np.sort(rates[rates[:]['date']!=0])\r\n if (self.invert_array == True):\r\n rates = np.flipud(rates)\r\n \"\"\" if (self.invert_array == True):\r\n rates = np.sort(rates) \"\"\"\r\n return rates\r\n else:\r\n self.command = 'F042#5#' + str(self.get_broker_instrument_name(self.instrument_name_universal)) + '#' + \\\r\n str(timeframe) + '#' + str(0) + '#' + str(self.numberofbars) + '#' + str(nbrofbars) + '#'\r\n #print(self.command)\r\n ok, dataString = self.send_command(self.command)\r\n if not ok:\r\n self.command_OK = False\r\n print('not ok')\r\n return None\r\n if self.debug:\r\n print(dataString)\r\n print('')\r\n print(len(dataString))\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F042':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return None\r\n\r\n del x[0:2]\r\n x.pop(-1)\r\n\r\n for value in range(0, len(x)):\r\n y = x[value].split('$')\r\n\r\n rates[value][0] = int(y[0])\r\n rates[value][1] = float(y[1])\r\n rates[value][2] = float(y[2])\r\n rates[value][3] = float(y[3])\r\n rates[value][4] = float(y[4])\r\n rates[value][5] = float(y[5])\r\n\r\n self.command_OK = True\r\n rates = np.sort(rates[rates[:]['date']!=0])\r\n if (self.invert_array == True):\r\n rates = np.flipud(rates)\r\n \"\"\" if (self.invert_array == True):\r\n rates = np.sort(rates) \"\"\"\r\n return rates\r\n\r\n def Get_actual_renko_bar_info(self,\r\n instrument: str = 'EURUSD',\r\n brick_code: str = 'B1') -> dict:\r\n \"\"\"\r\n Retrieves instrument last actual renko bar.\r\n Args:\r\n instrument: instrument name\r\n brick_code: should be \"B1\", \"B2\" or \"B3\"\r\n Returns: Dictionary with:\r\n instrument name,\r\n date,\r\n open,\r\n high,\r\n low,\r\n close,\r\n volume\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.brick_code = brick_code\r\n self.instrument_name_universal = instrument.upper()\r\n self.command = 'F141#2#' + self.get_broker_instrument_name(\r\n self.instrument_name_universal) + '#' + str(brick_code) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F141':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return None\r\n\r\n del x[0:2]\r\n x.pop(-1)\r\n returnDict = {}\r\n returnDict['instrument'] = str(self.instrument_name_universal)\r\n returnDict['date'] = int(x[0])\r\n returnDict['open'] = float(x[1])\r\n returnDict['high'] = float(x[2])\r\n returnDict['low'] = float(x[3])\r\n returnDict['close'] = float(x[4])\r\n returnDict['volume'] = float(x[5])\r\n\r\n self.command_OK = True\r\n return returnDict\r\n\r\n def Get_last_x_renko_bars_from_now(self,\r\n instrument: str = 'EURUSD',\r\n brick_code: str = 'B1',\r\n nbrofbars: int = 1000) -> np.array:\r\n \"\"\"\r\n retrieves last x renko bars\r\n\r\n Args:\r\n instrument: name of instrument like EURUSD\r\n brick_code: should be \"B1\", \"B2\" or \"B3\"\r\n nbrofbars: Number of bars to retrieve\r\n Returns: numpy array with:\r\n date,\r\n open,\r\n high,\r\n low,\r\n close,\r\n volume\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.instrument_name_universal = instrument.upper()\r\n self.numberofbars = nbrofbars\r\n\r\n dt = np.dtype([('date', np.int64), ('open', np.float64), ('high', np.float64),\r\n ('low', np.float64), ('close', np.float64), ('volume', np.int32)])\r\n rates = np.empty(self.numberofbars, dtype=dt)\r\n\r\n if (self.numberofbars > self.max_bars):\r\n iloop = self.numberofbars / self.max_bars\r\n iloop = math.floor(iloop)\r\n itail = int(self.numberofbars - iloop * self.max_bars)\r\n #print('iloop: ' + str(iloop))\r\n #print('itail: ' + str(itail))\r\n\r\n for index in range(0, iloop):\r\n self.command = 'F142#5#' + self.get_broker_instrument_name(self.instrument_name_universal) + '#' + str(brick_code) + \"#\" + \\\r\n str(index * self.max_bars) + '#' + str(self.max_bars) + '#' + str(nbrofbars) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n if self.debug:\r\n print(dataString)\r\n print('')\r\n print(len(dataString))\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F042':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return None\r\n\r\n del x[0:2]\r\n x.pop(-1)\r\n\r\n for value in range(0, len(x)):\r\n y = x[value].split('$')\r\n\r\n rates[value + index * self.max_bars][0] = int(y[0])\r\n rates[value + index * self.max_bars][1] = float(y[1])\r\n rates[value + index * self.max_bars][2] = float(y[2])\r\n rates[value + index * self.max_bars][3] = float(y[3])\r\n rates[value + index * self.max_bars][4] = float(y[4])\r\n rates[value + index * self.max_bars][5] = float(y[5])\r\n\r\n if (len(x) < self.max_bars):\r\n #rates = np.sort(rates)\r\n rates = np.sort(rates[rates[:]['date']!=0])\r\n self.command_OK = True\r\n if (self.invert_array == True):\r\n rates = np.flipud(rates)\r\n return rates\r\n\r\n if (itail == 0):\r\n #rates = np.sort(rates)\r\n rates = np.sort(rates[rates[:]['date']!=0])\r\n self.command_OK = True\r\n if (self.invert_array == True):\r\n rates = np.flipud(rates)\r\n return rates\r\n\r\n if (itail > 0):\r\n self.command = 'F142#5#' + self.get_broker_instrument_name(self.instrument_name_universal) + '#' + str(brick_code) + '#' + \\\r\n str(iloop * self.max_bars) + '#' + str(itail) + '#' + str(nbrofbars) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n if self.debug:\r\n print(dataString)\r\n print('')\r\n print(len(dataString))\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F042':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return None\r\n\r\n del x[0:2]\r\n x.pop(-1)\r\n\r\n for value in range(0, len(x)):\r\n y = x[value].split('$')\r\n\r\n rates[value + iloop * self.max_bars][0] = int(y[0])\r\n rates[value + iloop * self.max_bars][1] = float(y[1])\r\n rates[value + iloop * self.max_bars][2] = float(y[2])\r\n rates[value + iloop * self.max_bars][3] = float(y[3])\r\n rates[value + iloop * self.max_bars][4] = float(y[4])\r\n rates[value + iloop * self.max_bars][5] = float(y[5])\r\n\r\n self.command_OK = True\r\n #rates = np.sort(rates)\r\n rates = np.sort(rates[rates[:]['date']!=0])\r\n if (self.invert_array == True):\r\n rates = np.flipud(rates)\r\n return rates\r\n else:\r\n self.command = 'F142#4#' + str(self.get_broker_instrument_name(self.instrument_name_universal)) + '#' + str(brick_code) + \"#\" + \\\r\n str(0) + '#' + str(self.numberofbars) + '#' + str(nbrofbars) + '#'\r\n #print(self.command)\r\n ok, dataString = self.send_command(self.command)\r\n if not ok:\r\n self.command_OK = False\r\n print('not ok')\r\n return None\r\n if self.debug:\r\n print(dataString)\r\n print('')\r\n print(len(dataString))\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F142':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return None\r\n\r\n del x[0:2]\r\n x.pop(-1)\r\n\r\n for value in range(0, len(x)):\r\n y = x[value].split('$')\r\n\r\n rates[value][0] = int(y[0])\r\n rates[value][1] = float(y[1])\r\n rates[value][2] = float(y[2])\r\n rates[value][3] = float(y[3])\r\n rates[value][4] = float(y[4])\r\n rates[value][5] = float(y[5])\r\n\r\n self.command_OK = True\r\n rates = np.sort(rates[rates[:]['date']!=0])\r\n if (self.invert_array == True):\r\n rates = np.flipud(rates)\r\n return rates\r\n\r\n def Get_amount_of_renko_bars(self,\r\n instrument: str = 'EURUSD',\r\n brick_code: str = 'B1') -> int:\r\n \r\n \"\"\"\r\n retrieves last number of renko bars for specifies instrument and brick code/size\r\n\r\n Args:\r\n instrument: name of instrument like EURUSD\r\n brick_code: should be \"B1\", \"B2\" or \"B3\"\r\n\r\n Returns: int amount of bars:\r\n \"\"\"\r\n \r\n if (brick_code in ['B1', 'B2', 'B3'] == False):\r\n self.command_return_error = str(ERROR_DICT['15102'])\r\n self.command_OK = False\r\n return -1\r\n \r\n self.command_return_error = ''\r\n self.instrument_name_universal = instrument.upper()\r\n self.instrument = self.get_broker_instrument_name(self.instrument_name_universal)\r\n\r\n self.command = 'F151#2#' + str(self.instrument) + '#' + str(brick_code) + '#'\r\n\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if not ok:\r\n self.command_OK = False\r\n return -1\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if x[0] != 'F151':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return -1\r\n\r\n return int(x[3])\r\n\r\n def Get_last_tick_info(self,\r\n instrument: str = 'EURUSD') -> dict:\r\n \"\"\"\r\n Retrieves instrument last tick data.\r\n Backtester bid and ask are same. \r\n All data are the last M1 bar\r\n\r\n Args:\r\n instrument: instrument name\r\n Returns: Dictionary with:\r\n instrument name,\r\n date,\r\n ask,\r\n bid,\r\n last,\r\n volume,\r\n spread\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.instrument_name_universal = instrument.upper()\r\n self.instrument = self.get_broker_instrument_name(self.instrument_name_universal)\r\n if (self.instrument == 'none'):\r\n self.command_return_error = 'Instrument not in list'\r\n self.command_OK = False\r\n return None\r\n ok, dataString = self.send_command('F020#1#' + self.instrument + '#')\r\n\r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if x[0] != 'F020':\r\n self.command_return_error =ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return None\r\n\r\n returnDict = {}\r\n del x[0:2]\r\n x.pop(-1)\r\n\r\n returnDict['instrument'] = str(self.instrument_name_universal)\r\n returnDict['date'] = int(x[0])\r\n returnDict['ask'] = float(x[1])\r\n returnDict['bid'] = float(x[2])\r\n returnDict['last'] = float(x[3])\r\n returnDict['volume'] = int(x[4])\r\n returnDict['spread'] = float(x[5])\r\n\r\n self.command_OK = True\r\n return returnDict\r\n\r\n def Get_specific_bar(self,\r\n instrument_list: list = ['EURUSD', 'GBPUSD'],\r\n specific_bar_index: int = 1,\r\n timeframe: int = 16408) -> dict:\r\n \"\"\"\r\n Retrieves instrument data(d, o, h, l, c, v) of one bar(index) for the instruments in the list.\r\n Args:\r\n instrument_list: instrument list\r\n specific_bar_index: the specific bar (0 = actual bar)\r\n timeframe: time frame like H1, H4\r\n Returns: Dictionary with: {instrument:{instrument data}}\r\n instrument name,\r\n [date,\r\n open,\r\n high,\r\n low,\r\n close,\r\n volume]\r\n \"\"\"\r\n self.command_return_error = ''\r\n # compose MT5 command string\r\n self.command = 'F045#3#'\r\n for index in range (0, len(instrument_list), 1):\r\n _instr = self.get_broker_instrument_name(instrument_list[index].upper())\r\n self.command = self.command + _instr + '$'\r\n \r\n self.command = self.command + '#' + str(specific_bar_index) + '#' + str(timeframe) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F045':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return None\r\n\r\n del x[0:2]\r\n x.pop(-1)\r\n result = {}\r\n \r\n for value in range(0, len(x)):\r\n y = x[value].split('$')\r\n symbol_result = {}\r\n symbol = str(y[0])\r\n symbol_result['date'] = int(y[1])\r\n symbol_result['open'] = float(y[2])\r\n symbol_result['high'] = float(y[3])\r\n symbol_result['low'] = float(y[4])\r\n symbol_result['close'] = float(y[5])\r\n symbol_result['volume'] = float(y[6])\r\n result[symbol] = symbol_result\r\n \r\n return result \r\n\r\n def Get_specific_renko_bar(self,\r\n instrument_list: list = ['EURUSD', 'GBPUSD'],\r\n specific_bar_index: int = 1,\r\n brick_code: str = 'B1') -> dict:\r\n \"\"\"\r\n Retrieves instrument data(d, o, h, l, c, v) of one bar(index) for the instruments in the list.\r\n Args:\r\n instrument_list: instrument list\r\n specific_bar_index: the specific bar (0 = actual bar)\r\n timeframe: brick code valid value B1, B2 and B3\r\n Returns: Dictionary with: {instrument:{instrument data}}\r\n instrument name,\r\n [date,\r\n open,\r\n high,\r\n low,\r\n close,\r\n volume]\r\n \"\"\"\r\n self.command_return_error = ''\r\n # compose MT5 command string\r\n self.command = 'F145#3#'\r\n for index in range (0, len(instrument_list), 1):\r\n _instr = self.get_broker_instrument_name(instrument_list[index].upper())\r\n self.command = self.command + _instr + '$'\r\n \r\n self.command = self.command + '#' + str(specific_bar_index) + '#' + str(brick_code) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n\r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F145':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return None\r\n\r\n del x[0:2]\r\n x.pop(-1)\r\n result = {}\r\n \r\n for value in range(0, len(x)):\r\n y = x[value].split('$')\r\n symbol_result = {}\r\n symbol = str(y[0])\r\n symbol_result['date'] = int(y[1])\r\n symbol_result['open'] = float(y[2])\r\n symbol_result['high'] = float(y[3])\r\n symbol_result['low'] = float(y[4])\r\n symbol_result['close'] = float(y[5])\r\n symbol_result['volume'] = float(y[6])\r\n result[symbol] = symbol_result\r\n \r\n return result \r\n\r\n def Get_all_orders(self) -> pd.DataFrame:\r\n \"\"\"\r\n retrieves all pending orders.\r\n Args:\r\n\r\n Returns:\r\n data array(panda) with all order information:\r\n ticket,\r\n instrument,\r\n order_type,\r\n magic number,\r\n volume/lotsize,\r\n open price,\r\n stopp_loss,\r\n take_profit,\r\n comment\r\n \"\"\"\r\n self.command = 'F060#0#'\r\n ok, dataString = self.send_command(self.command)\r\n \r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n orders = self.create_empty_DataFrame(self.columnsOpenOrders, 'id')\r\n x = dataString.split('#')\r\n \r\n '''\r\n if str(x[0]) != 'F060':\r\n self.command_return_error = str(x[2])\r\n self.command_OK = False\r\n return None \r\n '''\r\n\r\n del x[0:2]\r\n x.pop(-1)\r\n\r\n for value in range(0, len(x)):\r\n y = x[value].split('$')\r\n\r\n rowOrders = pd.Series({\r\n 'ticket': int( y[0]), 'instrument': self.get_universal_instrument_name(str(y[1])), 'order_type': str(y[2]), 'magic_number': int(y[3]), \r\n 'volume': float( y[4]), 'open_price': float( y[5]), 'open_time': int(y[6]), 'stop_loss': float( y[7]), 'take_profit': float( y[8]), 'comment': str(y[9])})\r\n orders = orders.append(rowOrders, ignore_index=True)\r\n\r\n self.command_OK = True\r\n return orders\r\n\r\n def Get_all_open_positions(self) -> pd.DataFrame:\r\n \"\"\"\r\n retrieves all open positions.\r\n Args:\r\n\r\n Returns:\r\n data array(panda) with all position information:\r\n ticket,\r\n instrument,\r\n position_type,\r\n magic_number,\r\n volume/lotsize,\r\n open_price,\r\n open_time,\r\n stopp_loss,\r\n take_profit,\r\n comment,\r\n profit,\r\n swap,\r\n commission\r\n dd_min\r\n dd_plus\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.command = 'F061#0#'\r\n ok, dataString = self.send_command(self.command)\r\n \r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n positions = self.create_empty_DataFrame(\r\n self.columnsOpenPositions, 'id')\r\n x = dataString.split('#')\r\n\r\n '''\r\n if (str(x[0]) != 'F061'):\r\n self.command_return_error = str(x[2])\r\n self.command_OK = False\r\n return None\r\n '''\r\n\r\n del x[0:2]\r\n x.pop(-1)\r\n\r\n for value in range(0, len(x)):\r\n y = x[value].split('$')\r\n\r\n rowPositions = pd.Series(\r\n {\r\n 'ticket': int( y[0]), 'instrument': self.get_universal_instrument_name( (y[1])), 'position_type': str( y[2]), \r\n 'magic_number': int(y[3]), 'volume': float( y[4]), 'open_price': float( y[5]), 'open_time': int(y[6]),\r\n 'stop_loss': float( y[7]), 'take_profit': float( y[8]), 'comment': str( y[9]), 'profit': float( y[10]), \r\n 'swap': float( y[11]), 'commission': float( y[12]), 'dd_min': float(y[13]), 'dd_plus': float(y[14])})\r\n positions = positions.append(rowPositions, ignore_index=True)\r\n\r\n self.command_OK = True\r\n return positions\r\n\r\n def Get_all_closed_positions(self\r\n ):\r\n \"\"\"\r\n retrieves all closed positions/orders.\r\n Args:\r\n None\r\n Returns:\r\n data array(panda) with all position information:\r\n position ticket,\r\n instrument,\r\n order_ticket,\r\n position_type,\r\n magic number,\r\n volume/lotsize,\r\n open price,\r\n open time,\r\n close_price,\r\n close_time,\r\n comment,\r\n profit,\r\n swap,\r\n commission,\r\n open_log,\r\n close_log,\r\n dd_min,\r\n dd_plus\r\n \"\"\"\r\n self.command_return_error = ''\r\n\r\n self.command = 'F062#0#'\r\n ok, dataString = self.send_command(self.command)\r\n \r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n closed_positions = self.create_empty_DataFrame(\r\n self.columnsClosedPositions, 'id')\r\n x = dataString.split('#')\r\n\r\n '''\r\n if str(x[0]) != 'F062':\r\n self.command_return_error = str(x[2])\r\n self.command_OK = False\r\n return None\r\n '''\r\n\r\n del x[0:2]\r\n x.pop(-1)\r\n for value in range(0, len(x)):\r\n y = x[value].split('$')\r\n rowClosedPositions = pd.Series(\r\n {\r\n 'position_ticket': int(y[0]), 'instrument': self.get_universal_instrument_name(str( y[1])), 'order_ticket': int( y[2]), \r\n 'position_type': str( y[3]), 'magic_number': int( y[4]), 'volume': float( y[5]), 'open_price': float( y[6]), \r\n 'open_time': int( y[7]), 'close_price': float(y[8]), 'close_time': int( y[9]), 'sl': float(y[10]), 'tp': float(y[11]), 'comment': str( y[12]), \r\n 'profit': float( y[13]), 'swap': float( y[14]), 'commission': float( y[15]), 'open_log': str(y[16]), 'close_log': str(y[17]),\r\n 'dd_min': float(y[18]), 'dd_plus': float(y[19])})\r\n closed_positions = closed_positions.append(rowClosedPositions, ignore_index=True)\r\n\r\n return closed_positions\r\n\r\n def Get_last_x_closed_positions(self, \r\n amount: int = 3\r\n ):\r\n \"\"\"\r\n Retrieves last X closed positions.\r\n Args:\r\n amount: number of positions\r\n Returns:\r\n data array(panda) with all position information:\r\n position ticket,\r\n instrument,\r\n order_ticket,\r\n position_type,\r\n magic number,\r\n volume/lotsize,\r\n open price,\r\n open time,\r\n close_price,\r\n close_time,\r\n comment,\r\n profit,\r\n swap,\r\n commission,\r\n position open comment,\r\n position close comment\r\n dd_min\r\n dd_plus\r\n \"\"\"\r\n self.command_return_error = ''\r\n\r\n self.command = 'F063#1#' + str(amount) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n \r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n closed_positions = self.create_empty_DataFrame(\r\n self.columnsClosedPositions, 'id')\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F063':\r\n self.command_return_error = str(x[2])\r\n self.command_OK = False\r\n return None\r\n \r\n if (int(x[1]) == 0):\r\n return closed_positions\r\n \r\n del x[0:2]\r\n x.pop(-1)\r\n for value in range(0, len(x)):\r\n y = x[value].split('$')\r\n rowClosedPositions = pd.Series(\r\n {\r\n 'position_ticket': int(y[0]), 'instrument': self.get_universal_instrument_name(str( y[1])), 'order_ticket': int( y[2]), \r\n 'position_type': str( y[3]), 'magic_number': int( y[4]), 'volume': float( y[5]), 'open_price': float( y[6]), \r\n 'open_time': int( y[7]), 'close_price': float(y[8]), 'close_time': int( y[9]), 'sl': float(y[10]), 'tp': float(y[11]), 'comment': str( y[12]), \r\n 'profit': float( y[13]), 'swap': float( y[14]), 'commission': float( y[15]), 'open_log': str(y[16]), 'close_log': str(y[17]),\r\n 'dd_min': float(y[18]), 'dd_plus': float(y[19])})\r\n closed_positions = closed_positions.append(\r\n rowClosedPositions, ignore_index=True)\r\n\r\n return closed_positions\r\n\r\n def Open_order(self,\r\n instrument: str = '',\r\n ordertype: str = 'buy',\r\n volume: float = 0.01,\r\n openprice: float = 0.0,\r\n slippage: int = 5,\r\n magicnumber: int = 0,\r\n stoploss: float = 0.0,\r\n takeprofit: float = 0.0,\r\n comment: str = '',\r\n open_log: str = ''\r\n ) -> int:\r\n \"\"\"\r\n Open an order.\r\n Args:\r\n instrument: instrument\r\n ordertype: type of order, buy, sell, buy stop, sell stop, buy limit, sell limit\r\n volume: order volume/lot size\r\n open price: open price for order, 0.0 for market orders\r\n slippage: allowed slippage\r\n magicnumber: magic number for this order\r\n stoploss: order stop loss price, actual price, so not relative to open price\r\n takeprofit: order take profit, actual price, so not relative to open price\r\n comment: order comment\r\n open_log: additional comment for opening the order\r\n Returns:\r\n int: ticket number. If -1, open order failed\r\n \"\"\"\r\n\r\n self.command_return_error = ''\r\n self.instrument_name_universal = instrument.upper()\r\n # check the command for '#' , '$', '!' character\r\n # these are not allowed, used as delimiters\r\n comment.replace('#', '')\r\n comment.replace('$', '')\r\n comment.replace('!', '')\r\n self.command = 'F070#10#' + self.get_broker_instrument_name(self.instrument_name_universal) + '#' + ordertype + '#' + str(volume) + '#' + \\\r\n str(openprice) + '#' + str(slippage) + '#' + str(magicnumber) + '#' + str(stoploss) + '#' + str(takeprofit) + '#' + str(comment) + '#' + str(open_log) + \"#\"\r\n #print(self.command)\r\n ok, dataString = self.send_command(self.command)\r\n \r\n if not ok:\r\n self.command_OK = False\r\n return int(-1)\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F070':\r\n self.command_return_error = str(x[2])\r\n self.command_OK = False\r\n self.order_return_message = str(x[2])\r\n self.order_error = int(x[3])\r\n return int(-1)\r\n\r\n self.command_OK = True\r\n self.order_return_message = str(x[2])\r\n return int(x[3])\r\n\r\n def Close_position_by_ticket(self,\r\n ticket: int = 0,\r\n close_log: str = '') -> bool:\r\n \"\"\"\r\n Close a position.\r\n Args:\r\n ticket: ticket of position to close\r\n close_log: reason for closing position\r\n\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.command = 'F071#2#' + str(ticket) + '#' + str(close_log) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n \r\n if not ok:\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n '''\r\n if str(x[0]) != 'F071':\r\n self.command_return_error = str(x[2])\r\n self.command_OK = False\r\n self.order_return_message = str(x[2])\r\n self.order_error = str(x[3])\r\n return False\r\n '''\r\n if str(x[2]) == 'OK':\r\n self.command_OK = True\r\n self.order_return_message = ''\r\n return True\r\n elif str(x[2]) == 'NOK':\r\n self.command_OK = True\r\n self.order_return_message = ERROR_DICT[str(x[3])]\r\n return False\r\n \r\n return False \r\n\r\n def Delete_order_by_ticket(self,\r\n ticket: int = 0) -> bool:\r\n \"\"\"\r\n Delete an order.\r\n Args:\r\n ticket: ticket of order(pending) to delete\r\n\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.command = 'F073#1#' + str(ticket) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n \r\n if not ok:\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n \r\n if str(x[2]) == 'OK':\r\n self.command_OK = True\r\n self.order_return_message = ''\r\n return True\r\n elif str(x[2]) == 'NOK':\r\n self.command_OK = True\r\n self.order_return_message = ERROR_DICT[str(x[3])]\r\n return False\r\n return False \r\n\r\n def Set_sl_and_tp_for_position(self,\r\n ticket: int = 0,\r\n stoploss: float = 0.0,\r\n takeprofit: float = 0.0) -> bool:\r\n \"\"\"\r\n Change stop loss and take profit for a position.\r\n Args:\r\n ticket: ticket of position to change\r\n stoploss; new stop loss value, must be actual price value\r\n takeprofit: new take profit value, must be actual price value\r\n\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.command = 'F075#3#' + \\\r\n str(ticket) + '#' + str(stoploss) + '#' + str(takeprofit) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n \r\n if not ok:\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F075':\r\n self.command_OK = False\r\n self.order_return_message = ERROR_DICT[str(x[3])]\r\n return False\r\n\r\n self.command_OK = True\r\n return True\r\n\r\n def Set_sl_and_tp_for_order(self,\r\n ticket: int = 0,\r\n stoploss: float = 0.0,\r\n takeprofit: float = 0.0) -> bool:\r\n \"\"\"\r\n Change stop loss and take profit for an order.\r\n Args:\r\n ticket: ticket of order to change\r\n stoploss; new stop loss value, must be actual price value\r\n takeprofit: new take profit value, must be actual price value\r\n\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.command = 'F076#3#' + \\\r\n str(ticket) + '#' + str(stoploss) + '#' + str(takeprofit) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n \r\n if not ok:\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F076':\r\n self.command_OK = False\r\n self.order_return_message = ERROR_DICT[str(x[3])]\r\n return False\r\n\r\n self.command_OK = True\r\n return True\r\n\r\n def Reset_sl_and_tp_for_position(self,\r\n ticket: int = 0) -> bool:\r\n \"\"\"\r\n Reset stop loss and take profit for a position.\r\n Args:\r\n ticket: ticket of position to change\r\n\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.command = 'F077#1#' + str(ticket) + '#' \r\n ok, dataString = self.send_command(self.command)\r\n \r\n if not ok:\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F077':\r\n self.command_OK = False\r\n self.order_return_message = ERROR_DICT[str(x[3])]\r\n return False\r\n\r\n self.command_OK = True\r\n return True\r\n\r\n def Reset_sl_and_tp_for_order(self,\r\n ticket: int = 0) -> bool:\r\n \"\"\"\r\n Reset stop loss and take profit for an order.\r\n Args:\r\n ticket: ticket of order to change\r\n\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.command = 'F078#1#' + str(ticket) + '#'\r\n ok, dataString = self.send_command(self.command)\r\n \r\n if not ok:\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F078':\r\n self.command_OK = False\r\n self.order_return_message = ERROR_DICT[str(x[3])]\r\n return False\r\n\r\n self.command_OK = True\r\n return True\r\n\r\n def Reset_order_lists(self) -> bool:\r\n \r\n \"\"\"\r\n Reset orders lists for speed, only effective for big history of trades\r\n\r\n Returns:\r\n bool: True or False\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.command = 'F080#1#'\r\n ok, dataString = self.send_command(self.command)\r\n \r\n if not ok:\r\n self.command_OK = False\r\n return False\r\n\r\n if self.debug:\r\n print(dataString)\r\n\r\n x = dataString.split('#')\r\n if str(x[0]) != 'F080':\r\n self.command_return_error = str(x[2])\r\n self.command_OK = False\r\n self.order_return_message = str(x[2])\r\n return False\r\n\r\n return True\r\n\r\n def Get_datafactory_info(self,\r\n instrument: str = \"EURUSD\") -> dict:\r\n\r\n \"\"\"\r\n Retrieve data factory info\r\n\r\n Args:\r\n instrument: instrument name\r\n Returns: Dictionary with\r\n instrument\r\n number_of_bars (M1)\r\n start_date\r\n end_date\r\n \"\"\"\r\n self.command_return_error = ''\r\n self.instrument_name_universal = instrument.upper()\r\n self.instrument = self.get_broker_instrument_name(self.instrument_name_universal)\r\n self.command = \"F501#1#\" + self.instrument + \"#\"\r\n\r\n ok, dataString = self.send_command(self.command)\r\n if not ok:\r\n self.command_OK = False\r\n return None\r\n\r\n if self.debug:\r\n print(dataString)\r\n \r\n returnDict = {}\r\n x = dataString.split('#')\r\n if x[0] != 'F501':\r\n self.command_return_error = ERROR_DICT[str(x[3])]\r\n self.command_OK = False\r\n return None\r\n \r\n del x[0:2]\r\n x.pop(-1)\r\n returnDict['instrument'] = str(x[0])\r\n returnDict['number_of_bars'] = int(x[1])\r\n returnDict['start_date'] = datetime.fromtimestamp(int(x[2]))\r\n returnDict['end_date'] = datetime.fromtimestamp(int(x[3]))\r\n\r\n return returnDict\r\n\r\n def send_command(self,\r\n command):\r\n self.command = command + \"!\"\r\n self.timeout = False\r\n #self.sock.send(bytes(self.command, \"utf-8\"))\r\n if (self.connected == False):\r\n return False, None\r\n \r\n try:\r\n data_received = ''\r\n self.sock.send(bytes(self.command, \"utf-8\"))\r\n while True:\r\n data_received = data_received + self.sock.recv(500000).decode()\r\n if data_received.endswith('!'):\r\n break\r\n return True, data_received\r\n except socket.timeout as msg:\r\n self.timeout = True\r\n print(msg)\r\n return False, None\r\n \r\n def get_timeframe_value(self,\r\n timeframe: str = 'D1') -> int:\r\n\r\n self.tf = 16408 # mt5.TIMEFRAME_D1\r\n timeframe.upper()\r\n if timeframe == 'MN1':\r\n self.tf = 49153 # mt5.TIMEFRAME_MN1\r\n if timeframe == 'W1':\r\n self.tf = 32769 # mt5.TIMEFRAME_W1\r\n if timeframe == 'D1':\r\n self.tf = 16408 # mt5.TIMEFRAME_D1\r\n if timeframe == 'H12':\r\n self.tf = 16396 # mt5.TIMEFRAME_H12\r\n if timeframe == 'H8':\r\n self.tf = 16392 # mt5.TIMEFRAME_H8\r\n if timeframe == 'H6':\r\n self.tf = 16390 # mt5.TIMEFRAME_H6\r\n if timeframe == 'H4':\r\n self.tf = 16388 # mt5.TIMEFRAME_H4\r\n if timeframe == 'H3':\r\n self.tf = 16387 # mt5.TIMEFRAME_H3\r\n if timeframe == 'H2':\r\n self.tf = 16386 # mt5.TIMEFRAME_H2\r\n if timeframe == 'H1':\r\n self.tf = 16385 # mt5.TIMEFRAME_H1\r\n if timeframe == 'M30':\r\n self.tf = 30 # mt5.TIMEFRAME_M30\r\n if timeframe == 'M20':\r\n self.tf = 20 # mt5.TIMEFRAME_M20\r\n if timeframe == 'M15':\r\n self.tf = 15 # mt5.TIMEFRAME_M15\r\n if timeframe == 'M10':\r\n self.tf = 10 # mt5.TIMEFRAME_M10\r\n if timeframe == 'M5':\r\n self.tf = 5 # mt5.TIMEFRAME_M5\r\n if timeframe == 'M1':\r\n self.tf = 1 # mt5.TIMEFRAME_M1\r\n\r\n return self.tf\r\n\r\n def get_broker_instrument_name(self,\r\n instrumentname: str = '') -> str:\r\n self.intrumentname = instrumentname\r\n try:\r\n # str result =\r\n # (string)self.instrument_conversion_list.get(str(instrumentname))\r\n return self.instrument_conversion_list.get(str(instrumentname))\r\n except BaseException:\r\n return 'none'\r\n\r\n def get_universal_instrument_name(self,\r\n instrumentname: str = '') -> str:\r\n self.instrumentname = instrumentname\r\n try:\r\n for item in self.instrument_conversion_list:\r\n key = str(item)\r\n value = self.instrument_conversion_list.get(item)\r\n if (value == instrumentname):\r\n return str(key)\r\n except BaseException:\r\n return 'none'\r\n return 'none'\r\n\r\n def create_empty_DataFrame(self,\r\n columns, index_col) -> pd.DataFrame:\r\n index_type = next((t for name, t in columns if name == index_col))\r\n df = pd.DataFrame({name: pd.Series(dtype=t) for name,\r\n t in columns if name != index_col},\r\n index=pd.Index([],\r\n dtype=index_type))\r\n cols = [name for name, _ in columns]\r\n cols.remove(index_col)\r\n return df[cols]\r\n\r\n columnsOpenOrders = [\r\n ('id', int),\r\n ('ticket', int),\r\n ('instrument', str),\r\n ('order_type', str),\r\n ('magic_number', int),\r\n ('volume', float),\r\n ('open_price', float),\r\n ('open_time', int),\r\n ('stop_loss', float),\r\n ('take_profit', float),\r\n ('comment', str)]\r\n\r\n columnsOpenPositions = [\r\n ('id', int),\r\n ('ticket', int),\r\n ('instrument', str),\r\n ('position_type', str),\r\n ('magic_number', int),\r\n ('volume', float),\r\n ('open_price', float),\r\n ('open_time', int),\r\n ('stop_loss', float),\r\n ('take_profit', float),\r\n ('comment', str),\r\n ('profit', float),\r\n ('swap', float),\r\n ('commission', float),\r\n ('dd_min', float),\r\n ('dd_plus', float)]\r\n\r\n columnsClosedPositions = [\r\n ('id', int),\r\n ('position_ticket', int),\r\n ('instrument', str),\r\n ('order_ticket', int),\r\n ('position_type', str),\r\n ('magic_number', int),\r\n ('volume', float),\r\n ('open_price', float),\r\n ('open_time', int),\r\n ('close_price', float),\r\n ('close_time', int),\r\n ('sl', float),\r\n ('tp', float),\r\n ('comment', str),\r\n ('profit', float),\r\n ('swap', float),\r\n ('commission', float),\r\n ('open_log', str),\r\n ('close_log', str),\r\n ('dd_min', float),\r\n ('dd_plus', float)]\r\n\r\n","sub_path":"Pytrader_BT_API_V1_02.py","file_name":"Pytrader_BT_API_V1_02.py","file_ext":"py","file_size_in_byte":80171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"562926454","text":"import gpio_device, locomotion_device\nfrom time import sleep\n\nclass Simulation:\n def __init__(self):\n # variable_name: value\n self.simulation_variables = {}\n\n # variable_name: (id, function, device instance, parameter)\n # Function takes 1 variable: new value of variable\n self.listeners = {}\n\n # variable_name: (id, function, device_instance)\n # Function returns 1 variable: value of of the variable\n self.updaters = {}\n\n self.next_id = 1\n\n def get_variable(self, variable_name):\n return self.simulation_variables[variable_name]\n\n\n def register_variable(self, variable_name):\n if variable_name not in self.simulation_variables:\n self.simulation_variables[variable_name] = 0\n self.listeners[variable_name] = []\n self.updaters[variable_name] = []\n\n def register_listener(self, variable_name, function, device_instance, parameter):\n if variable_name in self.simulation_variables:\n self.listeners[variable_name].append((self.next_id, function, device_instance, parameter))\n self.next_id += 1\n return self.next_id - 1\n return 0\n\n\n def register_updater(self, variable_name, function, device_instance, parameter):\n if variable_name in self.simulation_variables:\n self.updaters[variable_name].append((self.next_id, function, device_instance, parameter))\n self.next_id += 1\n return self.next_id - 1\n return 0\n\n\n def delete_registration(self, registration_id):\n for key in self.listeners.keys():\n for j in range(len(self.listeners[key])):\n function_id, _, _, _ = self.listeners[key][j]\n if function_id == registration_id:\n del self.listeners[key][j]\n\n for key in self.updaters.keys():\n for j in range(len(self.updaters[key])):\n function_id, _, _, _ = self.updaters[key][j]\n if function_id == registration_id:\n del self.updaters[key][j] \n\n\ndef main():\n sim = Simulation()\n ###### Load Devices #######\n pi = gpio_device.GpioDevice(sim)\n bot = locomotion_device.LocomotionDevice(sim)\n #### End Load Devices #####\n \n while True:\n for var, val in sim.simulation_variables.items():\n updated = False\n for _, function, device_instance, parameter in sim.updaters[var]:\n new_val = function(parameter)\n if new_val != val:\n sim.simulation_variables[var] = new_val\n updated = True\n break\n for _, function, device_instance, parameter in sim.listeners[var]:\n function(parameter)\n\nif __name__ == '__main__':\n main()\n","sub_path":"sim.py","file_name":"sim.py","file_ext":"py","file_size_in_byte":2818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"438413670","text":"import pandas as pd\nimport numpy as np\nimport scipy.stats\n\ndata = pd.read_csv('testdata.csv',header=None)\ndata = data.iloc[:].values\n\nmean = []\nfor i in range(0,100):\n mean.append(np.average(data[i]))\nstd = []\nfor i in range(0,100):\n std.append(np.std(data[i]))\nskew = []\nfor i in range(0,100):\n skew.append(scipy.stats.skew(data[i]))\nkurtosis = []\nfor i in range(0,100):\n kurtosis.append(scipy.stats.kurtosis(data[i]))\n\nprint(mean[99])\nprint(kurtosis[99])\nprint(std[99])\nprint(skew[99])\n\nnp.savetxt(\"Mean.csv\", mean, delimiter=\",\")\nnp.savetxt(\"STD.csv\", std, delimiter=\",\")\nnp.savetxt(\"Skew.csv\", skew, delimiter=\",\")\nnp.savetxt(\"Kurtosis.csv\", kurtosis, delimiter=\",\")","sub_path":"analysis/MLP Classifier/Archived/Regression/Utils/datagen.py","file_name":"datagen.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"275217749","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# __author__ = 'TesterCC'\n# __time__ = '17/8/21 23:16'\n\n\nimport xadmin\n\nfrom .models import CityDict, CourseOrg, Teacher\n\n\nclass CityDictAdmin(object):\n\n list_display = ['name', 'desc', 'add_time']\n\n search_fields = ['name', 'desc']\n\n list_filter = ['name', 'desc', 'add_time']\n\n\nclass CourseOrgAdmin(object):\n\n list_display = ['name', 'desc', 'click_nums', 'fav_nums', 'image', 'address', 'city', 'add_time']\n\n search_fields = ['name', 'desc', 'click_nums', 'fav_nums', 'image', 'address', 'city__name']\n\n list_filter = ['name', 'desc', 'click_nums', 'fav_nums', 'image', 'address', 'city', 'add_time']\n\n # 下拉式改为搜索式,需要改外键的获取方式,不然会有外键查询bug,因为外键查询是需要指定相应的字段的\n relfield_style = 'fk-ajax'\n\n\nclass TeacherAdmin(object):\n\n list_display = ['org', 'name', 'work_years', 'work_company', 'work_position', 'points', 'click_nums', 'add_time']\n\n search_fields = ['org', 'name', 'work_years', 'work_company', 'work_position', 'points', 'click_nums']\n\n list_filter = ['org', 'name', 'work_years', 'work_company', 'work_position', 'points', 'click_nums', 'add_time']\n\n\n# register models in xadmin\nxadmin.site.register(CityDict, CityDictAdmin)\nxadmin.site.register(CourseOrg, CourseOrgAdmin)\nxadmin.site.register(Teacher, TeacherAdmin)","sub_path":"apps/organization/adminx.py","file_name":"adminx.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"453446910","text":"\"\"\"\r\nAuthor: Heidi Dye\r\nDate: \r\nVersion: 1.0\r\nPurpose: Convolutional Neural Network with the MNIST Dataset\r\n\"\"\"\r\n\r\n\r\nimport torch\r\nimport torchvision\r\nimport torchvision.transforms as transforms\r\nfrom torchvision import datasets\r\nfrom torch.utils.data import DataLoader\r\nimport torch.nn as nn\r\nimport torch.nn.functional as functional\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n\r\n\r\n\r\n#--------------------------------------#\r\n# CREATE THE MODEL #\r\n#--------------------------------------#\r\n\r\n#Get cpu or gpu device for training\r\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\r\n#device = \"cpu\"\r\nprint(\"Using {} device\".format(device))\r\n\r\n#define the model\r\nclass CNN(nn.Module):\r\n def __init__(self):\r\n super().__init__()\r\n self.conv1 = nn.Conv2d(1, 4, 5)\r\n self.pool = nn.MaxPool2d(2, 2)\r\n self.conv2 = nn.Conv2d(4, 12, 5)\r\n self.layer1 = nn.Linear(192, 250)\r\n self.layer2 = nn.Linear(250, 100)\r\n self.layer3 = nn.Linear(100, 10)\r\n\r\n def forward(self, x):\r\n x = self.pool(functional.relu(self.conv1(x)))\r\n #print(x.shape)\r\n x = self.pool(functional.relu(self.conv2(x)))\r\n #print(x.shape)\r\n #flatten all dimensions except the batch\r\n x = torch.flatten(x, 1)\r\n #print(x.shape)\r\n x = functional.relu(self.layer1(x))\r\n #print(x.shape)\r\n x = functional.relu(self.layer2(x))\r\n #print(x.shape)\r\n x = self.layer3(x)\r\n #print(x.shape)\r\n return x\r\n \r\n\r\n\r\n#-----------------------------#\r\n# GET THE DATASET #\r\n#-----------------------------#\r\n\r\n#transform to tensors from range [0, 1] to a normalized range of [-1, 1]\r\ntransform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5), (0.5))])\r\n\r\n#Download the training data from the open MNIST Dataset\r\ntraining_data = datasets.MNIST(\r\n root = \"data\",\r\n train = True,\r\n download = True,\r\n transform = transform\r\n )\r\n\r\n#Download the test data from the open MNIST Dataset\r\ntest_data = datasets.MNIST(\r\n root = \"data\",\r\n train = False,\r\n download = True,\r\n transform = transform\r\n )\r\n\r\nbatch_size = 4\r\n\r\n#Create data loaders\r\ntrain_dataloader = DataLoader(training_data, batch_size=batch_size, shuffle=True, num_workers=0)\r\ntest_dataloader = DataLoader(test_data, batch_size=batch_size, shuffle=False, num_workers=0)\r\n\r\n#tuple for the possible classifcations for image output\r\nclasses = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')\r\n\r\n\r\n#------------------------------------#\r\n# SHOW THE IMAGES #\r\n#------------------------------------#\r\n\r\ndef showImage(img):\r\n #unnormalize\r\n img = img/2 + 0.5\r\n img = img.numpy()\r\n plt.imshow(np.transpose(img, (1, 2, 0)))\r\n plt.show()\r\n \r\ndataiter = iter(train_dataloader)\r\nimages, labels = dataiter.next()\r\n\r\n#show images\r\nshowImage(torchvision.utils.make_grid(images))\r\n#print labels\r\nprint(' '.join('%5s' % classes[labels[j]] for j in range(batch_size)))\r\n\r\n\r\n#---------------------------------#\r\n# TRAIN AND TEST #\r\n#---------------------------------#\r\n\r\ndef train(dataloader, model, loss_fn, optimizer, device):\r\n running_loss = 0.0\r\n for batch, (inputs, labels) in enumerate(dataloader):\r\n # get the inputs; data is a list of [inputs, labels]\r\n inputs, labels = inputs.to(device), labels.to(device)\r\n\r\n # zero the parameter gradients\r\n optimizer.zero_grad()\r\n\r\n # forward + backward + optimize\r\n outputs = model(inputs)\r\n loss = loss_fn(outputs, labels)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n # print statistics\r\n running_loss += loss.item()\r\n if batch % 2000 == 1999: # print every 2000 mini-batches\r\n print('loss: %.3f' %(running_loss / 2000))\r\n running_loss = 0.0\r\n \r\n\r\ndef test(dataloader, model, loss_fn, device):\r\n size = len(dataloader.dataset)\r\n num_batches = len(dataloader)\r\n model.eval()\r\n test_loss, correct = 0, 0\r\n with torch.no_grad():\r\n for X, y in dataloader:\r\n X, y = X.to(device), y.to(device)\r\n pred = model(X)\r\n test_loss += loss_fn(pred, y).item()\r\n correct += (pred.argmax(1) == y).type(torch.float).sum().item()\r\n test_loss /= num_batches\r\n correct /= size\r\n print(f\"Test Error: \\n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \\n\") \r\n\r\nmodel = CNN().to(device)\r\n#loss function\r\nloss_fn = nn.CrossEntropyLoss()\r\nlearning_rate = .001\r\nmomentum = .9\r\noptimizer = torch.optim.SGD(model.parameters(), lr = learning_rate, momentum=momentum)\r\n\r\n\r\nepochs = 2\r\n\r\nfor t in range(epochs):\r\n print(f\"Epoch {t+1}\\n-----------------------------------\")\r\n train(train_dataloader, model, loss_fn, optimizer, device)\r\n test(test_dataloader, model, loss_fn, device)\r\n print(\"Done!\")\r\n","sub_path":"MNIST_CNN.py","file_name":"MNIST_CNN.py","file_ext":"py","file_size_in_byte":4925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"143862651","text":"class scraper:\n from selenium import webdriver\n global webdriver\n from bs4 import BeautifulSoup as bs\n global bs\n import time\n global time\n import re\n global re\n def __init__(self,username):\n self.browser = webdriver.Chrome(r'Self_Made\\chromedriver.exe')\n self.browser.get('https://www.instagram.com/' + username + '/?hl=en')\n self.username=username\n def get_links(self):\n browser=self.browser\n source = browser.page_source\n data = bs(source, 'html.parser')\n body = data.find('body')\n body=body.find(\"img\",{\"class\":\"_6q-tv\"})\n import re\n\n print(re.search(\"(?P<url>https?://[^\\s]+)\", str(body)).group(\"url\")[:-3])\n\n def link_list(browser):\n links=[]\n for i in range(6):\n Pagelength = browser.execute_script(\"window.scrollTo(document.body.scrollHeight/\" + str(i*1.5) + \", document.body.scrollHeight/\" + str(i*2.5) + \");\")\n Pagelength\n source = browser.page_source\n data = bs(source, 'html.parser')\n body = data.find('body')\n for link in body.findAll('a'):\n if re.match(\"/p/\", link.get('href')):\n links.append('https://www.instagram.com' + link.get('href'))\n time.sleep(5)\n return links\n\n return link_list(browser)\n def posts_data(self,link_list):\n d = {}\n browser=self.browser\n for link in link_list:\n browser.get(link)\n Pagelength = browser.execute_script(\"window.scrollTo(0, document.body.scrollHeight/1.5);\")\n src = browser.page_source\n src = bs(src, 'html.parser')\n bdy = src.find('body')\n time = str(bdy.find(\"time\", {\"class\": \"FH9sR Nzb55\"})).split('\"')\n description = bdy.find(\"div\", {\"class\": \"C4VMK\"})\n d[str(time[3]).encode(\"utf-8\") ]= str(description.text)[len(self.username)+len(\"Verified\"):].encode(\"utf-8\")\n return d\n def filer(self):\n posts=self.posts_data(self.get_links())\n print(len(posts))\n with open(self.username+'.txt', 'w') as f:\n f.write(\"{\\n\")\n for key in posts.keys():\n f.write(\"%s : %s,\\n\" % (str(key)[1:], str(posts[key])[1:]))\n f.write(\"}\\n\")\nscraper(\"originalfunko\").filer()\n","sub_path":"Scrapers/Self_Made/instagram.py","file_name":"instagram.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"494829632","text":"# pylint: disable=missing-docstring\nfrom os.path import join\n\nfrom resolwe_bio.utils.test import BioProcessTestCase, skipUnlessLargeFiles\n\n\nclass MicroarrayProcessorTestCase(BioProcessTestCase):\n\n @skipUnlessLargeFiles('affy_test_1.CEL', 'affy_test_2.CEL')\n def test_microarray(self):\n inputs = {'cel': join('large', 'affy_test_1.CEL')}\n cel_1 = self.run_process('upload-microarray-affy', inputs)\n inputs = {'cel': join('large', 'affy_test_2.CEL')}\n cel_2 = self.run_process('upload-microarray-affy', inputs)\n\n inputs = {'cel': [cel_1.pk, cel_2.pk],\n 'library': 'affy',\n 'logtransform': True}\n\n self.run_process('microarray-affy-qc', inputs)\n","sub_path":"resolwe_bio/tests/processes/test_microarray.py","file_name":"test_microarray.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"254320511","text":"# !/usr/bin/env python\n# coding: utf-8\nimport tensorflow as tf\nfrom tensorflow.keras.datasets import cifar10\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\nfrom tensorflow.keras.callbacks import TensorBoard \nimport pickle\nimport time\n\nSTART_TIME = int(time.time())\nprint('Start Time: {}'.format(START_TIME))\n\n# GPU Options\n# gpu_options = tf.GPUOptions(per_proccess_gpu_memory_fraction=0.333)\n# sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\n\n# reload pickle saved data\nx = pickle.load(open('x-sentdex-2.pickle', 'rb'))\ny = pickle.load(open('y-sentdex-2.pickle', 'rb'))\n\n# normalize the data, we know pixel data is 0-255 so we will use that simply\nx = x/255.0\n\n# model variation testing variables\ndense_layers = [0, 1, 2]\nconv_layers = [1, 2, 3]\nlayer_sizes = [32, 64, 128]\n\n# iterate through model variations and run them each\nfor dense_layer in dense_layers:\n for layer_size in layer_sizes:\n for conv_layer in conv_layers:\n # create log \n LOG_NAME = 'sentdex5-CNN_{}-conv_{}-dense_{}-nodes_{}'.format(conv_layer, dense_layer, layer_size, int(time.time()))\n tensorboard = TensorBoard(log_dir='logs/{}'.format(LOG_NAME))\n\n # create model (this is 5 layers)\n # input layer\n model = Sequential()\n\n # first Conv layer\n model.add(Conv2D(layer_size, (3, 3), input_shape=x.shape[1:]))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n\n # subsequent conv layers\n for l in range(conv_layer-1):\n model.add(Conv2D(layer_size, (3, 3), input_shape=x.shape[1:]))\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n \n model.add(Flatten())\n \n # generate dense layers\n for l in range(dense_layer):\n model.add(Dense(layer_size))\n model.add(Activation('relu'))\n\n # output layer\n model.add(Dense(1))\n model.add(Activation('sigmoid'))\n\n # compile\n model.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n # run, set batch size to something responsable subjective to data set size\n print('Running {} now'.format(LOG_NAME))\n model.fit(x,\n y,\n batch_size=32,\n epochs=10,\n validation_split=0.33,\n callbacks=[tensorboard])\n\nEND_TIME = int(time.time())\nprint('End Time: {}'.format(END_TIME))\nprint('Total Run Time: {}'.format(START_TIME - END_TIME))","sub_path":"sentdex-5-CNN.py","file_name":"sentdex-5-CNN.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"265682376","text":"from heads import *\n# 查询库里所有的持仓\ndef getAllPositons():\n # Position = pd.read_sql(\"select * from openquery(TEST1,'select dealusername,bondname,bondcode,(remainingfacevalue+takesupfacevalue) facevalue,fullprice costFullprice,begindate,backupday from smp_dhzq_new.VTY_BONDPOOL_HIS where type_pool = 5 and backupday = (select max(backupday) from smp_dhzq_new.VTY_BONDPOOL_HIS) and bondname like ''%CP%'' and dealusername = ''危定坤'' ')\",Engine)\n Position = pd.read_sql(\"select * from openquery(TEST1,'select dealusername,bondname,bondcode,(remainingfacevalue+takesupfacevalue) facevalue,fullprice costFullprice,begindate,backupday from smp_dhzq_new.VTY_BONDPOOL_HIS where type_pool = 5 and backupday = (select max(backupday) from smp_dhzq_new.VTY_BONDPOOL_HIS) ')\",Engine)\n return Position\n\n# 全价计算到期收益率 y = ((Fv-Pv)/Pv)*(TY/D)\ndef CalYield(code,Pv,NextTradeDay):\n try:\n code = code + \".IB\"\n Df = pd.read_sql(\n # \"select * from openquery(WIND,'select ceil(to_date(B_INFO_MATURITYDATE,''yyyyMMdd'') - sysdate) D from CBondDescription where S_INFO_WINDCODE = ''\" + code + \"'' and B_INFO_COUPON = ''505003000''')\",\n \"select * from openquery(WIND,'select ceil(to_date(B_INFO_MATURITYDATE,''yyyyMMdd'') - to_date(''\"+NextTradeDay+\"'',''yyyyMMdd'')) D from CBondDescription where S_INFO_WINDCODE = ''\" + code + \"'' ')\",\n Engine)\n D = float(Df.ix[0, 0])\n TY = 365\n Fv = 100\n y = round(100 * ((Fv - Pv) / Pv) * (TY / D), 4)\n return y\n except:\n return 0\n\n# 计算持有期资金成本\ndef CalFundCost(Position,costRate):\n # 获取最近的T+1债券交易日\n NextTradeDay = pd.read_sql(\"select * from openquery(WIND,'select min(trade_days) from CBondCalendar where S_INFO_EXCHMARKET = ''NIB'' and trade_days>sysdate order by trade_days') \",Engine)\n NextTradeDay = NextTradeDay.ix[0, 0]\n NextTradeDay = dh.str2date(NextTradeDay,type = 2)\n Position['holdDays'] = (NextTradeDay - Position.BEGINDATE).apply(lambda x: x.days)\n # Position['holdDays'] = (dh.str2date(dh.today2str()) - Position.BEGINDATE).apply(lambda x: x.days)\n Position['FundCost'] = (Position.FACEVALUE.astype(float) * Position.COSTFULLPRICE) * 100 * costRate * Position.holdDays / 365\n Position['FundCostFullPrice'] = ((Position.FACEVALUE.astype(float) * Position.COSTFULLPRICE) * 100 + Position['FundCost'])/(Position.FACEVALUE.astype(float)*100)\n return Position\n\n# 下个交易日\ndef CalNextTdDay():\n NextTradeDay = pd.read_sql(\n \"select * from openquery(WIND,'select min(trade_days) from CBondCalendar where S_INFO_EXCHMARKET = ''NIB'' and trade_days>sysdate order by trade_days') \",\n Engine)\n NextTradeDay = NextTradeDay.ix[0, 0]\n return NextTradeDay\n\n# 写入数据库\ndef WritePositionToSql(Position):\n Position.to_sql('Position', EngineIS, if_exists='replace', index=False, index_label=Position.columns,\n dtype={'backupday': sqlalchemy.DateTime,\n 'DEALUSERNAME': sqlalchemy.String,\n 'BONDNAME': sqlalchemy.String,\n 'BONDCODE': sqlalchemy.String,\n 'BEGINDATE': sqlalchemy.DateTime,\n })\n\nNextTradeDay = CalNextTdDay()\nPosition = getAllPositons()\nPosition = CalFundCost(Position,0.038)\nPosition['COSTYIELD'] = Position.apply(lambda x:CalYield(x['BONDCODE'],x['FundCostFullPrice'],NextTradeDay),axis=1)\nWritePositionToSql(Position)\n","sub_path":"jobs/SPositionjob.py","file_name":"SPositionjob.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"430876287","text":"import argparse\nfrom collections import defaultdict\nimport sys\nsys.path.append('../../../')\nfrom el_evaluation import *\nfrom utils import MyBatchSampler\nfrom torch.utils.data import DataLoader, TensorDataset\nfrom utils import QuestionSampler\nimport copy\nimport torch\nimport random\nrandom.seed(103)\n\ndevice = torch.device(\"cpu\")\n\nparser = argparse.ArgumentParser(description=\"main training script for training lnn entity linking models\")\n# parser.add_argument(\"--gmt_data\", type=str, default=\"./data/train_sorted.csv\", help=\"train csv\")\nparser.add_argument(\"--train_data\", type=str, default=\"./data/train_filtered_sorted.csv\", help=\"train csv\")\nparser.add_argument(\"--test_data\", type=str, default=\"./data/test_sorted.csv\", help=\"test csv\")\nparser.add_argument(\"--checkpoint_name\", type=str, default=\"checkpoint/best_model.pt\", help=\"checkpoint path\")\nparser.add_argument(\"--output_file_name\", type=str, default=\"output/purename_nway_alpha09.txt\", help=\"checkpoint path\")\nparser.add_argument(\"--model_name\", type=str, default=\"purename\", help=\"which model we choose\")\n# args for dividing the corpus\nparser.add_argument('--alpha', type=float, default=0.9, help='alpha for LNN')\nparser.add_argument('--num_epoch', type=int, default=100, help='training epochs for LNN')\nparser.add_argument(\"--use_binary\", action=\"store_true\", help=\"default is to use binary`, otherwise use stem\")\nparser.add_argument('--margin', type=float, default=0.15, help='margin for MarginRankingLoss')\nparser.add_argument('--learning_rate', type=float, default=0.001, help='learning rate')\nparser.add_argument(\"-f\")\nargs = parser.parse_args()\n\nfrom RuleLNN_nway_relu_vec import *\n\n\ndef get_qald_metrics(pred_, m_labels_, ques_, mode='val'):\n \"\"\"pred_ are 0/1 s after applying a threshold\"\"\"\n rows = []\n question_rows_map = {}\n question_mention_set = set()\n for i, pred in enumerate(pred_):\n pred = pred.data.tolist()[0]\n question = ques_[i]\n if question not in question_rows_map:\n question_rows_map[ques_[i]] = []\n if pred:\n men_entity_label = '_'.join(m_labels_[i].split(';')[-1].split())\n men_entity_mention = '_'.join(m_labels_[i].split(';')[0].split())\n if '-'.join([question, men_entity_mention]) in question_mention_set:\n question_rows_map[ques_[i]][-1].add(\n ('http://dbpedia.org/resource/{}'.format(men_entity_label), pred))\n else:\n question_mention_set.add('-'.join([question, men_entity_mention]))\n question_rows_map[ques_[i]].append(set())\n question_rows_map[ques_[i]][-1].add(\n ('http://dbpedia.org/resource/{}'.format(men_entity_label), pred))\n for key, preds_list_mentions in question_rows_map.items():\n if len(preds_list_mentions) > 1:\n rows.append([key, []])\n for preds_set in preds_list_mentions:\n sorted_values = sorted(list(preds_set), key=lambda x: x[1], reverse=True)[:5]\n rows[-1][1].append(sorted_values)\n elif len(preds_list_mentions) == 1:\n sorted_values = sorted(list(preds_list_mentions[0]), key=lambda x: x[1], reverse=True)[:5]\n rows.append([key, [sorted_values]])\n else:\n rows.append([key, []])\n\n df_output = pd.DataFrame(rows, columns=['Question', 'Entities'])\n df_output['Classes'] = str([])\n\n # generate the csv\n if mode == 'test':\n df_missing = pd.read_csv(\"data/missing.csv\", header=None)\n df_missing.columns = ['Unnamed:0', 'Question', 'Entities', 'Classes']\n df_missing = df_missing[['Question', 'Entities', 'Classes']]\n df_output = df_output[['Question', 'Entities', 'Classes']]\n df_output = pd.concat([df_output, df_missing], ignore_index=True)\n print(\"df_output\", df_output.shape)\n\n # gold\n benchmark = pd.read_csv('../../../data/gt_sparql.csv')\n benchmark = benchmark.set_index('Question')\n benchmark = benchmark.replace(np.nan, '', regex=True)\n benchmark['Entities'] = benchmark['Entities'].astype(object)\n is_qald_gt = True\n\n # pred\n predictions = df_output\n # print(df_output.shape)\n predictions = predictions.set_index('Question')\n predictions['Entities'] = predictions['Entities']\n predictions['Classes'] = predictions['Classes']\n\n metrics = compute_metrics(benchmark=benchmark, predictions=predictions, limit=410, is_qald_gt=is_qald_gt, eval='full')\n\n scores = metrics['macro']['named']\n prec, recall, f1 = scores['precision'], scores['recall'], scores['f1']\n return prec, recall, f1, df_output\n\n\n# def evaluate(eval_model, x_eval, y_eval, m_labels_eval, ques_eval, loss_fn):\n# \"\"\"evaluate a model on validation data\"\"\"\n# eval_model.eval()\n# with torch.no_grad():\n# val_pred = eval_model(x_eval, m_labels_eval)\n# loss = loss_fn(val_pred, y_eval)\n# # print(\"val loss is {}\".format(loss))\n# prec, recall, f1, _ = get_qald_metrics(val_pred, m_labels_eval, ques_eval)\n# # print(\"Val F1 is {}\".format(f1))\n#\n# return loss, f1, val_pred\n\n\ndef evaluate_ranking_loss(eval_model, x_, y_, m_labels_, ques_, loss_fn, mode='val'):\n \"\"\"evaluate a model on validation data\"\"\"\n eval_model.eval()\n\n dataset_ = TensorDataset(x_, y_)\n question_sampler = QuestionSampler(torch.utils.data.SequentialSampler(range(len(y_))), y_, False)\n loader = DataLoader(dataset_, batch_sampler=question_sampler, shuffle=False)\n total_loss = 0.0\n\n with torch.no_grad():\n pred_ = eval_model(x_, m_labels_)\n\n batch_num = 0\n for xb, yb in loader:\n if yb.shape[0] == 1:\n # print(xb, yb)\n continue\n yhat = eval_model(xb, yb)\n yb = yb.reshape(-1, 1)\n yhat_pos = yhat[-1].repeat((len(yhat) - 1), 1)\n yhat_neg = yhat[:-1]\n loss = loss_fn(yhat_pos, yhat_neg, torch.ones((len(yhat) - 1), 1).to(device))\n total_loss += loss.item() * (yb.shape[0] - 1)\n batch_num += 1\n avg_loss = total_loss / batch_num\n prec, recall, f1, _ = get_qald_metrics(pred_, m_labels_, ques_, mode=mode) # train and val both use 'val' mode\n\n return avg_loss, f1, pred_\n\n\ndef train(model, train_data, val_data, test_data, checkpoint_name, num_epochs, margin, learning_rate):\n \"\"\"train model and tune on validation set\"\"\"\n\n # unwrapping the data\n x_train, y_train, m_labels_train, ques_train = train_data\n x_val, y_val, m_labels_val, ques_val = val_data\n x_test, y_test, m_labels_test, ques_test = test_data\n\n # inialize the loss function and optimizer\n loss_fn = nn.MarginRankingLoss(margin=margin) # MSELoss(), did not work neither\n optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n best_val_f1, best_val_loss = 0, 100000\n best_train_val_loss = 1000000\n batch_size = 32\n\n # stats before training\n print(\"=========BEFORE TRAINING============\")\n train_loss, train_f1, train_pred = evaluate_ranking_loss(model, x_train, y_train, m_labels_train, ques_train, loss_fn)\n print(\"Train -- loss is {}; F1 is {}\".format(train_loss, train_f1))\n val_loss, val_f1, val_pred = evaluate_ranking_loss(model, x_val, y_val, m_labels_val, ques_val, loss_fn)\n print(\"Val -- loss is {}; F1 is {}\".format(val_loss, val_f1))\n test_loss, test_f1, test_pred = evaluate_ranking_loss(model, x_test, y_test, m_labels_test, ques_test, loss_fn, mode='test')\n print(\"Test -- loss is {}; F1 is {}\".format(test_loss, test_f1))\n\n # start training\n print(\"=========TRAINING============\")\n dataset_train = TensorDataset(x_train, y_train)\n question_sampler = QuestionSampler(torch.utils.data.SequentialSampler(range(len(y_train))), y_train, False)\n loader = DataLoader(dataset_train, batch_sampler=question_sampler, shuffle=False)\n # loader = DataLoader(dataset_train, sampler=torch.utils.data.SequentialSampler(dataset_train), batch_size=batch_size, shuffle=False) # always False\n # loader = DataLoader(dataset_train, sampler=torch.utils.data.WeightedRandomSampler(torch.FloatTensor([1, 100]), len(x_train), replacement=True), batch_size=64, shuffle=False) # always False\n best_model = None\n \n for epoch in range(num_epochs):\n total_loss = 0.0\n idx = 0\n\n # prev xb\n prev_xb, prev_yb = None, None\n for xb, yb in loader:\n idx += 1\n model.train() # set train to true\n optimizer.zero_grad()\n # handle question with multiple positives\n if yb.shape[0] == 1:\n yb = prev_yb\n # print(prev_xb)\n # print(xb)\n prev_xb[-1,:] = xb\n xb = prev_xb\n # print(xb)\n yhat = model(xb, yb)\n yb = yb.reshape(-1, 1)\n yhat_pos = yhat[-1].repeat((len(yhat) - 1), 1)\n yhat_neg = yhat[:-1] #torch.mean(yhat[:-1], dim=0)\n\n loss = loss_fn(yhat_pos, yhat_neg, torch.ones((len(yhat) - 1), 1).to(device))\n if idx == 212:\n print('loss', idx, loss)\n\n total_loss += loss.item() * (yb.shape[0] - 1)\n loss.backward()\n optimizer.step()\n prev_xb, prev_yb = xb, yb\n\n for name, param in model.named_parameters():\n if param.requires_grad:\n print(name, 'param -- data', param.data, 'grad -- ', param.grad)\n\n # show status after each epoch\n avg_loss = total_loss / idx\n # train_loss, train_f1, train_pred = evaluate(model, x_train, y_train, m_labels_train, ques_train, loss_fn)\n print(\"Epoch \" + str(epoch) + \": avg train loss -- \" + str(avg_loss))\n # print(\"Train -- loss is {}; F1 is {}\".format(train_loss, train_f1))\n val_loss, val_f1, val_pred = evaluate_ranking_loss(model, x_val, y_val, m_labels_val, ques_val, loss_fn)\n \n if val_f1 >= best_val_f1:\n # if val_f1 >= best_val_f1:\n best_val_f1 = val_f1\n best_val_loss = val_loss\n # best_train_val_loss = val_loss + avg_loss\n best_model = copy.deepcopy(model)\n torch.save(best_model.state_dict(), checkpoint_name)\n print(\"Val -- best loss is {}; F1 is {}\".format(best_val_loss, best_val_f1))\n\n test_loss, test_f1, test_pred = evaluate_ranking_loss(model, x_test, y_test, m_labels_test, ques_test, loss_fn, mode='test')\n print(\"Current Test -- loss is {}; F1 is {}\".format(test_loss, test_f1))\n\n # show stats after training\n print(\"=========AFTER TRAINING============\")\n train_loss, train_f1, train_pred = evaluate_ranking_loss(best_model, x_train, y_train, m_labels_train, ques_train, loss_fn)\n print(\"Train -- loss is {}; F1 is {}\".format(train_loss, train_f1))\n val_loss, val_f1, val_pred = evaluate_ranking_loss(best_model, x_val, y_val, m_labels_val, ques_val, loss_fn)\n print(\"Val -- loss is {}; F1 is {}\".format(val_loss, val_f1))\n test_loss, test_f1, test_pred = evaluate_ranking_loss(best_model, x_test, y_test, m_labels_test, ques_test, loss_fn, mode='test')\n print(\"Test -- loss is {}; F1 is {}\".format(test_loss, test_f1))\n\n return\n\n\ndef test(x_test, m_labels_test, ques_test, alpha, checkpoint_name, model_name, output_file_name):\n \"\"\"make predictions on test set\"\"\"\n bestModel = pick_model(model_name, alpha)\n bestModel.load_state_dict(torch.load(checkpoint_name))\n bestModel.eval()\n best_scores = {}\n\n with torch.no_grad():\n test_pred = bestModel(x_test, m_labels_test)\n prec, recall, f1, df_output = get_qald_metrics(test_pred, m_labels_test, ques_test, mode='test')\n df_output.to_csv(output_file_name)\n print(\"Test -- f1 is {} \".format(f1))\n print(\"Test -- prec, recall, f1\", prec, recall, f1)\n best_scores['precision'] = prec\n best_scores['recall'] = recall\n best_scores['f1'] = f1\n\n # for name, mod in bestModel.named_modules():\n # if type(mod) == nn.ModuleList:\n # for name1, mod1 in mod.named_modules():\n # if 'cdd' not in name1 and 'AND' not in name1:\n # if 'batch' in name1.lower():\n # continue\n # elif 'or_max' in name1.lower():\n # continue\n # elif 'and' in name1.lower():\n # print(name1, mod1.cdd())\n # elif 'or' in name1.lower():\n # print(name1, mod1.AND.cdd())\n # else:\n # if 'cdd' not in name and 'AND' not in name:\n # if 'batch' in name.lower():\n # continue\n # elif 'or_max' in name.lower():\n # continue\n # elif 'and' in name.lower():\n # print(name, mod.cdd())\n # elif 'or' in name.lower():\n # print(name, mod.AND.cdd())\n return test_pred, best_scores\n\n\ndef pick_model(model_name, alpha):\n if model_name == \"purename\":\n return PureNameLNN(alpha, -1, False)\n elif model_name == \"context\":\n return ContextLNN(alpha, -1, False)\n elif model_name == \"complex\":\n return ComplexRuleLNN(alpha, -1, False)\n elif model_name == \"lr\":\n return LogitsRegression()\n else:\n print(\"WRONG name input\")\n return None\n\n\ndef main():\n\n # read df and split into train/val\n df_gmt = pd.read_csv(args.train_data)\n df_train_val = pd.read_csv(args.train_data)\n shuffled_question_list = list(df_gmt.Question.unique())\n random.shuffle(shuffled_question_list)\n train_val_split_idx = int(len(shuffled_question_list)*0.8)\n train_ques_set = shuffled_question_list[:train_val_split_idx]\n val_ques_set = shuffled_question_list[train_val_split_idx:]\n df_train = df_gmt[df_gmt.Question.isin(train_ques_set)]\n df_val = df_train_val[df_train_val.Question.isin(val_ques_set)]\n df_test = pd.read_csv(args.test_data)\n\n # train\n features_train = np.array([np.fromstring(s[1:-1], dtype=np.float, sep=', ') for s in df_train.Features.values])\n x_train = torch.from_numpy(features_train).float()\n y_train = torch.from_numpy(df_train.Label.values).float().reshape(-1, 1)\n m_labels_train = df_train.Mention_label.values\n ques_train = df_train.Question.values\n\n # val\n features_val = np.array([np.fromstring(s[1:-1], dtype=np.float, sep=', ') for s in df_val.Features.values])\n x_val = torch.from_numpy(features_val).float()\n y_val = torch.from_numpy(df_val.Label.values).float().reshape(-1, 1)\n m_labels_val = df_val.Mention_label.values\n ques_val = df_val.Question.values\n\n # test\n features_test = np.array([np.fromstring(s[1:-1], dtype=np.float, sep=', ') for s in df_test.Features.values])\n x_test = torch.from_numpy(features_test).float()\n y_test = torch.from_numpy(df_test.Label.values).float().reshape(-1, 1)\n m_labels_test = df_test.Mention_label.values\n ques_test = df_test.Question.values\n\n # train model and evaluate\n model = pick_model(args.model_name, args.alpha)\n model = model.to(device)\n\n # move to gpu\n x_train, y_train = x_train.to(device), y_train.to(device)\n x_val, y_val = x_val.to(device), y_val.to(device)\n x_test, y_test = x_test.to(device), y_test.to(device)\n\n print(model)\n \n print(\"model: \", args.model_name, args.alpha)\n print(model(x_train, m_labels_train))\n print(x_train.shape, x_val.shape)\n\n print(\"y_train sum\", sum(y_train), sum(y_train)/len(y_train))\n print(\"y_val sum\", sum(y_val), sum(y_val)/len(y_val))\n print(\"y_test sum\", sum(y_test), sum(y_test)/len(y_test))\n\n # aggregate the data into train, val, and test\n train_data = (x_train, y_train, m_labels_train, ques_train)\n print(\"train:\", x_train.shape, y_train.shape, m_labels_train.shape, ques_train.shape)\n val_data = (x_val, y_val, m_labels_val, ques_val)\n print(\"val:\", x_val.shape, y_val.shape, m_labels_val.shape, ques_val.shape)\n test_data = (x_test, y_test, m_labels_test, ques_test)\n print(\"test:\", x_test.shape, y_test.shape, m_labels_test.shape, ques_test.shape)\n\n # check class distribution\n print(\"y_train sum\", sum(y_train), sum(y_train) / len(y_train))\n print(\"y_val sum\", sum(y_val), sum(y_val) / len(y_val))\n print(\"y_test sum\", sum(y_test), sum(y_test) / len(y_test))\n\n train(model, train_data, val_data, test_data, args.checkpoint_name, args.num_epoch, args.margin, args.learning_rate)\n test_pred, best_scores = test(x_test, m_labels_test, ques_test, args.alpha, args.checkpoint_name, args.model_name, args.output_file_name)\n with open(\"output_w_spacy.txt\", 'a') as f:\n f.write(\"model={}; use_binary={}; alpha={}; p={}; r={}; f1={}; lr={}; margin={}\\n\".format(args.model_name, args.use_binary, args.alpha,\n best_scores['precision'], best_scores['recall'],\n best_scores['f1'], args.learning_rate, args.margin))\n print(\"model={}; use_binary={}; alpha={}; p={}; r={}; f1={}\\n\".format(args.model_name, args.use_binary, args.alpha,\n best_scores['precision'], best_scores['recall'],\n best_scores['f1']))\n\n\nif __name__ == '__main__':\n # args.learning_rate = 0.001\n args.num_epoch = 200\n args.model_name = \"complex\"\n args.margin = 0.601\n args.alpha = 0.9\n args.learning_rate = 0.001\n main()\n # for margin in np.linspace(0.6, 0.9, num=301):\n # args.margin = round(margin, 3)\n # print(args.margin)\n # main()\n # args.margin = 0.69\n # args.learning_rate = 0.001\n # args.num_epoch = 100\n # main()\n # learning_rate = 1.0\n # for _ in range(0, 6):\n # learning_rate = learning_rate / 10\n # args.learning_rate = learning_rate\n # print(args)\n # main()\n #\n # learning_rate = 5.0\n # for _ in range(0, 6):\n # learning_rate = learning_rate / 10\n # args.learning_rate = learning_rate\n # print(args)\n # main()\n","sub_path":"examples/entity/history/run_el.py","file_name":"run_el.py","file_ext":"py","file_size_in_byte":18230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"448088998","text":"import unittest\nfrom flask_login import current_user\nfrom Flasklearning.flaskyy.app import create_app,db\nfrom flask import current_app\nfrom Flasklearning.flaskyy.app.models import User\n\n\nfrom flask import current_app,render_template\nfrom threading import Thread\nfrom Flasklearning.flaskyy.app import mail\nfrom flask_mail import Message\n\n\n\n\nclass Email_test(unittest.TestCase):\n def setUp(self):\n self.app=create_app('testing')\n self.app_context=self.app.app_context()\n self.app_context.push()\n db.create_all()\n\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n\n def test_email(self):\n self.app = create_app('testing')\n self.app_context = self.app.app_context()\n self.app_context.push()\n def send_async_email(app, msg):\n with self.app_context:\n mail.send(msg)\n\n def send_email(subject, to, text, **kwargs):\n msg = Message(subject=subject, sender='1627237372@qq.com', recipients=[to])\n msg.body = text\n thr = Thread(target=send_async_email, args=[current_app, msg])\n thr.start()\n return thr\n\n u = User(email='wangjie@163.com', username='wangjie', password='1111')\n db.session.add(u)\n db.session.commit()\n token = u.generate_confirmation_token()\n send_email(subject='Confirm your account', to='13533801264@163.com', text='Helo,test')\n\nif __name__==\"__main__\":\n unittest.main()","sub_path":"flaskyy/tests/test_email.py","file_name":"test_email.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"520466976","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass AlipayCloudCloudbaseFunctionVersionCreateModel(object):\n\n def __init__(self):\n self._biz_app_id = None\n self._biz_env_id = None\n self._description = None\n self._function_name = None\n self._name = None\n\n @property\n def biz_app_id(self):\n return self._biz_app_id\n\n @biz_app_id.setter\n def biz_app_id(self, value):\n self._biz_app_id = value\n @property\n def biz_env_id(self):\n return self._biz_env_id\n\n @biz_env_id.setter\n def biz_env_id(self, value):\n self._biz_env_id = value\n @property\n def description(self):\n return self._description\n\n @description.setter\n def description(self, value):\n self._description = value\n @property\n def function_name(self):\n return self._function_name\n\n @function_name.setter\n def function_name(self, value):\n self._function_name = value\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, value):\n self._name = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.biz_app_id:\n if hasattr(self.biz_app_id, 'to_alipay_dict'):\n params['biz_app_id'] = self.biz_app_id.to_alipay_dict()\n else:\n params['biz_app_id'] = self.biz_app_id\n if self.biz_env_id:\n if hasattr(self.biz_env_id, 'to_alipay_dict'):\n params['biz_env_id'] = self.biz_env_id.to_alipay_dict()\n else:\n params['biz_env_id'] = self.biz_env_id\n if self.description:\n if hasattr(self.description, 'to_alipay_dict'):\n params['description'] = self.description.to_alipay_dict()\n else:\n params['description'] = self.description\n if self.function_name:\n if hasattr(self.function_name, 'to_alipay_dict'):\n params['function_name'] = self.function_name.to_alipay_dict()\n else:\n params['function_name'] = self.function_name\n if self.name:\n if hasattr(self.name, 'to_alipay_dict'):\n params['name'] = self.name.to_alipay_dict()\n else:\n params['name'] = self.name\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = AlipayCloudCloudbaseFunctionVersionCreateModel()\n if 'biz_app_id' in d:\n o.biz_app_id = d['biz_app_id']\n if 'biz_env_id' in d:\n o.biz_env_id = d['biz_env_id']\n if 'description' in d:\n o.description = d['description']\n if 'function_name' in d:\n o.function_name = d['function_name']\n if 'name' in d:\n o.name = d['name']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/AlipayCloudCloudbaseFunctionVersionCreateModel.py","file_name":"AlipayCloudCloudbaseFunctionVersionCreateModel.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"105997389","text":"import random\nimport unittest\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.select import Select\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nfrom Ellie_Steps.common import login\n\n\nclass Homework_6(unittest.TestCase):\n\n def setUp(self):\n self.driver = webdriver.Chrome(executable_path='/Users/andrei/Documents/PycharmProjects/Seleniumwd2/browser_drivers/chromedriver')\n self.driver.get('http://hrm-online.portnov.com')\n self.wait = WebDriverWait(self.driver, 2)\n\n def tearDown(self):\n driver = self.driver\n if self.report_name:\n driver.find_element_by_id('menu_pim_viewPimModule').click()\n driver.find_element_by_id('menu_core_viewDefinedPredefinedReports').click()\n\n driver.find_element_by_id('search_search').send_keys(self.report_name)\n driver.find_element_by_class_name('searchBtn').click()\n\n driver.find_element_by_css_selector('td>input').click()\n driver.find_element_by_id('btnDelete').click()\n\n self.wait.until(EC.visibility_of_element_located((By.ID, 'dialogDeleteBtn'))).click()\n\n # teardown remove the report\n self.driver.quit()\n\n def test(self):\n report_name = 'Andrei' + str(random.randint(1, 100))\n\n driver = self.driver\n login(driver)\n\n # reports page - unique report name\n driver.find_element_by_id('menu_pim_viewPimModule').click()\n driver.find_element_by_id('menu_core_viewDefinedPredefinedReports').click()\n\n driver.find_element_by_id('btnAdd').click()\n self.wait.until(EC.presence_of_element_located\n ((By.ID, 'report_report_name'))).send_keys(report_name)\n\n # selection criteria - job title\n Select(driver.find_element_by_id('report_criteria_list')).select_by_visible_text('Job Title')\n driver.find_element_by_id('btnAddConstraint').click()\n\n # display field groups - personal - wait for checkbox\n Select(driver.find_element_by_id('report_display_groups')).select_by_visible_text('Personal')\n driver.find_element_by_id('btnAddDisplayGroup').click()\n\n driver.find_element_by_id('display_group_1').click()\n driver.find_element_by_id('btnSave').click()\n\n # verify the report was created\n self.assertTrue(self.is_element_present(By.XPATH, \"//td[text()='{0}']\".format(report_name)))\n\n # yes a report was created and will require cleanup\n self.report_name = report_name\n\n # run the report\n driver.find_element_by_xpath(\"//td[text()='{0}']/../td[3]/a\".format(report_name)).click()\n\n # verify that it works\n report_header = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, \".head h1\"))).text\n self.assertEqual('Report Name : {0}'.format(report_name), report_header)\n\n def is_element_present(self, by, locator):\n try:\n self.driver.find_element(by, locator)\n return True\n except NoSuchElementException:\n return False\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"PycharmProjects/Seleniumwd2/Ellie/6_report_test.py","file_name":"6_report_test.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"72189603","text":"class major():\r\n def __init__(self):\r\n #the main block keeping count of the \r\n #iteration ad which ba or ab to find\r\n self.text=list(\"__\")\r\n self.dotpos=0\r\n self.movCount=1\r\n def startCase(self):\r\n counter=input()\r\n for i in range(int(counter)):\r\n self.text.append('B')\r\n self.text.append('A')\r\n \r\n \r\n#moving only the given count number of AB from end to empty position \r\ndef step1(obj):\r\n \r\n curCount=0\r\n for curPos in range(len(obj.text)-1,obj.dotpos-1,-1):\r\n if obj.text[curPos]=='B' and obj.text[curPos-1]=='A':\r\n curCount+=1\r\n if curCount==obj.movCount:\r\n print(\"{} to {}\".format(curPos-2,obj.dotpos-1))\r\n obj.text[curPos]='_'\r\n obj.text[curPos-1]='_'\r\n obj.text[obj.dotpos]='A'\r\n obj.text[obj.dotpos+1]='B' \r\n obj.dotpos=curPos-1\r\n obj.movCount+=1\r\n break\r\n# print(\"\".join(obj.text))\r\n\r\n return \"\".join(obj.text)\r\n \r\n#moving only the given count number of BA from empty position \r\ndef step2(obj):\r\n curCount=0\r\n for curPos in range(0,obj.dotpos-1,1):\r\n if obj.text[curPos]=='B' and obj.text[curPos+1]=='A':\r\n curCount+=1\r\n# print(curCount)\r\n if curCount==obj.movCount:\r\n print(\"{} to {}\".format(curPos-1,obj.dotpos-1)) \r\n obj.text[curPos]='_'\r\n obj.text[curPos+1]='_'\r\n obj.text[obj.dotpos]='B'\r\n obj.text[obj.dotpos+1]='A' \r\n obj.dotpos=curPos\r\n break\r\n# print(\"\".join(obj.text))\r\n return \"\".join(obj.text)\r\n\r\n#sorting the pairs... bb to empty and then aa to empty\r\ndef step3(obj):\r\n for i in range(0,len(obj.text)-1,1):\r\n if obj.text[i]=='B' and obj.text[i+1]=='B':\r\n print(\"{} to {}\".format(i-1,obj.dotpos-1)) \r\n obj.text[i]='_'\r\n obj.text[i+1]='_'\r\n obj.text[obj.dotpos]='B' \r\n obj.text[obj.dotpos+1]='B'\r\n# print(\"{} to {}\".format(i-1,obj.log1-1))\r\n log=obj.dotpos\r\n obj.dotpos=i\r\n break\r\n# print(\"\".join(obj.text))\r\n for i in range(log+1,len(obj.text)-1,1):\r\n if obj.text[i]=='A' and obj.text[i+1]=='A':\r\n print(\"{} to {}\".format(i-1,obj.dotpos-1)) \r\n obj.text[i]='_'\r\n obj.text[i+1]='_'\r\n obj.text[obj.dotpos]='A' \r\n obj.text[obj.dotpos+1]='A'\r\n obj.dotpos=i\r\n break\r\n# print(\"\".join(obj.text))\r\n if i==len(obj.text)-2:\r\n return False\r\n else:\r\n return True\r\nif __name__==\"__main__\":\r\n m=major()\r\n m.startCase()\r\n# print(\"\".join(m.text))\r\n n=(len(m.text)-2)/2\r\n# print(n)\r\n \r\n #sorting ab and ba\r\n for i in range(int(n/4)):\r\n step1(m)\r\n step2(m)\r\n\r\n #for odd numbers (works only on n%4==1)\r\n if n%2==1:\r\n m.movCount-=1\r\n step1(m)\r\n \r\n #sorting the pairs now\r\n for j in range(i,int(n),1):\r\n if not step3(m):\r\n break\r\n","sub_path":"pythonTrials/src/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":3255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"605526431","text":"\"\"\"\nThe classes of token are keyword, identifier, comparison, float and whitespace etc..\n\"\"\"\nimport queue\n\n\nletter = ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',\n 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')\nnzero = ('1','2','3','4','5','6','7','8','9')\nzero = ('0')\nskip = (\" \",\"\\r\",\"\\n\")\nkeyword = ('int', 'INT', 'char', 'CHAR', 'if', 'IF', 'else', 'ELSE','while', 'WHILE','return', 'RETURN')\nARITHMETIC = ('MINUS', 'PLUS', 'MULTIPLY', 'DIVIDE')\nCOMPARISON = ('COMPARISONM', 'COMPARISON')\n\nclass DFA:\n state_now = None\n\n\n states = []\n finalState = []\n transitionFunction = dict()\n alphabet = []\n startState = ''\n\n\n token = ''\n finalStateCondition = False\n q = queue.Queue(100)\n\n\n def __init__(self, states, finalState, alphabet, startState, transitionFunction):\n self.states = states\n self.finalState = finalState\n self.transitionFunction = transitionFunction\n self.alphabet = alphabet\n self.state_now = startState\n self.startState = startState\n\n def transition(self, symbol):\n key = (self.state_now, symbol[1])\n if key in self.transitionFunction:\n self.q.put(symbol[0])\n\n #change the current state\n self.state_now = self.transitionFunction[key]\n\n #is this current state a final state\n if self.state_now in self.finalState:\n for i in range(self.q.qsize()):\n self.token += self.q.get()\n self.finalStateCondition = True\n\n else :\n #previous state is finalstate and current state is not finalstate\n #print state and then DFA is initialized\n if self.finalStateCondition == True:\n self.removeSpace()\n self.isIdentifier()\n self.isArithmetic()\n self.isComparision()\n print(self.state_now, self.token)\n self.state_now = 'start'\n self.token = ''\n self.finalStateCondition = False\n self.transition(symbol)\n else:\n #exception handling\n print(\"it's not right input\")\n exit(-1)\n\n def removeSpace(self):\n self.token = self.token.strip()\n\n def isIdentifier(self):\n if self.state_now == 'IDENTIFIER':\n if self.token in keyword:\n self.state_now = self.token.upper()\n else:\n pass\n else:\n pass\n return\n\n def isArithmetic(self):\n if self.state_now in ARITHMETIC:\n self.state_now = 'ARITHMETIC'\n return\n\n def isComparision(self):\n if self.state_now in COMPARISON:\n self.state_now = 'COMPARISON'\n\n def isthisfinalState(self):\n if self.state_now in self.finalState:\n return True\n\n\nstates = ['start', 'IDENTIFIER', 'MINUS', 'PLUS', 'MULTIPLY', 'DIVIDE', '!', 'COMPARISONM','COMPARISON', 'ASSIGNMENT', 'stringM', 'STRING', 'SEMICOLON', 'LBRACE', 'RBRACE','LPAREN', 'RPAREN', 'COMMA']\nfinalState = ['INTEGER', 'STRING', 'MINUS', 'PLUS', 'MULTIPLY', 'DIVIDE', 'COMPARISONM','COMPARISON', 'SEMICOLON', 'LBRACE', 'RBRACE', 'LPAREN','RPAREN', 'COMMA','IDENTIFIER', 'ASSIGNMENT']\nalphabet = [' ', '\\t', '\\n', 'letter', 'zero', 'nzero', '-', '+', '*', '/', '!', '=', '<', '>', '\\\"', ';', '{', '}', '(', ')', ',']\nstartState = 'start'\ntrans = dict()\n\n#trnas is transition function\n#The feature of trans is trans[(curremt_state, symbol)] = next_state\n\n#DFA for start\ntrans[('start', ' ')] = 'start'\ntrans[('start', '\\t')] = 'start'\ntrans[('start', '\\n')] = 'start'\n\n#DFA for IDENTIFIER\ntrans[('start', 'letter')] = 'IDENTIFIER'\ntrans[('IDENTIFIER', 'letter')] = 'IDENTIFIER'\ntrans[('IDENTIFIER', 'zero')] = 'IDENTIFIER'\ntrans[('IDENTIFIER', 'nzero')] = 'IDENTIFIER'\n\n#DFA for Signed INTEGER\ntrans[('start', '-')] = 'MINUS'\ntrans[('MINUS', 'nzero')] = 'INTEGER'\n\ntrans[('start', 'zero')] = 'INTEGER'\ntrans[('start', 'nzero')] = 'INTEGER'\ntrans[('INTEGER', 'zero')] = 'INTEGER'\ntrans[('INTEGER', 'nzero')] = 'INTEGER'\n\n\n#DFA for ARITHMETIC\ntrans[('start', '+')] = 'PLUS'\ntrans[('start', '*')] = 'MULTIPLY'\ntrans[('start', '/')] = 'DIVIDE'\n\n#DFA for COMPARISON and ASSIGNMENT\ntrans[('start', '!')] = '!'\ntrans[('start', '=')] = 'ASSIGNMENT'\ntrans[('start', '>')] = 'COMPARISONM'\ntrans[('start', '<')] = 'COMPARISONM'\n\ntrans[('!', '=')] = 'COMPARISON'\ntrans[('ASSIGNMENT', '=')] = 'COMPARISON'\ntrans[('COMPARISONM', '=')] = 'COMPARISON'\n\n#DFA for STRING\ntrans[('start', '\\\"')] = 'stringM'\ntrans[('stringM', 'letter')] = 'stringM'\ntrans[('stringM', 'zero')] = 'stringM'\ntrans[('stringM', 'nzero')] = 'stringM'\ntrans[('stringM', ' ')] = 'stringM'\ntrans[('stringM', '\\\"')] = 'STRING'\n\n\n\n\n#DFA for SEMICOLON\ntrans[('start', ';')] = 'SEMICOLON'\n\n#DFA for LBRACE\ntrans[('start', '{')] = 'LBRACE'\n\n#DFA for RBRACE\ntrans[('start', '}')] = 'RBRACE'\n\n#DFA for LPAREN\ntrans[('start', '(')] = 'LPAREN'\n\n#DFA for RPAREN\ntrans[('start', ')')] = 'RPAREN'\n\n#DFA for COMMA\ntrans[('start', ',')] = 'COMMA'\n\n\n\n#read file and we initialize DFA\nfilename = \"test.c\"\nf = open(filename, 'r')\ndata = f.read()\ndata += ' '\ndfa = DFA(states, finalState, alphabet, startState, trans)\n\n#If c is letter or zero or nzero, we append the alphabet of c ( ex) letter, zero, nzero)\ndef isitletterOrdigit(c):\n set = [c]\n if c in letter:\n set.append('letter')\n elif c in zero:\n set.append('zero')\n elif c in nzero:\n set.append('nzero')\n else:\n set.append(c)\n return set\n\n#Input data into trasition function\nfor c in data:\n dfa.transition(isitletterOrdigit(c))\n","sub_path":"[컴파일러] lexical_Anlyzer_Project/lexicalAnlyzerProject/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"492886647","text":"from movies.models import Movie\nfrom .handlers import keys_to_lower\n\ndef save_movie(data):\n '''\n save movie if is not in database\n '''\n title = data['Title']\n if not is_movie_in_db(title):\n data = keys_to_lower(data)\n data['movie_type'] = data.pop('type', None)\n movie = Movie(**data)\n movie.save()\n else:\n movie = Movie.objects.get(title__iexact=title)\n\n return movie\n\ndef is_movie_in_db(title):\n exists = False\n if Movie.objects.filter(title__iexact=title).count():\n exists = True\n\n return exists\n\n\n\n","sub_path":"django/movies/queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"262508263","text":"# import pprint\nimport pandas as pd\nimport numpy as np\nimport collections\nimport functools\nimport operator\nimport subprocess\nimport io\nimport re\nfrom sklearn.neighbors import KernelDensity\nimport matplotlib.pyplot as plt\n\ndef preview_file(swcfile, rows=15):\n \"\"\"Preview swc header and first few lines\"\"\"\n with open(swcfile, 'r') as f:\n print(\"First {} lines of `{}`:\\n\".format(rows, swcfile))\n for n, row in enumerate(f.readlines()[:rows]):\n print(\"{}\\t{}\".format(n,row))\n\ndef load_to_dataframe(swcfile, skiprows=None,\n names=['type','x_coord','y_coord','z_coord','radius','parent'],\n dtype={'type':'int8','parent':'int32'},\n sep=\" \",\n **kwargs):\n \"\"\"Load swc file to pandas dataframe and return\"\"\"\n n_df = pd.read_csv(swcfile, names=names,\n dtype=dtype, skiprows=skiprows, sep=\" \",\n **kwargs\n )\n return n_df\n\ndef euc_distance_to_root(n_df, root_index=1):\n \"\"\"For each point, calculate euclidean distance to root (default root index=0);\n add as column euc_dist_root\"\"\"\n dist_coords = np.array(\n n_df.loc[:,['x_coord','y_coord','z_coord']] \\\n - n_df.loc[root_index,['x_coord','y_coord','z_coord']],dtype=float)\n #return np.sum(dist_coords * dist_coords, axis=1)**.5\n return np.linalg.norm(dist_coords, axis=1)\n\ndef distance_to_parent(n_df):\n \"\"\"for each point, get distance to parent node; return array\"\"\"\n dist_coords = np.asarray(\n n_df.loc[:,['x_coord','y_coord','z_coord']] \\\n - n_df.loc[n_df.loc[:,'parent'],['x_coord','y_coord','z_coord']].values\n )\n return np.linalg.norm(dist_coords, axis=1)\n\ndef get_child_list(n_df):\n childlist = collections.defaultdict(list)\n for row in n_df.iterrows():\n childlist[int(row[1]['parent'])].append(row[0])\n # if childlist.get(-1):\n # del childlist[-1]\n childlist_df = pd.DataFrame(pd.Series(childlist))\n childlist_df.columns=['child_indices']\n return childlist_df\n\ndef get_termini(n_df):\n child_list = get_child_list(n_df)\n termini = set(n_df.index.values) - set(child_list)\n return termini\n\ndef get_path_to_root(n, path_to_root, n_df):\n \"\"\"Given a point, return a list of points connecting to the root\"\"\"\n n = n_df.loc[n,'parent']\n if n != -1:\n path_to_root.append(n)\n# print n\n get_path_to_root(n, path_to_root, n_df)\n return path_to_root\n\ndef get_dist_to_root(n, n_df):\n \"\"\"Given a point n, get distance to root using get_path_to_root\"\"\"\n path_array = np.asarray(get_path_to_root(n,[],n_df))\n return distance_to_parent(n_df)[path_array[:-1]].sum()\n\ndef get_persistence_barcode(tree):\n \"\"\"Given swc, return persistence barcode\n \"\"\"\n pass\n\n\ndef memoize(obj):\n \"\"\"cache output of functions for efficiency\"\"\"\n cache = obj.cache = {}\n\n @functools.wraps(obj)\n def memoizer(*args, **kwargs):\n if args not in cache:\n cache[args] = obj(*args, **kwargs)\n return cache[args]\n return memoizer\n\nclass NTree(object):\n \"\"\"This class generates morophology information from swc files.\n \"\"\"\n def __init__(self, swcfp, root_index=1):\n self.root_index = root_index\n _, self.df = self.split_meta_data(swcfp)\n self.df['child_indices'] = self._get_child_list()\n self.df['euc_dist_to_root'] = self.get_euc_distance_to_root()\n self.branch_nodes = self.get_branch_nodes()\n self.terminal_nodes = self.get_terminal_nodes()\n\n def __repr__(self):\n return \"\"\n\n def split_meta_data(self, swc):\n if type(swc)== bytes:\n s = str(swc, 'utf-8')\n else:\n with open(swc,'r') as f:\n s = \"\\n\".join(f.readlines())\n\n # pass only valid lines: comments (starts with #) and swc lines (starts with blank or int), sent to `meta` and `swc` buffers\n line_generator = (x.group(0).strip() for x in re.finditer(r\"[# 0-9].+\\s\", s))\n meta = io.StringIO()\n swc = io.StringIO()\n for line in line_generator:\n # print(line)\n if re.match(r\"^[ 0-9]+\", line):\n swc.write(f\"{line}\\n\")\n else:\n meta.write(f\"{line}\\n\")\n\n # with open(\"meta.tmp\",\"w\") as m:\n # m.write(meta.getvalue())\n # with open(\"swc.tmp\", \"w\") as fs:\n # fs.write(swc.getvalue())\n if type(s) == \"_io.TextIOWrapper\":\n s.close()\n meta.seek(0)\n swc.seek(0)\n return meta.read(), load_to_dataframe(swc)\n\n def find_skiprows(self, swcfile):\n \"\"\"obsolete\"\"\"\n cmd1 = [\"grep\", \"^# \", swcfile]\n cmd2 = [\"wc\", \"-l\"]\n grep = subprocess.Popen(cmd1, stdout=subprocess.PIPE)\n out = subprocess.check_output(cmd2, stdin = grep.stdout)\n return int(out.strip())\n\n @staticmethod\n def preview_file(swcfile, rows=15):\n preview_file(swcfile, rows)\n\n def load_to_dataframe(self,swcfile,skiprows, sep=\" \"):\n return load_to_dataframe(swcfile,skiprows=self.skiprows, sep=sep, skipinitialspace=True)\n\n def verify_swc_structure(self):\n assert self.df.iloc[0,5] == -1\n# assert self.df.shape[0] == self.df.loc[self.df.shape[0]-1,'pindex']\n\n def _get_child_list(self):\n \"\"\"Returns child list as pandas series\"\"\"\n return self.df.merge(get_child_list(self.df),how='left',right_index=True,\n left_index=True).loc[:,['child_indices']]\n\n def get_branch_nodes(self):\n \"\"\"Given df with child indices, returns numpy array of branch nodes\"\"\"\n branch_nodes = [1]\n for row in self.df.iterrows():\n if type(row[1]['child_indices']) == list:\n if len(row[1]['child_indices']) > 1:\n branch_nodes.append(row[0])\n return np.array(branch_nodes)\n\n def get_terminal_nodes(self):\n \"\"\"Given df with child indices, returns numpy array of terminal nodes\"\"\"\n terminal_nodes = []\n for row in self.df.iterrows():\n if type(row[1]['child_indices']) != list:\n terminal_nodes.append(row[0])\n return np.array(terminal_nodes)\n\n def get_euc_distance_to_root(self):\n return euc_distance_to_root(self.df,self.root_index)\n\n def get_lineage(self,l):\n \"\"\"Given a node index, yield a generator that traces lineage to root,\n traversing branch nodes\"\"\"\n\n n = l\n lineage = [n]\n while n != -1:\n p = self.df.loc[n,'parent']\n if p in self.branch_nodes:\n lineage.append(p)\n n = p\n lineage.append(-1)\n yield lineage\n\n @memoize\n def get_parent_branch(self,l):\n \"\"\"Get parent branch of l\"\"\"\n n = l\n while True:\n p = self.df.loc[n,'parent']\n if p in self.branch_nodes:\n return p\n if p == -1:\n return 1\n n = p\n return n\n\n @memoize\n def get_child_nodes(self,n):\n \"\"\"Given a node, find its children (branches and leaves immediately downstream)\"\"\"\n assert n in self.branch_nodes\n\n child_nodes = []\n cl = collections.deque(self.df.loc[n,'child_indices'])\n while len(cl)>0:\n c = cl.pop()\n if any([(c in self.branch_nodes), (c in self.terminal_nodes)]):\n child_nodes.append(c)\n else:\n cl.extendleft(self.df.loc[c,'child_indices'])\n return child_nodes\n\n\n\n def get_subtree_leaves(self,n):\n \"\"\"Given node index n, return list of leaves in subtree\"\"\"\n terminal_nodes = self.get_terminal_nodes()\n cl = self.df.loc[n,'child_indices']\n if type(cl)==list:\n node_list = collections.deque(cl)\n else:\n return [n]\n\n subtree_leaves = []\n while len(node_list) != 0:\n n = node_list.popleft()\n cl = self.df.loc[n,'child_indices']\n if type(cl)==list:\n if len(cl)>1:\n node_list.extendleft(cl)\n elif len(cl) == 1:\n node_list.appendleft(cl[0])\n else:\n subtree_leaves.append(n)\n return subtree_leaves\n\n\n def get_farthest_subtree_leaf_dist(self,n):\n \"\"\"Given node index n, return distance of farthest leaf in subtree starting from n\"\"\"\n subtree_leaves= self.get_subtree_leaves(n)\n if len(subtree_leaves)==1:\n return self.df.loc[subtree_leaves,'euc_dist_to_root']\n else:\n return self.df.loc[subtree_leaves,'euc_dist_to_root'].sort_values()[-1:]\n\n\n def get_persistence_barcode(self):\n \"\"\"Implement persistence barcode analysis\"\"\"\n D_t = []\n active_list = list(self.get_terminal_nodes())\n v_ = collections.defaultdict()\n for l in active_list:\n v_[l] = self.df.loc[l,'euc_dist_to_root']\n while self.root_index not in active_list:\n for l in active_list:\n p = self.get_parent_branch(l) #*make hash\n C = self.get_child_nodes(p) # immediate branches or leaves below p\n if all([n in active_list for n in C]):\n vc_ = dict((k,v_[k]) for k in C)\n c_m = max(vc_.items(), key=operator.itemgetter(1))[0]\n active_list.append(p)\n for c in C:\n active_list.remove(c)\n if c != c_m:\n D_t.append((v_[c], self.df.loc[p,'euc_dist_to_root']))\n v_[p] = v_[c_m]\n D_t.append((v_[self.root_index],self.df.loc[self.root_index,'euc_dist_to_root']))\n return np.array(D_t)\n\n def barcode_density_profile(self):\n pass\n\n def plot_morphology(self):\n \"\"\"Retrieve 2d snapshot if available (if not, render) and plot\"\"\"\n pass\n\ndef create_persistence_image(pbcode, plot=True):\n \"\"\"Given persistence barcode, create persistence image\"\"\"\n X_grid, Y_grid = np.mgrid[0:150:400j,0:150:400j]\n grid = np.vstack([X_grid.ravel(),Y_grid.ravel()])\n val = np.array([*zip(*pbcode)])\n skl_kernel = KernelDensity(bandwidth=9)\n skl_kernel.fit(val.T)\n Zs = np.exp(skl_kernel.score_samples(grid.T))\n if plot:\n ax = plt.subplot()\n v0,v1 = np.array([*zip(*list(pbcode))])\n plt.imshow(np.rot90(Zs.reshape(400,-1)), cmap=plt.cm.RdYlBu_r, extent=[0, 150, 0, 150])\n plt.plot( v0, v1, 'k.', markersize=2)\n ax.set_xlim([0, 150])\n ax.set_ylim([0, 150])\n return Zs\n","sub_path":"src/swcfunctions.py","file_name":"swcfunctions.py","file_ext":"py","file_size_in_byte":10566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"89957779","text":"import os\nimport sys\nimport glob\nimport json\nimport shutil\n\nfrom tqdm import tqdm\nfrom types import SimpleNamespace\nfrom argparse import ArgumentParser\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\n\ndef clone_repo(repo_url):\n repo_name = repo_url.split('github.com/')[1]\n directory = f'./data/{repo_name}'\n\n os.system(f\"git clone --depth=1 {repo_url} {directory} >/dev/null 2>&1\")\n shutil.rmtree(f\"{directory}/.git\")\n\n # Remove any non python file\n folders = []\n for file in glob.glob(f\"{directory}/**\", recursive=True):\n\n if os.path.isdir(file):\n folders.append(file)\n if not os.path.isdir(file) and not (file.endswith('.py') or file.endswith('.ipynb')):\n os.remove(file)\n\n # Run command to convert notebooks into .py\n if file.endswith('.ipynb'):\n os.system(\n f\"jupyter nbconvert --to script {file} >/dev/null 2>&1\")\n os.remove(file)\n\n # Tidy up, removing empty folders\n for folder in folders:\n if len(os.listdir(folder)) == 0:\n os.removedirs(folder)\n\n\ndef start_async_download(repositories):\n with tqdm(total=len(repositories), unit=' Repositories', desc='Downloading repositories') as pbar:\n with ThreadPoolExecutor(max_workers=10) as executor:\n tasks = {executor.submit(\n clone_repo, url): url for url in repositories}\n\n for task in as_completed(tasks):\n pbar.update(1)\n\n\nif __name__ == \"__main__\":\n\n parser = ArgumentParser()\n parser.add_argument(\"-f\", \"--file\", dest=\"file\", type=str,\n help=\"The json file containing links to repositories to download\", required=True)\n parser.add_argument(\"-n\", \"--num_repos\", dest=\"num_repositories\", type=int,\n help=\"The maximum number of repositories to download\", required=False)\n\n args = parser.parse_args()\n\n # Read repository urls from json file\n with open(args.file, 'r') as file:\n repositories = json.loads(\n file.read(), object_hook=lambda d: SimpleNamespace(**d))\n\n # Filter out any eventual links to non-github repos\n repositories = list(set([repository.repo_url for repository in repositories if (\n 'github.com/' in repository.repo_url)]))\n\n if args.num_repositories is not None:\n repositories = repositories[:args.num_repositories]\n\n start_async_download(repositories)\n print(\"Done cloning.\")\n","sub_path":"downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"510766769","text":"import requests\nimport matplotlib.pyplot as plt\nimport os\nimport sqlite3\n\ndef mkdir(s):\n if not os.path.exists(s):\n os.mkdir(s)\n\ndef download_image():\n while not Q.empty():\n task = Q.get()\n print(task[1][-2])\n imgLinks = eval(task[1][-2])\n if not imgLinks:\n Q.task_done()\n continue\n else:\n link = 'https:' + imgLinks[0]\n success = False\n for n_trait in range(5):\n # 至多尝试5次重复下载\n try:\n re = requests.get(link)\n except BaseException as e:\n print(f'{task[0]}: exception: {e}: n_trait={n_trait}')\n n_trait += 1\n else:\n success = True\n break\n if not success:\n Q.task_done()\n continue\n else:\n file_path = f'imgs/{task[1][-1]}/{task[0]}.jpg'\n mkdir(file_path)\n content = re.content\n with open(file_path, 'wb') as fw:\n fw.write(content)\n Q.task_done()\n\ndb = sqlite3.connect('data/MSN_ALL.db')\nallData = db.execute('SELECT * FROM MSN')\nallData = list(allData)\n\nmkdir('imgs')\nmkdir('imgs/politics')\nmkdir('imgs/technology')\n\n# 修改此处以改变起始/结束的地方\n\nstart = 0\nend = 100\n\nimport threading\nimport queue\n\nN_THREADS = 8\nthread_pool = []\nQ = queue.Queue()\n\nfor i, x in enumerate(allData[start : end]):\n Q.put((i + start, x))\n\nfor i in range(N_THREADS):\n t = threading.Thread(target=download_image)\n t.setDaemon(True)\n thread_pool.append(t)\n t.start()\n\nQ.join()","sub_path":"lab2&3/code/downloadImage.py","file_name":"downloadImage.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"513084895","text":"#-*- coding:utf-8 _*-\n\"\"\"\n @author:小胡\n @file: Homework_requests_testcase.py\n @time: 2019/03/22\n \n \"\"\"\n\n#总结 调用测试类的时候,一定要先创建对象之后,才能调用\n\"\"\"\n第一步:先导入 import unittest 导入要测试的方法类\n第二步:编写测试用例类,一定要继承unittest.TestCase类\n第三步:编写测试用例,一定要用test开头,不然执行不出来\n第四步:在测试用例里面,编写期望值,实际值,实际值是导入的方法类,\n一定要在类名后面加()创建对象,传参数,之后用assert断言\n第五步:新建模块,使用suite存储用例,先导入import unittest\n第六步:创建个TestSuite类的对象TestSuite(),创建对象,才能调用方法\n第七步:有三种方法来加载用例\n1:一个一个加,导入所有测试类,用TestSuite()调用addTest()方法\n2:使用Loader来加载,导入模块,创建个TestLoader类的对象TestLoader(),来调用LoadTestsFromModule方法\n3:使用Loader来加载,导入所有测试类,创建个TestLoader类的对象TestLoader(),来调用loadTestsFromTestCase方法\n第八步:执行用例,首先要创建个TextTestRunner类的对象TextTestRunner()\n用TextTestRunner()调用run方法使用Suite\nTextTestRunner().run(Suite)\n\n\"\"\"\nimport unittest\nimport json\nfrom week_6.class_0321_readme.class_requests import HttpRequests\n\n\nclass TestHttpGet(unittest.TestCase):\n def test_001(self):\n print('http_requests_get_one')\n expected=\"登录成功\"\n url = 'http://47.107.168.87:8080/futureloan/mvc/api/member/login'\n params = {'mobilephone': '18688773467', 'pwd': '123456'}\n res=HttpRequests(url,params,'get').httprequests().text\n self.assertIn(expected,res)\n def test_002(self):\n print('http_requests_get_two')\n expected=\"用户名或密码错误\"\n url = 'http://47.107.168.87:8080/futureloan/mvc/api/member/login'\n params = {'mobilephone': '18688773467', 'pwd': '12345678'}\n res=HttpRequests(url,params,'get').httprequests().text\n self.assertIn(expected,res)\nclass TestHttpPost(unittest.TestCase):\n def test_001(self):\n print('http_requests_post_one')\n expected=\"手机号不能为空\"\n url = 'http://47.107.168.87:8080/futureloan/mvc/api/member/login'\n res=HttpRequests(url, '{\"mobilephone\":\"\",\"pwd\":\"123456\"}', 'post').httprequests().text\n self.assertIn(expected,res)\n def test_002(self):\n print('http_requests_post_two')\n expected=\"登录成功\"\n url = 'http://47.107.168.87:8080/futureloan/mvc/api/member/login'\n res=HttpRequests(url,json.loads('{\"mobilephone\":\"18688773467\",\"pwd\":\"123456\"}'),'post').httprequests().text\n self.assertIn(expected,res)\n","sub_path":"Task/class_http_requests/Homework_requests_testcase.py","file_name":"Homework_requests_testcase.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"203970324","text":"from app import app\nfrom flask import flash, request\nimport sqlhelper\nfrom authhelper import require_appkey\n\n@app.route('/projectfunder', methods=['POST'])\n@require_appkey\ndef projectfunder_add():\n try:\n content = request.json\n _projectid = content['ProjectId']\n _categoryid = content['FunderId']\n _amount = content['AmountFunded']\n\n sql = \"CALL usp_AddFunderToProject(%s, %s, %s)\"\n data = (_projectid, _categoryid, _amount,)\n resp = sqlhelper.do_writedata(sql, data)\n resp.status_code = 200\n return resp\n except Exception as e:\n print(e) \n\n@app.route('/projectfunder/<int:id>', methods=['DELETE'])\n@require_appkey\ndef delete_projectfunder(id):\n try:\n sql = \"CALL usp_RemoveFunderFromProject(%s)\"\n data = (id,)\n resp = sqlhelper.do_writedata(sql, data)\n resp.status_code = 200\n return resp\n except Exception as e:\n print(e)\n\n@app.route('/projectfunder/<int:projectid>', methods=['GET'])\n@require_appkey\ndef projectfunder(projectid):\n try:\n resp = sqlhelper.do_selectmultibyid(\"CALL usp_GetFundersForProject(%s)\", projectid)\n resp.status_code = 200\n return resp\n except Exception as e:\n print(e)","sub_path":"tdt_crud/projectfunders.py","file_name":"projectfunders.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"131159303","text":"#! /usr/bin/python3\nimport requests\nfrom bs4 import BeautifulSoup\nimport pyperclip\n'''\nprint ('Select your torrent search engine:')\nprint ('Enter 1 to search on pirate bay')\nprint ('Enter 2 to search on kickass')\nprint ('Enter 3 to search on extratorrent')\nwhile True:\n select = input()\n if select != '1' and select != '2' and select != '3':\n print ('Enter correct input')\n continue\n else:\n break\nselect = int(select)'''\n \nprint ('Enter search term:',end=' ')\nsearch = input()\nlist = []\nprint ('Piratebay:') \nprint () \nurl = 'https://thepiratebay.se/search/'+search+'/0/99/0' \nsource_code = requests.get(url)\nsoup = BeautifulSoup(source_code.text,'lxml')\ni = 0\nj = 1\nfor search_item in soup.findAll('a',{'class':'detLink'}):\n list.append(search_item.get('href'))\n seeds = soup.findAll('td',{'align':'right'})\n leeches = soup.findAll('td',{'align':'right'})\n print (str(j)+'. '+search_item.text,seeds[i].text,leeches[i+1].text)\n i += 2\n j += 1\n if j > 10:\n break\nprint ()\nprint ('Kickass Torrents')\nprint ()\nurl = 'https://kickass.unblocked.li/usearch/'+search \nsource_code = requests.get(url)\nsoup = BeautifulSoup(source_code.text,'lxml') \ni = 1\nfor search_item in soup.findAll('a',{'class':'cellMainLink'}):\n list.append(search_item.get('href'))\n size = soup.findAll('td',{'class':'nobr center'})\n seeds = soup.findAll('td',{'class':'green center'})\n leeches = soup.findAll('td',{'class':'red lasttd center'})\n print (str(j)+'. '+search_item.text,size[i-1].text,seeds[i-1].text,leeches[i-1].text)\n i += 1\n j += 1\n if j > 20:\n break\nprint ()\nprint ('Extratorrent')\nprint ()\nurl = 'https://thepiratebay.se/search/'+search+'/0/99/0' \nsource_code = requests.get(url)\nsoup = BeautifulSoup(source_code.text,'lxml')\ni = 1\nfor search_item in soup.findAll('td',{'class':'tli'}):\n list.append(search_item.find('a').get('href'))\n seeds = soup.findAll('td',{'class':'sy'})\n leeches = soup.findAll('td',{'class':'ly'})\n if len(search_item.find_all('a')[0].text) < 4:\n search_item = search_item.find_all('a')[1].text\n else:\n search_item = search_item.find_all('a')[0].text\n print (str(j)+'. '+search_item,seeds[i-1].text,leeches[i-1].text)\n i += 1\n j += 1\n if j > 30:\n break\nwhile True:\n try:\n user_input = int(input('Enter the number of the file to download: '))\n except ValueError:\n print ('Enter correct input')\n continue\n if user_input < 1 or user_input > 30:\n print ('Enter correct input')\n continue\n else:\n break\nif 1 <= user_input <= 10:\n url = 'https://thepiratebay.se'+list[user_input - 1] \n source_code = requests.get(url)\n soup = BeautifulSoup(source_code.text,'lxml')\n magnet = soup.findAll('a',{'title':'Get this torrent'})\n pyperclip.copy(magnet[0].get('href'))\n print ('Magnet Link Copied')\n \nelif 11 <= user_input <= 20:\n url = 'https://kickass.unblocked.li'+list[user_input - 1] \n source_code = requests.get(url)\n soup = BeautifulSoup(source_code.text,'lxml')\n for magnet in soup.findAll('a',{'class':'kaGiantButton '}):\n pyperclip.copy(magnet.get('href'))\n print ('Magnet link Copied')\nelif 20 <= user_input <= 30:\n url = 'http://www.extratorrent.date'+list[user_input - 1] \n source_code = requests.get(url)\n soup = BeautifulSoup(source_code.text,'lxml')\n for magnet in soup.findAll('a',{'title':'Magnet link'}):\n pyperclip.copy(magnet.get('href'))\n print ('Magnet link Copied')\n","sub_path":"torrent.py","file_name":"torrent.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"200701644","text":"# -*- coding: utf-8 -*-\n\nfrom functools import wraps\nfrom .errors import ValidationError\n\n\ndef validator(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n fail = kwargs.get('fail', False)\n if 'fail' in kwargs:\n del kwargs['fail']\n valid = func(*args, **kwargs)\n if not valid:\n error = ValidationError(func, args)\n if fail:\n raise error\n return error\n return True\n return wrapper\n","sub_path":"seemslegit/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"166840598","text":"#!/usr/bin/env python\n\nimport time\nimport boto.ec2\nimport re\nimport ConfigParser\n\nfrom fabric.api import *\n\ndef connect():\n config = ConfigParser.ConfigParser()\n config.read('blink.cfg')\n\n aws_key = config.get('aws', 'aws_key')\n aws_secret = config.get('aws', 'aws_secret')\n\n conn = boto.ec2.connect_to_region(\n 'us-east-1',\n aws_access_key_id=aws_key,\n aws_secret_access_key=aws_secret,\n )\n\n return conn\n\ndef find_blink_instances():\n conn = connect()\n\n reservations = conn.get_all_instances()\n\n name_matcher = re.compile('blink slave \\d+')\n\n for reservation in reservations:\n for instance in reservation.instances:\n if instance.state != 'running':\n continue\n if 'Name' in instance.tags:\n if name_matcher.match(instance.tags['Name']) is not None:\n yield instance\n\ninstances = list(find_blink_instances())\nenv.user = 'ubuntu'\nenv.hosts = [i.public_dns_name for i in instances]\nenv.key_filename = '/home/kmatzen/kmatzenvision.pem'\n\n@task\ndef hostname():\n run('hostname')\n\n@task\ndef upgrade():\n install()\n with cd('blink'):\n run('git pull')\n stop()\n start()\n\n@task\ndef install():\n try:\n run('ls blink')\n except:\n run('git clone https://github.com/kmatzen/blink.git')\n configure()\n\n@task\ndef configure():\n put('blink.cfg', 'blink/blink.cfg')\n\n@task\ndef stop():\n run('tmux kill-session -t blink', warn_only=True)\n\n@task\ndef start():\n with cd('blink'):\n run('tmux new-session -d -s blink ./fetch.py', pty=False)\n\n@task\ndef status():\n run('ps aux|grep python')\n\n@task\n@hosts('localhost')\ndef add_instance(count):\n conn = connect()\n config = ConfigParser.ConfigParser()\n config.read('blink.cfg')\n ami = config.get('aws', 'ami')\n spot_price = config.getfloat('aws', 'spot_price')\n key_name = config.get('aws', 'key_name')\n instance_type = config.get('aws', 'instance_type')\n availability_zone_group = config.get('aws', 'availability_zone_group')\n security_group = config.get('aws', 'security_group')\n\n reservation = conn.request_spot_instances(\n spot_price, \n ami, \n count=count,\n key_name=key_name, \n instance_type=instance_type, \n availability_zone_group=availability_zone_group, \n security_groups=[security_group]\n )\n \n spot_ids = [s.id for s in reservation]\n \n while True:\n ready = True\n \n try: \n for r in conn.get_all_spot_instance_requests(spot_ids):\n print('Code: %s'%r.status.code)\n print('Update time: %s'%r.status.update_time)\n print('Message: %s'%r.status.message)\n if r.status.code != 'fulfilled':\n ready = False\n\n if ready:\n break\n except:\n pass\n\n time.sleep(1)\n\n existing = set()\n\n name_matcher = re.compile('blink slave (\\d+)')\n for instance in instances:\n name = instance.tags['Name']\n groups = name_matcher.match(name).groups()\n num = int(groups[0])\n existing.add(num)\n\n while True:\n ready = True\n\n for r in conn.get_all_spot_instance_requests(spot_ids):\n instance_id = r.instance_id\n reservations = conn.get_all_instances(instance_id)\n for reservation in reservations:\n for instance in reservation.instances:\n print('State: %s'%instance.state)\n if instance.state != 'running':\n ready = False\n\n if ready:\n break\n\n time.sleep(1)\n\n for r in conn.get_all_spot_instance_requests(spot_ids):\n instance_id = r.instance_id\n reservations = conn.get_all_instances(instance_id)\n for reservation in reservations:\n for instance in reservation.instances:\n for num in xrange(len(existing)+1):\n if num not in existing:\n new_name = 'blink slave %d'%num\n existing.add(num)\n break\n\n instance.add_tag('Name', new_name)\n print('New node named %s'%new_name)\n","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"39487453","text":"# -*- coding: utf-8 -*-\n\n# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the MIT License.\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# MIT License for more details.\n\n\"\"\"Defined ResNet Blocks For Detection.\"\"\"\nimport torch.nn as nn\nfrom .conv_ws import ConvWS2d\n\nnorm_cfg_dict = {'BN': ('bn', nn.BatchNorm2d),\n 'GN': ('gn', nn.GroupNorm)}\n\nconv_cfg_dict = {'Conv': nn.Conv2d,\n 'ConvWS': ConvWS2d}\n\n\ndef conv3x3(in_planes, out_planes, stride=1, groups=1):\n \"\"\"Generate 3x3 convolution layer.\"\"\"\n return nn.Conv2d(\n in_planes,\n out_planes,\n kernel_size=3,\n stride=stride,\n padding=1,\n groups=groups,\n bias=False,\n )\n\n\ndef conv1x1(in_planes, out_planes, stride=1):\n \"\"\"Generate 1x1 convolution layer.\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n \"\"\"This is the class of BasicBlock block for ResNet.\n\n :param inplanes: input feature map channel num\n :type inplanes: int\n :param planes: output feature map channel num\n :type planes: int\n :param stride: stride\n :type stride: int\n :param dilation: dilation\n :type dilation: int\n :param downsample: downsample\n :param style: style, \"pytorch\" mean 3x3 conv layer and \"caffe\" mean the 1x1 conv layer.\n :type style: str\n :param with_cp: with cp\n :type with_cp: bool\n :param conv_cfg: conv config\n :type conv_cfg: dict\n :param norm_cfg: norm config\n :type norm_cfg: dict\n :param dcn: deformable conv network\n :param gcb: gcb\n :param gen_attention: gen attention\n \"\"\"\n\n expansion = 1\n\n def __init__(self,\n inplanes,\n planes,\n stride=1,\n dilation=1,\n downsample=None,\n style='pytorch',\n with_cp=False,\n conv_cfg={\"type\": 'Conv'},\n norm_cfg={\"type\": 'BN'}):\n \"\"\"Init BasicBlock.\"\"\"\n super(BasicBlock, self).__init__()\n self.expansion = 1\n self.conv_cfg = conv_cfg\n self.norm_cfg = norm_cfg\n requires_grad = self.norm_cfg['requires_grad'] if 'requires_grad' in self.norm_cfg else False\n if self.norm_cfg['type'] == 'BN':\n self.norm1 = norm_cfg_dict[self.norm_cfg['type']][1](planes)\n self.norm2 = norm_cfg_dict[self.norm_cfg['type']][1](planes)\n else:\n self.norm1 = norm_cfg_dict[self.norm_cfg['type']][1](num_channels=planes)\n self.norm2 = norm_cfg_dict[self.norm_cfg['type']][1](num_channels=planes)\n if requires_grad:\n for param in self.norm1.parameters():\n param.requires_grad = requires_grad\n for param in self.norm2.parameters():\n param.requires_grad = requires_grad\n self.norm1_name = norm_cfg_dict[self.norm_cfg['type']][0] + '_1'\n self.norm2_name = norm_cfg_dict[self.norm_cfg['type']][0] + '_2'\n self.conv1 = conv_cfg_dict[self.conv_cfg['type']](inplanes, planes, 3, stride=stride, padding=dilation,\n dilation=dilation, bias=False)\n self.add_module(self.norm1_name, self.norm1)\n self.conv2 = conv_cfg_dict[self.conv_cfg['type']](planes, planes, 3, padding=1, bias=False, )\n self.add_module(self.norm2_name, self.norm2)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.inplanes = inplanes\n self.planes = planes\n self.stride = stride\n self.dilation = dilation\n self.style = style\n assert not with_cp\n\n def forward(self, x):\n \"\"\"Forward compute.\n\n :param x: input feature map\n :type x: torch.Tensor\n :return: output feature map\n :rtype: torch.Tensor\n \"\"\"\n identity = x\n out = self.conv1(x)\n out = self.norm1(out)\n out = self.relu(out)\n out = self.conv2(out)\n out = self.norm2(out)\n if self.downsample is not None:\n identity = self.downsample(x)\n out += identity\n out = self.relu(out)\n return out\n\n\nclass Bottleneck(nn.Module):\n \"\"\"This is the class of Bottleneck block for ResNet.\n\n :param inplanes: input feature map channel num\n :type inplanes: int\n :param planes: output feature map channel num\n :type planes: int\n :param stride: stride\n :type stride: int\n :param dilation: dilation\n :type dilation: int\n :param downsample: downsample\n :param style: style, \"pytorch\" mean 3x3 conv layer and \"caffe\" mean the 1x1 conv layer.\n :type style: str\n :param with_cp: with cp\n :type with_cp: bool\n :param conv_cfg: conv config\n :type conv_cfg: dict\n :param norm_cfg: norm config\n :type norm_cfg: dict\n :param dcn: deformable conv network\n :param gcb: gcb\n :param gen_attention: gen attention\n \"\"\"\n\n expansion = 4\n\n def __init__(self,\n inplanes,\n planes,\n stride=1,\n dilation=1,\n downsample=None,\n style='pytorch',\n with_cp=False,\n conv_cfg={\"type\": 'Conv'},\n norm_cfg={\"type\": 'BN'}):\n \"\"\"Init Bottleneck.\"\"\"\n super(Bottleneck, self).__init__()\n assert style in ['pytorch', 'caffe']\n self.expansion = 4\n self.inplanes = inplanes\n self.planes = planes\n self.stride = stride\n self.dilation = dilation\n self.style = style\n self.with_cp = with_cp\n self.conv_cfg = conv_cfg\n self.norm_cfg = norm_cfg\n requires_grad = self.norm_cfg['requires_grad'] if 'requires_grad' in self.norm_cfg else False\n if self.style == 'pytorch':\n self.conv1_stride = 1\n self.conv2_stride = stride\n else:\n self.conv1_stride = stride\n self.conv2_stride = 1\n if self.norm_cfg['type'] == 'BN':\n self.norm1 = norm_cfg_dict[self.norm_cfg['type']][1](planes)\n self.norm2 = norm_cfg_dict[self.norm_cfg['type']][1](planes)\n self.norm3 = norm_cfg_dict[self.norm_cfg['type']][1](planes * self.expansion)\n else:\n self.norm1 = norm_cfg_dict[self.norm_cfg['type']][1](num_channels=planes)\n self.norm2 = norm_cfg_dict[self.norm_cfg['type']][1](num_channels=planes)\n self.norm3 = norm_cfg_dict[self.norm_cfg['type']][1](planes * self.expansion)\n if requires_grad:\n for param in self.norm1.parameters():\n param.requires_grad = requires_grad\n for param in self.norm2.parameters():\n param.requires_grad = requires_grad\n for param in self.norm3.parameters():\n param.requires_grad = requires_grad\n self.norm1_name = norm_cfg_dict[self.norm_cfg['type']][0] + '_1'\n self.norm2_name = norm_cfg_dict[self.norm_cfg['type']][0] + '_2'\n self.norm3_name = norm_cfg_dict[self.norm_cfg['type']][0] + '_3'\n self.conv1 = conv_cfg_dict[self.conv_cfg['type']](inplanes, planes, kernel_size=1, stride=self.conv1_stride,\n bias=False, )\n self.add_module(self.norm1_name, self.norm1)\n self.with_modulated_dcn = False\n self.conv2 = conv_cfg_dict[self.conv_cfg['type']](planes, planes, kernel_size=3, stride=self.conv2_stride,\n padding=dilation, dilation=dilation, bias=False, )\n self.add_module(self.norm2_name, self.norm2)\n self.conv3 = conv_cfg_dict[self.conv_cfg['type']](planes, planes * self.expansion, kernel_size=1,\n bias=False)\n self.add_module(self.norm3_name, self.norm3)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n\n def forward(self, x):\n \"\"\"Forward compute.\n\n :param x: input feature map\n :type x: torch.Tensor\n :return: out feature map\n :rtype: torch.Tensor\n \"\"\"\n\n def _inner_forward(x):\n \"\"\"Inner forward.\n\n :param x: input feature map\n :type x: torch.Tensor\n :return: out feature map\n :rtype: torch.Tensor\n \"\"\"\n identity = x\n out = self.conv1(x)\n out = self.norm1(out)\n out = self.relu(out)\n if not self.with_dcn:\n out = self.conv2(out)\n elif self.with_modulated_dcn:\n offset_mask = self.conv2_offset(out)\n offset = offset_mask[:, :18 * self.deformable_groups, :, :]\n mask = offset_mask[:, -9 * self.deformable_groups:, :, :]\n mask = mask.sigmoid()\n out = self.conv2(out, offset, mask)\n else:\n offset = self.conv2_offset(out)\n out = self.conv2(out, offset)\n out = self.norm2(out)\n out = self.relu(out)\n if self.with_gen_attention:\n out = self.gen_attention_block(out)\n out = self.conv3(out)\n out = self.norm3(out)\n if self.with_gcb:\n out = self.context_block(out)\n if self.downsample is not None:\n identity = self.downsample(x)\n out += identity\n return out\n\n out = _inner_forward(x)\n out = self.relu(out)\n return out\n\n\ndef make_res_layer(block,\n inplanes,\n planes,\n blocks,\n stride=1,\n dilation=1,\n style='pytorch',\n with_cp=False,\n conv_cfg={\"type\": 'Conv'},\n norm_cfg={\"type\": 'BN'}):\n \"\"\"Build resnet layer.\n\n :param block: Block function\n :type blocks: Bottleneck or BasicBlock\n :param inplanes: input planes\n :type inplanes: int\n :param planes: output planes\n :type planes: int\n :param blocks: num of blocks\n :type block: int\n :param stride: stride of convolution\n :type stride: int\n :param dilation: num of dilation\n :type dilation: int\n :param style: style of bottle neck connect\n :type style: str\n :param with_cp: if with conv cp\n :type with_cp: bool\n :param conv_cfg: convolution config\n :type conv_cfg: dict\n :param norm_cfg: normalization config\n :type norm_cfg: dict\n :return: resnet layer\n :rtype: nn.Sequential\n \"\"\"\n downsample = None\n requires_grad = norm_cfg['requires_grad'] if 'requires_grad' in norm_cfg else False\n if stride != 1 or inplanes != planes * block.expansion:\n conv_layer = conv_cfg_dict[conv_cfg['type']](inplanes, planes * block.expansion, kernel_size=1, stride=stride,\n bias=False)\n norm_layer = norm_cfg_dict[norm_cfg['type']][1](planes * block.expansion)\n if requires_grad:\n for param in norm_layer.parameters():\n param.requires_grad = requires_grad\n downsample = nn.Sequential(conv_layer, norm_layer)\n layers = []\n layers.append(\n block(\n inplanes=inplanes,\n planes=planes,\n stride=stride,\n dilation=dilation,\n downsample=downsample,\n style=style,\n with_cp=with_cp,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg, ))\n inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(\n block(\n inplanes=inplanes,\n planes=planes,\n stride=1,\n dilation=dilation,\n style=style,\n with_cp=with_cp,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg))\n return nn.Sequential(*layers)\n","sub_path":"built-in/TensorFlow/Research/cv/image_classification/Cars_for_TensorFlow/automl/vega/search_space/networks/pytorch/blocks/resnet_block_det.py","file_name":"resnet_block_det.py","file_ext":"py","file_size_in_byte":12203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"339003902","text":"## Evaluate profit.\r\n# Obtain input from user.\r\ncosts = eval(input(\"Enter total costs: \"))\r\nrevenue = eval(input(\"Enter total revenue: \"))\r\n# Determine and display profit or loss.\r\nif costs == revenue:\r\n result = \"Break even.\"\r\nelse:\r\n if costs < revenue:\r\n profit = revenue - costs\r\n result = \"Profit is ${0:,.2f}.\".format(profit)\r\n else:\r\n loss = costs - revenue\r\n result = \"Loss is ${0:,.2f}.\".format(loss)\r\nprint(result)\r\n","sub_path":"Ch03/3-2-5.py","file_name":"3-2-5.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"544066029","text":"from random import randrange, choice\nfrom string import ascii_lowercase\n\n\n\"\"\"\ncreates board file\n\"\"\"\n\ndef create_board(file_path, board_size=100, number_of_snakes=10, number_of_ladders=10, number_of_players=3):\n board = [0]*board_size\n\n info_data = [str(number_of_snakes)]\n\n _curr_snakes=0\n while _curr_snakes < number_of_snakes:\n source = randrange(1, board_size)\n if source-1 <= 1:\n continue\n destination = randrange(1, source-1)\n\n if destination == board_size:\n continue\n\n if board[source] == 0 and board[destination] == 0:\n board[source] = 1\n board[destination] = 1\n info_data.append(str(source)+ \" \" + str(destination))\n _curr_snakes += 1\n\n _curr_ladders=0\n info_data.append(str(number_of_ladders))\n while _curr_ladders < number_of_ladders:\n source = randrange(1, board_size)\n if source+1 >= board_size:\n continue\n destination = randrange(source+1, board_size)\n\n if board[source] == 0 and board[destination] == 0:\n board[source] = 1\n board[destination] = 1\n info_data.append(str(source)+ \" \" + str(destination))\n _curr_ladders += 1\n\n info_data.append(str(number_of_players))\n for i in range(number_of_players):\n name=''.join(choice(ascii_lowercase) for _ in range(6))\n info_data.append(name)\n info_data = (\"\\n\".join(info_data)) \n\n file = open(file_path, 'w')\n file.write(info_data)\n file.close()\n\n","sub_path":"create_board.py","file_name":"create_board.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"435290418","text":"import os\nimport logging\nimport multiprocessing\nfrom multiprocessing.managers import Namespace\nfrom datetime import datetime\nimport time\n\nfrom mynetwork import Net\nfrom mydb import DB\nfrom sso import SSO\nfrom settings import COOKIE_FILE, TIME_BEFORE_EXPIRES\n\nclass Session():\n def __init__(self):\n self.working_dir = os.path.dirname(os.path.realpath(__file__))\n self.net = Net(COOKIE_FILE)\n self.db = DB()\n self.sso = SSO(self.net)\n \n if not self.sso.login():\n logging.error(\"Failed to login to ISP, exiting...\")\n raise RuntimeError(\"Failed to login to ISP\")\n\n # lock used to avoid conflicting accesses of critical data\n self.lock = multiprocessing.RLock()\n \n # Global variable used to save state/info among processes\n manager = multiprocessing.Manager()\n self.core = manager.Namespace()\n self.core.is_reset = False\n self.core.cookie_expires_time = self.get_isp_expires_time()\n\n def will_be_expired(self):\n \"\"\"\n @deprecated since Orion 6.5\n It cannot estimate cookie expire time.\n \"\"\"\n now = int(datetime.now().strftime(\"%s\"))\n #Integer expiry date in seconds since epoch\n remaining_time = self.core.cookie_expires_time - now\n if remaining_time > TIME_BEFORE_EXPIRES:\n logging.debug(\"Session is valid(expires in %dMins later)\" % (remaining_time/60))\n return False\n \n logging.debug(\"Session will be invalid soon in %dmins.\" % (remaining_time/60))\n return True\n \n def is_reset(self):\n if self.core.is_reset:\n return True\n\n return False\n\n def reload(self):\n '''\n Session reload do following things:\n - reload cookie\n - flag the is_reset to be False\n '''\n logging.debug(\"Session Reloading...\")\n with self.lock:\n self.net.reload_cookie()\n self.core.is_reset = False\n \n def reset(self):\n '''\n Session reset do following things:\n - relogin to ISP\n - reload cookie\n - save the latest cookie expires time to global variable\n - falg the is_reset to be True\n '''\n logging.debug(\"Session Resetting...\")\n \n if not self.sso.login():\n logging.error(\"Failed to relogin to ISP, exiting...\")\n return\n \n with self.lock:\n self.net.reload_cookie()\n self.core.cookie_expires_time = self.get_isp_expires_time()\n self.core.is_reset = True\n\n def get_isp_expires_time(self):\n \"\"\"\n Since Orion6.5, it use cookie item\n \"\"\"\n expires_time = -1\n cookie = self.net.get_cookie_item('ORASSO_AUTH_HINT')\n if cookie is None:\n logging.error(\"Failed to get ISP SSO cookie, I assume not signed in.\")\n return expires_time\n \n # cookie item 'ORASSO_AUTH_HIN' has format:\n # v1.0~20130604173127\n if len(cookie.value) <= 5:\n logging.error(\"Invalid SSO cookie, I assume not signed in.\")\n return expires_time\n \n # extract local ISO time and conver it to UTC timestamp \n # fixme: hardcode the timezone to be GMT+8\n local_signin_time = datetime.strptime(cookie.value[5:], \"%Y%m%d%H%M%S\")\n \n # ISO cookie expire in 8 hours after local_signin_time\n expires_time = time.mktime(local_signin_time.timetuple()) + (8 * 60 * 60)\n \n return expires_time\n \n def get_isp_expires_time_v1(self):\n '''\n @deprecated since Orion 6.5\n no 'orion_prod_support_us_abc_com' cookie item exist\n \n Get expire time that ISP need re-login\n \n @return -1 indicates session timeout or not logined in\n @ewruen 0 indicates \n '''\n expires_time = -1\n cookie = self.net.get_cookie_item('orion_prod_support_us_abc_com')\n if cookie is None:\n logging.error(\"Failed to get ISP SSO cookie, I assume not signed in.\")\n return expires_time\n \n return cookie.expires\n \n def get_cookie_dict(self):\n return self.net.cj.get_dict()\n \n def get_cookie_str(self):\n return self.net.cj.dump_to_str(True, True)\n","sub_path":"srportal/spd/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":4351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"636684146","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport ulz\nimport interpolate\nimport flexi, hopr\n\nflshfilepath = \"/home/jmark/projects/stirturb/flexi-sims/whirlpool/turb-unit-128/flash_hdf5_chk_0050.h5\"\nflexfilepath = \"/home/jmark/projects/stirturb/flexi-sims/whirlpool/turb-unit-128/sim_State_0000000.000000000.h5\"\nhoprfilepath = \"/home/jmark/projects/stirturb/flexi-sims/whirlpool/turb-unit-128/sim_mesh.h5\"\n\nflx = flexi.File(flexfilepath, hopr.CartesianMeshFile(hoprfilepath))\nfls = flash.File(flshfilepath)\n\nbox = np.zero(flx.mesh.gridsize)\n\nnpoly = flx.npoly\nntype = flx.nodetype\nnvisu = npoly + 1\n\nxs = np.linspace(0,1,nvisu)\n\nFs = interpolate.lagrange_interpolate_3d_RG(xs,Xs,fs)\n","sub_path":"sandbox/test/t_flexi.py","file_name":"t_flexi.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"489131910","text":"'''\nCreated on 25-Aug-2016\n\n@author: ishan\n'''\nimport json\nfrom flask import Flask, Response\nfrom flask_redis import FlaskRedis\napp = Flask(__name__)\n\napp.config['REDIS_URL'] = 'redis://localhost:6379'\nredis = FlaskRedis(app)\n\n\n# global_list = []\n@app.route(\"/hello\")\ndef hello():\n redis.hmset('session', {'hello':'SETTING HELLO'})\n return Response(json.dumps(redis.hgetall('session')))\n\n\n@app.route(\"/hello_fast\")\ndef hello_fast():\n redis.hmset('session', {'hello_fast':'SETTING HELLO_FAST'})\n return Response(json.dumps(redis.hgetall('session')))\n\nif __name__ == '__main__':\n app.run()","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"106941069","text":"from cx_Freeze import setup, Executable\n\nexecutables = [Executable('sys_security.py',\n targetName='sys_security.exe',\n base='Win32GUI')]\ninclude_files = ['data']\n\noptions = {\n 'build_exe': {\n 'include_msvcr': True,\n 'include_files': include_files,\n }\n}\n\nsetup(name='sys_security',\n version='0.0.1',\n description='Sys_security - lab 1,2',\n executables=executables,\n options=options)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"548499043","text":"from pathlib import Path\n\nfrom ..test_utils import load_data\nfrom .templates import (\n add_test_function_metadata,\n parse_name_function_tested,\n t_erase,\n t_exists,\n t_parse,\n t_remove_and_update,\n t_to_string,\n t_update_content,\n)\n\n\ndef main():\n PATH_TEST_DEF = Path(__file__).parent / \"test_InlineMetadata.json\"\n data = load_data(PATH_TEST_DEF)\n\n for t_fn in [\n t_parse,\n t_to_string,\n t_update_content,\n t_exists,\n t_erase,\n t_remove_and_update,\n ]:\n name_f = parse_name_function_tested(t_fn.__name__)\n test_ids: list[str] = list(data[\"tests\"][f\"tests-{name_f}\"].keys())\n for tid in test_ids:\n add_test_function_metadata(glob=globals(), fn=t_fn, test_id=tid, data=data)\n\n\nmain()\n","sub_path":"test/metadata/test_InlineMetadata.py","file_name":"test_InlineMetadata.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"409984862","text":"import socket, string\nimport time\nimport keyboard\nfrom bs4 import BeautifulSoup\nimport urllib.request\nimport codecs\nimport json\nimport sys\nfrom bottle import route, run, template, static_file, get, post, request, BaseRequest, Bottle, abort\nfrom threading import Thread\nfrom time import sleep\n\n@route('/')\ndef send_static2():\n # return (\"?\")\n return static_file(\"main.html\", root='web/')\n\n@route('/<filename:path>')\ndef send_static(filename):\n return static_file(filename, root='web/')\n\n@route('/clip1', method='POST')\ndef do_uploadc():\n print(\"make the clip u booster\")\n clip(0)\n return \"hehexd\"\n\ndef threadfunc():\n run(host=\"0.0.0.0\", port=8000)\n\nthread = Thread(target = threadfunc)\nthread.daemon = True\nthread.start()\nprint(\"threading worked\")\n\n# Set all the variables necessary to connect to Twitch IRC\nHOST = \"irc.twitch.tv\"\nNICK = \"BungusBot\"\nPORT = 6667\nPASS = \"oauth:yoq3z1p3t3kt4pz1cl4n5nil3zq72a\"\nreadbuffers = []\nMODT = False\n\nstreamers = [\"a_seagull\", \"nl_kripp\", \"riotgames\", \"tsm_theoddone\"]\n# streamers = [\"riotgames\"]\n\nsockets = []\ncounts = []\navgss = []\nchats = []\n\ntest = 0\n\napp = Bottle()\n\n@app.route('/websocket')\ndef handle_websocket():\n wsock = request.environ.get('wsgi.websocket')\n if not wsock:\n abort(400, 'Expected WebSocket request.')\n\n while True:\n time.sleep(0.5)\n wsock.send(json.dumps(avgss))\n # try:\n # message = wsock.receive()\n # wsock.send(\"Your message was: %r\" % message)\n # except WebSocketError:\n # break\n\n\nfrom gevent.pywsgi import WSGIServer\nfrom geventwebsocket import WebSocketError\nfrom geventwebsocket.handler import WebSocketHandler\n\ndef threadfunc2():\n server = WSGIServer((\"0.0.0.0\", 8080), app,\n handler_class=WebSocketHandler)\n server.serve_forever()\n\nthread = Thread(target = threadfunc2)\nthread.daemon = True\nthread.start()\nprint(\"threading worked\")\n\n\n\n\nfor i in range(len(streamers)):\n # Connecting to Twitch IRC by passing credentials and joining a certain channel\n s = socket.socket()\n s.connect((HOST, PORT))\n s.send((\"PASS \" + PASS + \"\\r\\n\").encode())\n s.send((\"NICK \" + NICK + \"\\r\\n\").encode())\n s.send((\"JOIN #%s \\r\\n\" % streamers[i]).encode())\n sockets.append(s);\n counts.append(0);\n avgss.append([]);\n avgss[i].append(1);\n readbuffers.append(\"\");\n\niters = 0\n\nif sys.argv[1] == \"load\":\n avgss = json.load(open('data.txt'))\n iters = 100\n\nstart = time.time()\nskip = 0\n\ndef getVideo(html_doc, name):\n soup = BeautifulSoup(html_doc, 'html.parser')\n video_link = soup.video['src'][:-4]\n test=urllib.request.FancyURLopener()\n test.retrieve(video_link,name+\".mp4\")\n\n\ndef clip(streamerid):\n global chats\n print(\"clipping\")\n\n theiters = iters\n\n with open('%s%d.txt' % (streamers[streamerid], theiters), 'w') as outfile:\n json.dump(chats, outfile)\n #Switch screens from terminal to chrome\n time.sleep(1)\n keyboard.press(59) #ctrl\n keyboard.press(19) #2\n keyboard.release(59)\n keyboard.release(19)\n\n time.sleep(2)\n\n #Open new chrome tab\n keyboard.press(55) #command\n keyboard.press(45) #N\n keyboard.release(55) #command\n keyboard.release(45) #N\n\n time.sleep(2)\n\n #Type streamer URL into chrome search bar\n keyboard.write('twitch.tv/riotgames')\n time.sleep(0.5)\n keyboard.send(36)\n\n #Get Clip\n time.sleep(5)\n\n keyboard.press(58) #alt\n keyboard.press(7) #X\n keyboard.release(58)\n keyboard.release(7)\n time.sleep(15) #there may be some lag in internet speed\n\n #Save\n keyboard.press(55) #command\n keyboard.press(1) #S\n keyboard.release(55)\n keyboard.release(1)\n time.sleep(0.5)\n\n #Write title for clip in finder\n keyboard.write(\"%s%d\" % (streamers[streamerid], theiters))\n keyboard.send(36) #enter\n time.sleep(2)\n\n #Close 2 tabs\n keyboard.press(55) #command\n keyboard.press(13) #W\n keyboard.release(55) #command\n keyboard.release(13) #W\n\n time.sleep(1)\n\n keyboard.press(55) #command\n keyboard.press(13) #W\n keyboard.release(55) #command\n keyboard.release(13) #W\n\n f=codecs.open(\"/Users/kevin/Downloads/%s%d.html\" % (streamers[streamerid], theiters), 'r')\n text = f.read()\n getVideo(text, \"%s%d\" % (streamers[streamerid], theiters))\n print(\"download a clip!!!!!!\")\n skip = 2\n pass\n\nwhile True:\n test += 1\n for i in range(len(streamers)):\n readbuffers[i] = readbuffers[i] + sockets[i].recv(1024).decode('utf-8')\n temp = str.split(readbuffers[i], \"\\n\")\n readbuffers[i] = temp.pop()\n\n for line in temp:\n if (line[0] == \"PING\"):\n sockets[i].send(\"PONG %s\\r\\n\" % line[1])\n else:\n parts = str.split(line, \":\")\n if \"QUIT\" not in parts[1] and \"JOIN\" not in parts[1] and \"PART\" not in parts[1]:\n try:\n message = parts[2][:len(parts[2]) - 1]\n except:\n message = \"\"\n usernamesplit = str.split(parts[1], \"!\")\n username = usernamesplit[0]\n if MODT:\n # print(username + \": \" + message)\n chats.append(username + \": \" + message)\n counts[i] += 1;\n for l in parts:\n if \"End of /NAMES list\" in l:\n MODT = True\n\n if time.time() > start + 10:\n iters += 1\n start = time.time()\n\n with open('data.txt', 'w') as outfile:\n json.dump(avgss, outfile)\n\n for i in range(len(streamers)):\n avg = sum(avgss[i]) / float(len(avgss[i]))\n print(\"streamer %s count: %d, avg: %d\" % (streamers[i], counts[i], avg))\n\n if iters > 10 and counts[i] > avg*1.5 and skip <= 0:\n clip(i)\n avgss[i].append(counts[i]);\n skip = 4\n\n if skip < 2:\n avgss[i].append(counts[i]);\n chats = []\n if(len(avgss[i]) > 10):\n avgss[i].pop()\n else:\n print(\"(skipperino)\")\n skip -= 1;\n\n counts[i] = 0;\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"119892412","text":"import enum\nimport logging\nimport os\nimport platform\nimport sys\nimport textwrap\n\nimport click\n\nimport great_expectations.exceptions as ge_exceptions\nfrom great_expectations import DataContext, rtd_url_ge_version\nfrom great_expectations.cli import toolkit\nfrom great_expectations.cli.pretty_printing import (\n cli_message,\n cli_message_dict,\n display_not_implemented_message_and_exit,\n)\nfrom great_expectations.cli.util import verify_library_dependent_modules\nfrom great_expectations.data_context.types.base import DatasourceConfigSchema\nfrom great_expectations.datasource import (\n PandasDatasource,\n SparkDFDatasource,\n SqlAlchemyDatasource,\n)\nfrom great_expectations.datasource.batch_kwargs_generator import (\n ManualBatchKwargsGenerator,\n)\nfrom great_expectations.exceptions import DatasourceInitializationError\n\nlogger = logging.getLogger(__name__)\n\ntry:\n import sqlalchemy\nexcept ImportError:\n logger.debug(\n \"Unable to load SqlAlchemy context; install optional sqlalchemy dependency for support\"\n )\n sqlalchemy = None\n\n\nclass DatasourceTypes(enum.Enum):\n PANDAS = \"pandas\"\n SQL = \"sql\"\n SPARK = \"spark\"\n # TODO DBT = \"dbt\"\n\n\nMANUAL_GENERATOR_CLASSES = ManualBatchKwargsGenerator\n\n\nclass SupportedDatabases(enum.Enum):\n MYSQL = \"MySQL\"\n POSTGRES = \"Postgres\"\n REDSHIFT = \"Redshift\"\n SNOWFLAKE = \"Snowflake\"\n BIGQUERY = \"BigQuery\"\n OTHER = \"other - Do you have a working SQLAlchemy connection string?\"\n # TODO MSSQL\n\n\n@click.group()\n@click.pass_context\ndef datasource(ctx):\n \"\"\"Datasource operations\"\"\"\n directory: str = toolkit.parse_cli_config_file_location(\n config_file_location=ctx.obj.config_file_location\n ).get(\"directory\")\n context: DataContext = toolkit.load_data_context_with_error_handling(\n directory=directory,\n from_cli_upgrade_command=False,\n )\n # TODO consider moving this all the way up in to the CLIState constructor\n ctx.obj.data_context = context\n\n\n@datasource.command(name=\"new\")\n@click.pass_context\ndef datasource_new(ctx):\n \"\"\"Add a new datasource to the data context.\"\"\"\n display_not_implemented_message_and_exit()\n context = ctx.obj.data_context\n datasource_name, data_source_type = add_datasource(context)\n\n if datasource_name:\n cli_message(\n \"A new datasource '{}' was added to your project.\".format(datasource_name)\n )\n toolkit.send_usage_message(\n data_context=context, event=\"cli.datasource.new\", success=True\n )\n else: # no datasource was created\n toolkit.send_usage_message(\n data_context=context, event=\"cli.datasource.new\", success=False\n )\n sys.exit(1)\n\n\n@datasource.command(name=\"delete\")\n@click.argument(\"datasource\")\n@click.pass_context\ndef delete_datasource(ctx, datasource):\n \"\"\"Delete the datasource specified as an argument\"\"\"\n context = ctx.obj.data_context\n try:\n context.delete_datasource(datasource)\n except ValueError:\n cli_message(\n \"<red>{}</red>\".format(\n \"Datasource {} could not be found.\".format(datasource)\n )\n )\n sys.exit(1)\n try:\n context.get_datasource(datasource)\n except ValueError:\n cli_message(\"<green>{}</green>\".format(\"Datasource deleted successfully.\"))\n sys.exit(1)\n else:\n cli_message(\"<red>{}</red>\".format(\"Datasource not deleted.\"))\n sys.exit(1)\n\n\n@datasource.command(name=\"list\")\n@click.pass_context\ndef datasource_list(ctx):\n \"\"\"List known datasources.\"\"\"\n display_not_implemented_message_and_exit()\n context = ctx.obj.data_context\n datasources = context.list_datasources()\n datasource_count = len(datasources)\n\n if datasource_count == 0:\n list_intro_string = \"No Datasources found\"\n else:\n list_intro_string = _build_datasource_intro_string(datasource_count)\n\n cli_message(list_intro_string)\n for datasource in datasources:\n cli_message(\"\")\n cli_message_dict(datasource)\n\n toolkit.send_usage_message(\n data_context=context, event=\"cli.datasource.list\", success=True\n )\n\n\ndef _build_datasource_intro_string(datasource_count):\n if datasource_count == 1:\n list_intro_string = \"1 Datasource found:\"\n if datasource_count > 1:\n list_intro_string = f\"{datasource_count} Datasources found:\"\n return list_intro_string\n\n\ndef add_datasource(context, choose_one_data_asset=False):\n \"\"\"\n Interactive flow for adding a datasource to an existing context.\n\n :param context:\n :param choose_one_data_asset: optional - if True, this signals the method that the intent\n is to let user choose just one data asset (e.g., a file) and there is no need\n to configure a batch kwargs generator that comprehensively scans the datasource for data assets\n :return: a tuple: datasource_name, data_source_type\n \"\"\"\n\n msg_prompt_where_is_your_data = \"\"\"\nWhat data would you like Great Expectations to connect to?\n 1. Files on a filesystem (for processing with Pandas or Spark)\n 2. Relational database (SQL)\n\"\"\"\n\n msg_prompt_files_compute_engine = \"\"\"\nWhat are you processing your files with?\n 1. Pandas\n 2. PySpark\n\"\"\"\n\n data_source_location_selection = click.prompt(\n msg_prompt_where_is_your_data, type=click.Choice([\"1\", \"2\"]), show_choices=False\n )\n\n datasource_name = None\n data_source_type = None\n\n if data_source_location_selection == \"1\":\n data_source_compute_selection = click.prompt(\n msg_prompt_files_compute_engine,\n type=click.Choice([\"1\", \"2\"]),\n show_choices=False,\n )\n\n if data_source_compute_selection == \"1\": # pandas\n\n data_source_type = DatasourceTypes.PANDAS\n\n datasource_name = _add_pandas_datasource(\n context, passthrough_generator_only=choose_one_data_asset\n )\n\n elif data_source_compute_selection == \"2\": # Spark\n\n data_source_type = DatasourceTypes.SPARK\n\n datasource_name = _add_spark_datasource(\n context, passthrough_generator_only=choose_one_data_asset\n )\n else:\n data_source_type = DatasourceTypes.SQL\n datasource_name = _add_sqlalchemy_datasource(context)\n\n return datasource_name, data_source_type\n\n\ndef _add_pandas_datasource(\n context, passthrough_generator_only=True, prompt_for_datasource_name=True\n):\n toolkit.send_usage_message(\n data_context=context,\n event=\"cli.new_ds_choice\",\n event_payload={\"type\": \"pandas\"},\n success=True,\n )\n\n if passthrough_generator_only:\n datasource_name = \"files_datasource\"\n configuration = PandasDatasource.build_configuration()\n\n else:\n path = click.prompt(\n msg_prompt_filesys_enter_base_path,\n type=click.Path(exists=True, file_okay=False),\n )\n\n if path.startswith(\"./\"):\n path = path[2:]\n\n if path.endswith(\"/\"):\n basenamepath = path[:-1]\n else:\n basenamepath = path\n\n datasource_name = os.path.basename(basenamepath) + \"__dir\"\n if prompt_for_datasource_name:\n datasource_name = click.prompt(\n msg_prompt_datasource_name, default=datasource_name\n )\n\n configuration = PandasDatasource.build_configuration(\n batch_kwargs_generators={\n \"subdir_reader\": {\n \"class_name\": \"SubdirReaderBatchKwargsGenerator\",\n \"base_directory\": os.path.join(\"..\", path),\n }\n }\n )\n\n configuration[\"class_name\"] = \"PandasDatasource\"\n configuration[\"module_name\"] = \"great_expectations.datasource\"\n errors = DatasourceConfigSchema().validate(configuration)\n if len(errors) != 0:\n raise ge_exceptions.GreatExpectationsError(\n \"Invalid Datasource configuration: {:s}\".format(errors)\n )\n\n cli_message(\n \"\"\"\nGreat Expectations will now add a new Datasource '{:s}' to your deployment, by adding this entry to your great_expectations.yml:\n\n{:s}\n\"\"\".format(\n datasource_name,\n textwrap.indent(toolkit.yaml.dump({datasource_name: configuration}), \" \"),\n )\n )\n\n toolkit.confirm_proceed_or_exit(\n continuation_message=\"Okay, exiting now. To learn more about adding datasources, run great_expectations \"\n \"datasource --help or visit https://docs.greatexpectations.io/\"\n )\n\n context.add_datasource(name=datasource_name, **configuration)\n return datasource_name\n\n\ndef _add_sqlalchemy_datasource(context, prompt_for_datasource_name=True):\n\n msg_success_database = (\n \"\\n<green>Great Expectations connected to your database!</green>\"\n )\n\n if not _verify_sqlalchemy_dependent_modules():\n return None\n\n db_choices = [str(x) for x in list(range(1, 1 + len(SupportedDatabases)))]\n selected_database = (\n int(\n click.prompt(\n msg_prompt_choose_database,\n type=click.Choice(db_choices),\n show_choices=False,\n )\n )\n - 1\n ) # don't show user a zero index list :)\n\n selected_database = list(SupportedDatabases)[selected_database]\n\n toolkit.send_usage_message(\n data_context=context,\n event=\"cli.new_ds_choice\",\n event_payload={\"type\": \"sqlalchemy\", \"db\": selected_database.name},\n success=True,\n )\n\n datasource_name = \"my_{}_db\".format(selected_database.value.lower())\n if selected_database == SupportedDatabases.OTHER:\n datasource_name = \"my_database\"\n if prompt_for_datasource_name:\n datasource_name = click.prompt(\n msg_prompt_datasource_name, default=datasource_name\n )\n\n credentials = {}\n # Since we don't want to save the database credentials in the config file that will be\n # committed in the repo, we will use our Variable Substitution feature to store the credentials\n # in the credentials file (that will not be committed, since it is in the uncommitted directory)\n # with the datasource's name as the variable name.\n # The value of the datasource's \"credentials\" key in the config file (great_expectations.yml) will\n # be ${datasource name}.\n # Great Expectations will replace the ${datasource name} with the value from the credentials file in runtime.\n\n while True:\n cli_message(msg_db_config.format(datasource_name))\n\n if selected_database == SupportedDatabases.MYSQL:\n if not _verify_mysql_dependent_modules():\n return None\n\n credentials = _collect_mysql_credentials(default_credentials=credentials)\n elif selected_database == SupportedDatabases.POSTGRES:\n if not _verify_postgresql_dependent_modules():\n return None\n\n credentials = _collect_postgres_credentials(default_credentials=credentials)\n elif selected_database == SupportedDatabases.REDSHIFT:\n if not _verify_redshift_dependent_modules():\n return None\n\n credentials = _collect_redshift_credentials(default_credentials=credentials)\n elif selected_database == SupportedDatabases.SNOWFLAKE:\n if not _verify_snowflake_dependent_modules():\n return None\n\n credentials = _collect_snowflake_credentials(\n default_credentials=credentials\n )\n elif selected_database == SupportedDatabases.BIGQUERY:\n if not _verify_bigquery_dependent_modules():\n return None\n\n credentials = _collect_bigquery_credentials(default_credentials=credentials)\n elif selected_database == SupportedDatabases.OTHER:\n sqlalchemy_url = click.prompt(\n \"\"\"What is the url/connection string for the sqlalchemy connection?\n(reference: https://docs.sqlalchemy.org/en/latest/core/engines.html#database-urls)\n\"\"\",\n show_default=False,\n ).strip()\n credentials = {\"url\": sqlalchemy_url}\n\n context.save_config_variable(datasource_name, credentials)\n\n message = \"\"\"\n<red>Cannot connect to the database.</red>\n - Please check your environment and the configuration you provided.\n - Database Error: {0:s}\"\"\"\n try:\n cli_message(\n \"<cyan>Attempting to connect to your database. This may take a moment...</cyan>\"\n )\n\n configuration = SqlAlchemyDatasource.build_configuration(\n credentials=\"${\" + datasource_name + \"}\"\n )\n\n configuration[\"class_name\"] = \"SqlAlchemyDatasource\"\n configuration[\"module_name\"] = \"great_expectations.datasource\"\n errors = DatasourceConfigSchema().validate(configuration)\n if len(errors) != 0:\n raise ge_exceptions.GreatExpectationsError(\n \"Invalid Datasource configuration: {:s}\".format(errors)\n )\n\n cli_message(\n \"\"\"\nGreat Expectations will now add a new Datasource '{0:s}' to your deployment, by adding this entry to your great_expectations.yml:\n\n{1:s}\nThe credentials will be saved in uncommitted/config_variables.yml under the key '{0:s}'\n\"\"\".format(\n datasource_name,\n textwrap.indent(\n toolkit.yaml.dump({datasource_name: configuration}), \" \"\n ),\n )\n )\n\n toolkit.confirm_proceed_or_exit()\n context.add_datasource(name=datasource_name, **configuration)\n cli_message(msg_success_database)\n break\n except ModuleNotFoundError as de:\n cli_message(message.format(str(de)))\n return None\n\n except DatasourceInitializationError as de:\n cli_message(message.format(str(de)))\n if not click.confirm(\"Enter the credentials again?\", default=True):\n context.add_datasource(\n datasource_name,\n initialize=False,\n module_name=\"great_expectations.datasource\",\n class_name=\"SqlAlchemyDatasource\",\n data_asset_type={\"class_name\": \"SqlAlchemyDataset\"},\n credentials=\"${\" + datasource_name + \"}\",\n )\n # TODO this message about continuing may not be accurate\n cli_message(\n \"\"\"\nWe saved datasource {:s} in {:s} and the credentials you entered in {:s}.\nSince we could not connect to the database, you can complete troubleshooting in the configuration files documented in the how-to guides here:\n<blue>https://docs.greatexpectations.io/en/latest/guides/how_to_guides/configuring_datasources.html?utm_source=cli&utm_medium=init&utm_campaign={:s}#{:s}</blue> .\n\nAfter you connect to the datasource, run great_expectations init to continue.\n\n\"\"\".format(\n datasource_name,\n DataContext.GE_YML,\n context.get_config()[\"config_variables_file_path\"],\n rtd_url_ge_version,\n selected_database.value.lower(),\n )\n )\n return None\n\n return datasource_name\n\n\ndef _should_hide_input():\n \"\"\"\n This is a workaround to help identify Windows and adjust the prompts accordingly\n since hidden prompts may freeze in certain Windows terminals\n \"\"\"\n if \"windows\" in platform.platform().lower():\n return False\n return True\n\n\ndef _collect_postgres_credentials(default_credentials=None):\n if default_credentials is None:\n default_credentials = {}\n\n credentials = {\"drivername\": \"postgresql\"}\n\n db_hostname = os.getenv(\"GE_TEST_LOCAL_DB_HOSTNAME\", \"localhost\")\n credentials[\"host\"] = click.prompt(\n \"What is the host for the postgres connection?\",\n default=default_credentials.get(\"host\", db_hostname),\n ).strip()\n credentials[\"port\"] = click.prompt(\n \"What is the port for the postgres connection?\",\n default=default_credentials.get(\"port\", \"5432\"),\n ).strip()\n credentials[\"username\"] = click.prompt(\n \"What is the username for the postgres connection?\",\n default=default_credentials.get(\"username\", \"postgres\"),\n ).strip()\n # This is a minimal workaround we're doing to deal with hidden input problems using Git Bash on Windows\n # TODO: Revisit this if we decide to fully support Windows and identify if there is a better solution\n credentials[\"password\"] = click.prompt(\n \"What is the password for the postgres connection?\",\n default=\"\",\n show_default=False,\n hide_input=_should_hide_input(),\n )\n credentials[\"database\"] = click.prompt(\n \"What is the database name for the postgres connection?\",\n default=default_credentials.get(\"database\", \"postgres\"),\n show_default=True,\n ).strip()\n\n return credentials\n\n\ndef _collect_snowflake_credentials(default_credentials=None):\n if default_credentials is None:\n default_credentials = {}\n credentials = {\"drivername\": \"snowflake\"}\n\n auth_method = click.prompt(\n \"\"\"What authentication method would you like to use?\n 1. User and Password\n 2. Single sign-on (SSO)\n 3. Key pair authentication\n\"\"\",\n type=click.Choice([\"1\", \"2\", \"3\"]),\n show_choices=False,\n )\n\n credentials[\"username\"] = click.prompt(\n \"What is the user login name for the snowflake connection?\",\n default=default_credentials.get(\"username\", \"\"),\n ).strip()\n\n credentials[\"host\"] = click.prompt(\n \"What is the account name for the snowflake connection (include region -- ex \"\n \"'ABCD.us-east-1')?\",\n default=default_credentials.get(\"host\", \"\"),\n ).strip()\n\n database = click.prompt(\n \"What is database name for the snowflake connection? (optional -- leave blank for none)\",\n default=default_credentials.get(\"database\", \"\"),\n ).strip()\n if len(database) > 0:\n credentials[\"database\"] = database\n\n credentials[\"query\"] = {}\n schema = click.prompt(\n \"What is schema name for the snowflake connection? (optional -- leave \"\n \"blank for none)\",\n default=default_credentials.get(\"schema_name\", \"\"),\n ).strip()\n\n if len(schema) > 0:\n credentials[\"query\"][\"schema\"] = schema\n warehouse = click.prompt(\n \"What is warehouse name for the snowflake connection? (optional \"\n \"-- leave blank for none)\",\n default=default_credentials.get(\"warehouse\", \"\"),\n ).strip()\n\n if len(warehouse) > 0:\n credentials[\"query\"][\"warehouse\"] = warehouse\n\n role = click.prompt(\n \"What is role name for the snowflake connection? (optional -- leave blank for none)\",\n default=default_credentials.get(\"role\", \"\"),\n ).strip()\n if len(role) > 0:\n credentials[\"query\"][\"role\"] = role\n\n if auth_method == \"1\":\n credentials = {**credentials, **_collect_snowflake_credentials_user_password()}\n elif auth_method == \"2\":\n credentials = {**credentials, **_collect_snowflake_credentials_sso()}\n elif auth_method == \"3\":\n credentials = {**credentials, **_collect_snowflake_credentials_key_pair()}\n return credentials\n\n\ndef _collect_snowflake_credentials_user_password():\n credentials = {}\n\n credentials[\"password\"] = click.prompt(\n \"What is the password for the snowflake connection?\",\n default=\"\",\n show_default=False,\n hide_input=True,\n )\n\n return credentials\n\n\ndef _collect_snowflake_credentials_sso():\n credentials = {}\n\n credentials[\"connect_args\"] = {}\n credentials[\"connect_args\"][\"authenticator\"] = click.prompt(\n \"Valid okta URL or 'externalbrowser' used to connect through SSO\",\n default=\"externalbrowser\",\n show_default=False,\n )\n\n return credentials\n\n\ndef _collect_snowflake_credentials_key_pair():\n credentials = {}\n\n credentials[\"private_key_path\"] = click.prompt(\n \"Path to the private key used for authentication\",\n show_default=False,\n )\n\n credentials[\"private_key_passphrase\"] = click.prompt(\n \"Passphrase for the private key used for authentication (optional -- leave blank for none)\",\n default=\"\",\n show_default=False,\n )\n\n return credentials\n\n\ndef _collect_bigquery_credentials(default_credentials=None):\n sqlalchemy_url = click.prompt(\n \"\"\"What is the SQLAlchemy url/connection string for the BigQuery connection?\n(reference: https://github.com/mxmzdlv/pybigquery#connection-string-parameters)\n\"\"\",\n show_default=False,\n ).strip()\n credentials = {\"url\": sqlalchemy_url}\n\n return credentials\n\n\ndef _collect_mysql_credentials(default_credentials=None):\n # We are insisting on pymysql driver when adding a MySQL datasource through the CLI\n # to avoid overcomplication of this flow.\n # If user wants to use another driver, they must create the sqlalchemy connection\n # URL by themselves in config_variables.yml\n if default_credentials is None:\n default_credentials = {}\n\n credentials = {\"drivername\": \"mysql+pymysql\"}\n\n db_hostname = os.getenv(\"GE_TEST_LOCAL_DB_HOSTNAME\", \"localhost\")\n credentials[\"host\"] = click.prompt(\n \"What is the host for the MySQL connection?\",\n default=default_credentials.get(\"host\", db_hostname),\n ).strip()\n credentials[\"port\"] = click.prompt(\n \"What is the port for the MySQL connection?\",\n default=default_credentials.get(\"port\", \"3306\"),\n ).strip()\n credentials[\"username\"] = click.prompt(\n \"What is the username for the MySQL connection?\",\n default=default_credentials.get(\"username\", \"\"),\n ).strip()\n credentials[\"password\"] = click.prompt(\n \"What is the password for the MySQL connection?\",\n default=\"\",\n show_default=False,\n hide_input=True,\n )\n credentials[\"database\"] = click.prompt(\n \"What is the database name for the MySQL connection?\",\n default=default_credentials.get(\"database\", \"\"),\n ).strip()\n\n return credentials\n\n\ndef _collect_redshift_credentials(default_credentials=None):\n # We are insisting on psycopg2 driver when adding a Redshift datasource through the CLI\n # to avoid overcomplication of this flow.\n # If user wants to use another driver, they must create the sqlalchemy connection\n # URL by themselves in config_variables.yml\n if default_credentials is None:\n default_credentials = {}\n\n credentials = {\"drivername\": \"postgresql+psycopg2\"}\n\n # required\n\n credentials[\"host\"] = click.prompt(\n \"What is the host for the Redshift connection?\",\n default=default_credentials.get(\"host\", \"\"),\n ).strip()\n credentials[\"port\"] = click.prompt(\n \"What is the port for the Redshift connection?\",\n default=default_credentials.get(\"port\", \"5439\"),\n ).strip()\n credentials[\"username\"] = click.prompt(\n \"What is the username for the Redshift connection?\",\n default=default_credentials.get(\"username\", \"\"),\n ).strip()\n # This is a minimal workaround we're doing to deal with hidden input problems using Git Bash on Windows\n # TODO: Revisit this if we decide to fully support Windows and identify if there is a better solution\n credentials[\"password\"] = click.prompt(\n \"What is the password for the Redshift connection?\",\n default=\"\",\n show_default=False,\n hide_input=_should_hide_input(),\n )\n credentials[\"database\"] = click.prompt(\n \"What is the database name for the Redshift connection?\",\n default=default_credentials.get(\"database\", \"\"),\n ).strip()\n\n # optional\n\n credentials[\"query\"] = {}\n credentials[\"query\"][\"sslmode\"] = click.prompt(\n \"What is sslmode name for the Redshift connection?\",\n default=default_credentials.get(\"sslmode\", \"prefer\"),\n )\n\n return credentials\n\n\ndef _add_spark_datasource(\n context, passthrough_generator_only=True, prompt_for_datasource_name=True\n):\n toolkit.send_usage_message(\n data_context=context,\n event=\"cli.new_ds_choice\",\n event_payload={\"type\": \"spark\"},\n success=True,\n )\n\n if not _verify_pyspark_dependent_modules():\n return None\n\n if passthrough_generator_only:\n datasource_name = \"files_spark_datasource\"\n\n # configuration = SparkDFDatasource.build_configuration(batch_kwargs_generators={\n # \"default\": {\n # \"class_name\": \"PassthroughGenerator\",\n # }\n # }\n # )\n configuration = SparkDFDatasource.build_configuration()\n\n else:\n path = click.prompt(\n msg_prompt_filesys_enter_base_path,\n type=click.Path(exists=True, file_okay=False),\n ).strip()\n if path.startswith(\"./\"):\n path = path[2:]\n\n if path.endswith(\"/\"):\n basenamepath = path[:-1]\n else:\n basenamepath = path\n\n datasource_name = os.path.basename(basenamepath) + \"__dir\"\n if prompt_for_datasource_name:\n datasource_name = click.prompt(\n msg_prompt_datasource_name, default=datasource_name\n )\n\n configuration = SparkDFDatasource.build_configuration(\n batch_kwargs_generators={\n \"subdir_reader\": {\n \"class_name\": \"SubdirReaderBatchKwargsGenerator\",\n \"base_directory\": os.path.join(\"..\", path),\n }\n }\n )\n configuration[\"class_name\"] = \"SparkDFDatasource\"\n configuration[\"module_name\"] = \"great_expectations.datasource\"\n errors = DatasourceConfigSchema().validate(configuration)\n if len(errors) != 0:\n raise ge_exceptions.GreatExpectationsError(\n \"Invalid Datasource configuration: {:s}\".format(errors)\n )\n\n cli_message(\n \"\"\"\nGreat Expectations will now add a new Datasource '{:s}' to your deployment, by adding this entry to your great_expectations.yml:\n\n{:s}\n\"\"\".format(\n datasource_name,\n textwrap.indent(toolkit.yaml.dump({datasource_name: configuration}), \" \"),\n )\n )\n toolkit.confirm_proceed_or_exit()\n\n context.add_datasource(name=datasource_name, **configuration)\n return datasource_name\n\n\ndef _verify_sqlalchemy_dependent_modules() -> bool:\n return verify_library_dependent_modules(\n python_import_name=\"sqlalchemy\", pip_library_name=\"sqlalchemy\"\n )\n\n\ndef _verify_mysql_dependent_modules() -> bool:\n return verify_library_dependent_modules(\n python_import_name=\"pymysql\",\n pip_library_name=\"pymysql\",\n module_names_to_reload=CLI_ONLY_SQLALCHEMY_ORDERED_DEPENDENCY_MODULE_NAMES,\n )\n\n\ndef _verify_postgresql_dependent_modules() -> bool:\n psycopg2_success: bool = verify_library_dependent_modules(\n python_import_name=\"psycopg2\",\n pip_library_name=\"psycopg2-binary\",\n module_names_to_reload=CLI_ONLY_SQLALCHEMY_ORDERED_DEPENDENCY_MODULE_NAMES,\n )\n # noinspection SpellCheckingInspection\n postgresql_psycopg2_success: bool = verify_library_dependent_modules(\n python_import_name=\"sqlalchemy.dialects.postgresql.psycopg2\",\n pip_library_name=\"psycopg2-binary\",\n module_names_to_reload=CLI_ONLY_SQLALCHEMY_ORDERED_DEPENDENCY_MODULE_NAMES,\n )\n return psycopg2_success and postgresql_psycopg2_success\n\n\ndef _verify_redshift_dependent_modules() -> bool:\n # noinspection SpellCheckingInspection\n postgresql_success: bool = _verify_postgresql_dependent_modules()\n redshift_success: bool = verify_library_dependent_modules(\n python_import_name=\"sqlalchemy_redshift.dialect\",\n pip_library_name=\"sqlalchemy-redshift\",\n module_names_to_reload=CLI_ONLY_SQLALCHEMY_ORDERED_DEPENDENCY_MODULE_NAMES,\n )\n return redshift_success or postgresql_success\n\n\ndef _verify_snowflake_dependent_modules() -> bool:\n return verify_library_dependent_modules(\n python_import_name=\"snowflake.sqlalchemy.snowdialect\",\n pip_library_name=\"snowflake-sqlalchemy\",\n module_names_to_reload=CLI_ONLY_SQLALCHEMY_ORDERED_DEPENDENCY_MODULE_NAMES,\n )\n\n\ndef _verify_bigquery_dependent_modules() -> bool:\n return verify_library_dependent_modules(\n python_import_name=\"pybigquery.sqlalchemy_bigquery\",\n pip_library_name=\"pybigquery\",\n module_names_to_reload=CLI_ONLY_SQLALCHEMY_ORDERED_DEPENDENCY_MODULE_NAMES,\n )\n\n\ndef _verify_pyspark_dependent_modules() -> bool:\n return verify_library_dependent_modules(\n python_import_name=\"pyspark\", pip_library_name=\"pyspark\"\n )\n\n\ndef skip_prompt_message(skip_flag, prompt_message_text) -> bool:\n\n if not skip_flag:\n return click.confirm(prompt_message_text, default=True)\n\n return skip_flag\n\n\nmsg_prompt_choose_datasource = \"\"\"Configure a datasource:\n 1. Pandas DataFrame\n 2. Relational database (SQL)\n 3. Spark DataFrame\n 4. Skip datasource configuration\n\"\"\"\n\nmsg_prompt_choose_database = \"\"\"\nWhich database backend are you using?\n{}\n\"\"\".format(\n \"\\n\".join(\n [\" {}. {}\".format(i, db.value) for i, db in enumerate(SupportedDatabases, 1)]\n )\n)\n\nmsg_prompt_filesys_enter_base_path = \"\"\"\nEnter the path (relative or absolute) of the root directory where the data files are stored.\n\"\"\"\n\nmsg_prompt_datasource_name = \"\"\"\nGive your new Datasource a short name.\n\"\"\"\n\nmsg_db_config = \"\"\"\nNext, we will configure database credentials and store them in the `{0:s}` section\nof this config file: great_expectations/uncommitted/config_variables.yml:\n\"\"\"\n\nmsg_unknown_data_source = \"\"\"\nDo we not have the type of data source you want?\n - Please create a GitHub issue here so we can discuss it!\n - <blue>https://github.com/great-expectations/great_expectations/issues/new</blue>\"\"\"\n\nCLI_ONLY_SQLALCHEMY_ORDERED_DEPENDENCY_MODULE_NAMES: list = [\n # 'great_expectations.datasource.batch_kwargs_generator.query_batch_kwargs_generator',\n \"great_expectations.datasource.batch_kwargs_generator.table_batch_kwargs_generator\",\n \"great_expectations.dataset.sqlalchemy_dataset\",\n \"great_expectations.validator.validator\",\n \"great_expectations.datasource.sqlalchemy_datasource\",\n]\n","sub_path":"great_expectations/cli/datasource.py","file_name":"datasource.py","file_ext":"py","file_size_in_byte":30463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"548959424","text":"#\n# The MIT License (MIT)\n#\n# Copyright (c) 2020-2021 Dominik Meier\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\n# THE SOFTWARE.\n#\nimport pandas as pd\n\n\ndef load_dataset(filename, sparsify=False):\n mutants_and_tests = pd.read_pickle(filename)\n mutants_and_tests.reset_index()\n mutants_and_tests[\"outcome\"] = mutants_and_tests[\"outcome\"].astype(\"bool\")\n mutants_and_tests[\"outcome\"]\n if sparsify:\n keep_fraction = 0.05 # Keep 5% of the dataset (roughly, since we delete tests and mutants smaller than that)\n max_mutant_id = mutants_and_tests[\"mutant_id\"].max()\n max_test_id = max(\n mutants_and_tests[\"test_id\"].max(), 10\n ) # At least use 10 tests\n return mutants_and_tests.loc[\n mutants_and_tests[\"test_id\"] < max_test_id * keep_fraction\n ].loc[mutants_and_tests[\"mutant_id\"] < max_mutant_id * keep_fraction]\n return mutants_and_tests\n\n\ndef load_datasets(name_and_filename, sparsify=False):\n datasets = {}\n for name, filename in name_and_filename.items():\n datasets[name] = load_dataset(filename, sparsify)\n return datasets\n","sub_path":"src/loading.py","file_name":"loading.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"590355250","text":"import pygame\n\npygame.init() #초기화 (반드시 필요)\n\n# 화면 크기 설정\nscreen_width = 480 #가로크기\nscreen_height = 640 # 세로크기\nscreen = pygame.display.set_mode((screen_width, screen_height))\n\n# 화면 타이틀 설정\npygame.display.set_caption(\"Nado Game\") #게임 \n\n# 배경 이미지 불러오기\nbackground = pygame.image.load(\"/Users/hamsiyeon/Desktop/PythonWorkspace/pygame_basic/background.png\")\n\n# 캐릭터 (스프라이트) 불러오기\ncharacter = pygame.image.load(\"/Users/hamsiyeon/Desktop/PythonWorkspace/pygame_basic/character.png\")\ncharacter_size = character.get_rect().size # 이미지의 크기를 구해옴\ncharacter_width = character_size[0] #캐릭터의 가로크기\ncharacter_height = character_size[1] # 캐럭터의 세로 크기\ncharacter_x_pos = (screen_width / 2) - (character_width / 2)# 화면 가로의 절반에 위치\ncharacter_y_pos = screen_height - character_height # 화면의 가장 아래에 위치 \n\n#이벤트 루프\nrunning = True #게임이 진행중인가\nwhile running:\n for event in pygame.event.get(): #어떤 이벤트가 발생하였는가?\n if event.type == pygame.QUIT: #창이 닫히는 이벤트가 발생하였는가?\n running = False # 게임이 진행중이 아님\n\n screen.blit(background, (0,0)) #배경 그리기\n\n screen.blit(character, (character_x_pos, character_y_pos))\n\n pygame.display.update() # 게임 화면을 다시 그리기\n\n#pygame 종료\npygame.quit()","sub_path":"pygame_basic/3_main_sprite.py","file_name":"3_main_sprite.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"362067678","text":"\"\"\"\nSettings file\n\"\"\"\n\n# file location used to write file for db bulk insert\nSHARE_PATH = '\\\\\\\\localhost\\\\upload\\\\'\n\n# record batch size for database reads\nRECORDS_BATCH_SIZE = 500\n\n# define database here\nDATABASES = {\n 'datatasks_test': {\n 'db_platform': 'MSSQL',\n 'dsn': 'DSN=App Test', #'DSN=datatasks_test;UID=sa;PWD=yourStrong(!)Password',\n #'username': 'sa',\n #'password': 'yourStrong(!)Password'\n },\n}\n","sub_path":"datatasks/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"433173486","text":"#CS304 Project\n#Dana, Erica, and Gabby\n\nfrom flask import (Flask, url_for, render_template, request, redirect, flash,session)\nfrom datetime import date\nimport random,math\nimport MySQLdb\nimport sys\nimport bcrypt\nimport clickDatabase\nimport search_project\nfrom connection import getConn\nfrom functools import wraps\nimport os\n\napp = Flask(__name__)\napp.url_map.strict_slashes = False\n\napp.secret_key = ''.join([ random.choice(('ABCDEFGHIJKLMNOPQRSTUVXYZ' +\n 'abcdefghijklmnopqrstuvxyz' +\n '0123456789'))\n for i in range(20) ])\n\n\n#route to the home page\n@app.route(\"/\")\ndef home():\n return render_template('home.html')\n\n'''Since in the future, we want to have a user visiting\n a site to be redirected to the login page if they are\n not already logged in. We use a decorator to solve \n this problem. \n'''\n#method learned from flask.pocoo.org\ndef login_required(f):\n @wraps(f)\n def decorated_fcn():\n if 'logged_in' in session:\n return f()\n else:\n flash('You need to login first')\n return redirect(url_for('login'))\n return decorated_fcn()\n\n\n#route to the login page\n@app.route('/login/',methods=['GET','POST'])\ndef login():\n #the code below works well\n if request.method=='GET':\n return render_template('login.html')\n else:\n try:\n print(\"test enter\")\n username=request.form['username']\n password=request.form['password']\n conn=getConn()\n curs=conn.cursor(MySQLdb.cursors.DictCursor)\n curs.execute('select hashed from user where email=%s',[username])\n row=curs.fetchone()\n if row is None:\n flash('Login failed. Please register or try again')\n return redirect(url_for('home'))\n hashed=row['password']\n if bcrypt.hashpw(password.encode('utf-8'),hashed.encode('utf-8'))==hashed:\n print(\"test enter1\")\n flash('Login failed. Please register or try again')\n return redirect(url_for('home'))\n hashed=row['password']\n if (bcrypt.hashpw(password.encode('utf-8'),hashed.encode('utf-8'))==hashed.encode('utf-8')):\n print(\"test enter2\")\n flash('Successfully logged in as'+username)\n session['username']=username\n session['logged_in']= True\n return redirect(url_for('home'))\n else:\n flash('Login failed. Please register or try again')\n return redirect(url_for('login'))\n except Exception as err:\n flash('From submission error'+str(err))\n return redirect(url_for('home'))\n \n\n@app.route('/loginPage/',methods=[\"POST\"]) \ndef redirectToLogin():\n '''renders login.html where user can login or register'''\n return render_template('login.html') \n \n#route to the register page\n@app.route('/register/', methods=[\"POST\"])\ndef register():\n '''allows user to register by creating a username and password;\n if username is unique, encrypts passwords and store it'''\n try:\n username=request.form['username']\n password1=request.form['password1']\n password2=request.form['password2']\n if password1 != password2:\n flash('Passwords do not match.')\n return redirect(url_for('login'))\n hashed=bcrypt.hashpw(password1.encode('utf-8'),bcrypt.gensalt())\n #hashed=password1\n conn=getConn()\n curs=conn.cursor(MySQLdb.cursors.DictCursor)\n curs.execute('select email from user where email=%s',[username])\n row=curs.fetchone()\n if row is not None:\n flash('This email has already been used')\n return redirect(url_for('login'))\n curs.execute('insert into user(email,hashed) values (%s,%s)',[username,hashed])\n session['username']=username\n session['logged_in']=True\n flash('Successfully logged in as'+username)\n return redirect(url_for('login'))\n except Exception as err:\n flash('From submission error'+str(err))\n return redirect(url_for('home'))\n\n#route to logout\n@app.route('/logout/')\ndef logout():\n '''logging out the current user'''\n try:\n if 'username' in session:\n username = session['username']\n session.pop('username')\n session.pop('logged_in')\n flash('You are logged out')\n return redirect(url_for('home'))\n else:\n flash('You are not logged in. Please login or register')\n return redirect( url_for('home') )\n except Exception as err:\n flash('Error Message: '+str(err))\n return redirect( url_for('home') )\n \n#route to page that student sees when first log in\n\n'''route to page that student sees when first log in'''\n@app.route(\"/student/<email>\")\n#@login_required\ndef studentPage(email):\n return render_template('student.html',\n email=email)\n \n@app.route('/reset/', methods=['GET', 'POST'])\ndef reset():\n '''clears all filters and sorting and displays original tables'''\n resetType = request.form.get(\"submit-reset\")\n #in students.html, reset students; return master list of students\n if (resetType == \"Reset Students\"):\n return redirect('students')\n #in project.html, reset projects; return master list of projects\n else: \n return redirect('projects')\n\n#route to page that job poster sees when first log in\n@app.route(\"/jobPoster/<email>\")\ndef jobPosterPage(email):\n return render_template('jobPoster.html',\n email=email) \n\n'''\n#route to page that allows student to view profile and add skills \n@app.route(\"/studentProfile/<email>\", methods = ['GET', 'POST'])\n#@login_required\ndef studentProfile(email):\n studentInfo = clickDatabase.getStudent(conn, email)\n skills = clickDatabase.studentSkills(conn, email)\n #if GET, renders page with all information about student in database\n if request.method == 'GET':\n return render_template('studentProfile.html',\n name = studentInfo['name'],\n email = studentInfo['email'],\n skills = skills)\n #if POST, either adding or removing a skill\n else:\n #removing skill\n if request.form['submit'] == 'Remove':\n skill = request.form.get('skill')\n clickDatabase.removeSkill(conn, email, skill)\n return redirect(url_for('studentProfile',\n email = studentInfo['email']))\n #adding skill\n else:\n newSkill = request.form.get('newSkill')\n clickDatabase.addSkill(conn, email, newSkill)\n return redirect(url_for('studentProfile',\n email = studentInfo['email']))\n\n#route to page that allows job poster to see his/her current projects \n@app.route(\"/project/<pid>\", methods = ['GET', 'POST'])\ndef project(pid):\n #if GET, renders page with all information about that project in database\n if request.method == 'GET':\n projectInfo = clickDatabase.getProject(conn, pid)\n return render_template('project.html',\n name = projectInfo['name'],\n minHours = projectInfo['minHours'],\n pay = projectInfo['pay'],\n location = projectInfo['location'],\n )\n\n# insert page\n@app.route('/insertProject/')\ndef insertProject():\n return render_template('insertProject.html')\n'''\n\n\n# insert page form handling \n#@app.route('/insertProject/', methods=['GET','POST'])\n#def submit_insertProject():\n# '''Route to page that allows student to view profile and add skills.\n# The student profile is for the student that is currently logged in.\n# '''\n\n@app.route(\"/studentProfile/<email>\", methods = ['GET'])\n#@login_required\ndef studentProfile(email):\n conn = clickDatabase.getConn('clickdb')\n studentInfo = clickDatabase.getStudent(conn, email)\n skills = clickDatabase.studentSkills(conn, email)\n #renders page with all information about student in database\n return render_template('studentProfile.html',\n name = studentInfo['name'],\n email = studentInfo['email'],\n active = studentInfo['active'],\n skills = skills)\n\n \n'''Route to page to update student profile'''\n\n@app.route(\"/studentUpdate/<email>\", methods = ['GET', 'POST'])\ndef studentUpdate(email):\n conn = clickDatabase.getConn('clickdb')\n studentInfo = clickDatabase.getStudent(conn, email)\n skills = clickDatabase.studentSkills(conn, email)\n #if GET, renders page with given information as default values in form\n if request.method == 'GET':\n return render_template('studentUpdate.html',\n name = studentInfo['name'],\n email = studentInfo['email'],\n active = studentInfo['active'],\n skills = skills)\n #if POST, updates profile\n else:\n # if student updates name, email, or active status\n if request.form['submit'] == 'Update Personal Information':\n newName = request.form.get('studentName')\n newEmail = request.form.get('studentEmail')\n newActive = request.form.get('studentActive')\n clickDatabase.updateStudentProfile(conn, email, newEmail, newName, newActive)\n flash(\"Profile successfully updated\")\n return redirect(url_for('studentUpdate', email=newEmail))\n # if student removes a skill\n elif request.form['submit'] == 'Remove':\n skill = request.form.get('skill')\n clickDatabase.removeSkill(conn, email, skill)\n return redirect(url_for('studentUpdate',\n email = studentInfo['email']))\n #adding skill\n elif request.form['submit'] == 'Add skill':\n #try and except to handle errors if user tries to enter a\n #skill they've already added to their profile\n try:\n newSkill = request.form.get('newSkill')\n clickDatabase.addSkill(conn, email, newSkill)\n return redirect(url_for('studentUpdate',\n email = studentInfo['email']))\n except:\n flash(\"Error. Skill may already be in your profile.\")\n return redirect(url_for('studentUpdate',\n email = studentInfo['email']))\n else:\n return redirect(url_for('studentProfile',\n email = studentInfo['email']))\n\n\n@app.route(\"/jobs\", methods = ['GET', 'POST'])\ndef jobs():\n conn = getConn()\n if request.method == 'GET':\n jobs = clickDatabase.getJobs(conn)\n return render_template('jobs.html', jobs = jobs)\n else:\n if request.form['submit'] == 'Search':\n search = request.form.get('searchJobs')\n filteredJobs = clickDatabase.searchJobs(conn, search)\n return render_template('jobs.html', jobs = filteredJobs)\n \n@app.route(\"/filterProjects\", methods = ['GET', 'POST'])\ndef filterProjects():\n '''Routes that deal with sorting and filtering project'''\n conn=getConn()\n dropdown=request.form.get(\"menu-tt\")\n checkbox=request.form.get(\"type\")\n projectByLocation=search_project.getProjectByLocation(conn,checkbox)\n allProjects=search_project.getAllProjects(conn)\n \n #when no dropdown is selected\n if dropdown ==\"none\":\n #when checkbox is also not selected\n if checkbox is None:\n return render_template('project.html',allProjects=allProjects)\n #when checkbox is selected\n else:\n #there is no project of the selected location\n if(len(projectByLocation)==0):\n flash(\"There are no projects in the chosen location: \"+ checkbox)\n return render_template('project.html',allProjects=projectByLocation)\n #dropdown is selected\n else:\n #check box not selected\n if checkbox is None:\n if(dropdown==\"Min Hours Ascending\"):\n sortedProjects=search_project.sortProectByMinHoursAscending(conn)\n return render_template('project.html',allProjects=sortedProjects)\n elif(dropdown==\"Pay Descending\"):\n sortedProjects=search_project.sortProectByPayDescending(conn)\n return render_template('project.html',allProjects=sortedProjects)\n elif(dropdown==\"Alphabetical By Location\"):\n sortedProjects=search_project.sortProjectByLocation(conn)\n return render_template('project.html',allProjects=sortedProjects)\n #both dropdown and checkbox selected\n else:\n multiFilter=search_project.multipleFilters(conn,checkbox,dropdown)\n return render_template('project.html',allProjects=multiFilter)\n\n#route to page that allows job poster to see his/her current projects \n@app.route(\"/project/<pid>\", methods = ['GET', 'POST'])\ndef project(pid):\n conn = clickDatabase.getConn('clickdb')\n #if GET, renders page with all information about that project in database\n if request.method == 'GET':\n projectInfo = clickDatabase.getProject(conn, pid)\n return render_template('project.html',\n name = projectInfo['name'],\n minHours = projectInfo['minHours'],\n pay = projectInfo['pay'],\n location = projectInfo['location'],\n )\n\n# insert page\n@app.route('/insertProject/')\ndef insertProject():\n return render_template('insertProject.html')\n\n# insert page form handling \n@app.route('/insertProject/', methods=['GET','POST'])\ndef submit_insertProject():\n conn = clickDatabase.getConn('clickdb')\n if request.method == 'POST':\n \n # checking database to see if the given pid is in use \n if (clickDatabase.search_project_pid(conn, request.form['project-pid'])) != None:\n flash('bad input: project\\'s pid already in use.')\n return render_template('insertProject.html')\n \n # checking if info is missing in input \n if ((request.form['project-pid'] == \"\") or (request.form['project-name'] == \"\") \n or (request.form['project-pay'] == \"\") or (request.form['project-minHours'] == \"\")\n or (request.form['project-location'] == \"\")):\n if request.form['project-pid'] == \"\":\n flash('missing input: project\\'s pid is missing.')\n \n \n if request.form['project-name'] == \"\":\n flash('missing input: name is missing.')\n \n if request.form['project-pay'] == \"\": \n flash('missing input: pay is missing.')\n \n if request.form['project-minHours'] == \"\": \n flash('missing input: minimum hours is missing.')\n \n if request.form['project-location'] == \"\": \n flash('missing input: location is missing.')\n \n return render_template('insertProject.html')\n \n if ((request.form['project-pid'] == \"\") and (request.form['project-name'] == \"\") \n and (request.form['project-pay'] == \"\") and (request.form['project-minHours'] == \"\")\n and (request.form['project-location'] == \"\")):\n \n projectInfo = clickDatabase.search_project_pid(conn, request.form['project-pid'])\n if projectInfo == None: \n clickDatabase.insert_project(conn, request.form['project-pid'], \n request.form['project-name'], request.form['project-pay'],\n request.form['project-minHours'], request.form['project-location'])\n flash('Project {name} was created successfully'.format(title=request.form['project-name']))\n\n else:\n flash(\"Project already exists\")\n return redirect(url_for('updateProject', pid = request.form['project-pid']))\n\n'''\n# setting up page with projects\n@app.route('/selectProject/')\ndef selectProject():\n conn = getConn()\n allProjects = clickDatabase.find_allProjects(conn)\n return render_template('selectProject.html', allProjects=allProjects)\n<<<<<<< HEAD\n if (clickDatabase.search_posting_pid(conn, request.form['posting-pid'])) != None:\n flash('bad input: project\\'s pid already in use.')\n return render_template('insertPosting.html')\n \n # checking if info is missing in input \n if ((request.form['posting-pid'] == \"\") or (request.form['posting-name'] == \"\") \n or (request.form['posting-pay'] == \"\") or (request.form['posting-minHours'] == \"\")\n or (request.form['posting-location'] == \"\")):\n if request.form['posting-pid'] == \"\":\n flash('missing input: project\\'s pid is missing.')\n \n \n if request.form['posting-name'] == \"\":\n flash('missing input: name is missing.')\n \n if request.form['posting-pay'] == \"\": \n flash('missing input: pay is missing.')\n \n if request.form['posting-minHours'] == \"\": \n flash('missing input: minimum hours is missing.')\n \n if request.form['posting-location'] == \"\": \n flash('missing input: location is missing.')\n \n return render_template('insertPosting.html')\n \n if ((request.form['posting-pid'] == \"\") and (request.form['posting-name'] == \"\") \n and (request.form['posting-pay'] == \"\") and (request.form['posting-minHours'] == \"\")\n and (request.form['posting-location'] == \"\")):\n \n postingInfo = clickDatabase.search_posting_pid(conn, request.form['posting-pid'])\n if postingInfo == None: \n clickDatabase.insert_posting(conn, request.form['posting-pid'], \n request.form['posting-name'], request.form['posting-pay'],\n request.form['posting-minHours'], request.form['posting-location'])\n flash('Posting {name} was created successfully'.format(title=request.form['posting-name']))\n\n else:\n flash(\"Posting already exists\")\n return redirect(url_for('updatePosting', pid = request.form['movie-posting']))\n'''\n\n# setting up page with postings\n@app.route('/selectPosting/')\ndef selectPosting():\n conn = getConn()\n allPostings = clickDatabase.find_allPostings(conn)\n return render_template('selectPosting.html', allPostings=allPostings)\n\n \n# returns true when a SQL query's result is not empty\ndef isValid(results):\n return results is not None\n \n# select page form handling\n@app.route('/selectProject/', methods=['GET','POST'])\ndef select_project():\n conn = clickDatabase.getConn('clickdb')\n pid = request.form.get('select-name') ###this line may not work\n if isValid(pid):\n return redirect(url_for('updateProject', pid=pid))\n else: \n flash('Please select a project')\n return render_template('selectProject.html')\n\n \n# search page\n@app.route('/searchStudent/')\ndef searchStudent():\n return render_template('searchStudent.html')\n \n# search page with form request handling \n@app.route('/searchStudent/', methods=['GET','POST'])\ndef search_student():\n name = request.form.get('search-name')\n conn = clickDatabase.getConn('clickdb')\n email = clickDatabase.get_email(conn, name)\n if isValid(email):\n return redirect(url_for('updateProject', email=email))\n\n else: \n flash('Requested student does not exist')\n return render_template\n \n\n@app.route(\"/students\", methods = ['GET', 'POST'])\ndef students():\n conn = clickDatabase.getConn('clickdb')\n if request.method == 'GET':\n students = clickDatabase.getStudents(conn)\n return render_template('students.html', students = students)\n else:\n if request.form['submit'] == 'Search':\n search = request.form.get('searchsStudents')\n filteredStudents = clickDatabase.searchStudents(conn, search)\n return render_template('students.html', jobs = filteredStudents)\n\nif __name__ == '__main__':\n app.debug = True\n app.run('0.0.0.0',8081)\n","sub_path":"Click/clickApp.py","file_name":"clickApp.py","file_ext":"py","file_size_in_byte":20721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"450274589","text":"import torch\nimport PIL\nfrom PIL import Image\nimport numpy as np\n\n\n# 二\nclass DealDataset(torch.utils.data.Dataset):\n def __init__(self, images_path, labels_path, Transform=None):\n # 1:所有图片和标签的路径\n images_path_list = []\n labels_path_list = []\n\n \"\"\"\"\"\"\n # 在这里写,获得所有image路径,所有label路径的代码,并将路径放在分别放在images_path_list和labels_path_list中\n \"\"\"\"\"\"\n self.images_path_list = images_path_list\n self.labels_path_list = labels_path_list\n self.transform = Transform\n\n def __getitem__(self, index):\n # 2:根据index取得相应的一幅图像,一幅标签的路径\n\n image_path = image_path_list[index]\n label_path = label_path_list[index]\n\n # 3:将图片和label读出。“L”表示灰度图,也可以填“RGB”\n\n image = Image.open(image_path).convert(\"L\")\n label = Image.open(label_path).convert(\"L\")\n\n # 4:tansform 参数一般为 transforms.ToTensor(),意思是上步image,label 转换为 tensor 类型\n\n if self.transform is not None:\n image = self.transform(image)\n label = self.transform(label)\n\n return image, label\n\n def __len__(self):\n return len(self.images_path_list)\n\n# 一\nimages_path = \"\"\nlabels_path = \"\"\ndataset = DealDataset(images_path,labels_path,Transform = transforms.ToTensor())\ndataloader = torch.utils.data.DataLoader(dataset = dataset,batch_size = 16,shuffle = False) #shuffle 填True 就会打","sub_path":"HuBMAP/sampleDataloader.py","file_name":"sampleDataloader.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"308435246","text":"fib = [1, 1]\nfor i in range(2, 11):\n\tfib.append(fib[i - 1] + fib[i - 2])\n#These 3 lines creates the fibbonachi numbers up to the 11'th element, and stores them in the variable fib\n#fib = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\n\n\ndef c2f(c):\n\tn = ord(c) # Transforms the character to a number value using ascii/utf-8 and store it in the variable n\n\tb = ''\n\tfor i in range(10, -1, -1): # Counts backwards from 10 to 0\n\t\tif n >= fib[i]: # Since i counts backwards, the first number checked in fib[i] will be the biggest \n\t\t\tn -= fib[i]\n\t\t\tb += '1' # and since the first number checked in fib[i] was the biggest, we know that the first 1/0 symbol will be the \"most significant bit\"\n\t\telse:\n\t\t\tb += '0'\n\treturn b\n\n\nflag = open('flag.txt', 'r').read() # The program opens a flag.txt, so to make it work we have created a placeholder flag.txt\nenc = ''\nfor c in flag:\n\tenc += c2f(c) + ' ' # This passes each character in the flag through the c2f() function before adding it to the array enc[] with a trailing space\nwith open('flag.enc', 'w') as f:\n\tf.write(enc.strip()) # Writes the flag to the file we were given","sub_path":"corCTF/fibinary/enc.py","file_name":"enc.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"16276211","text":"\nfrom datetime import datetime\nimport os\n\nclass Report:\n\n def __init__(self, log_filename, err_filename, summary_filename, debug_depth = 0, display_output = False):\n self.debug_depth = debug_depth\n self.summary_filename = summary_filename\n self.display_output = display_output\n self.log_filename = log_filename\n if not self.garante_filename_path(log_filename, True):\n print('ERROR: there is no path for ' + log_filename)\n self.err_filename = err_filename\n if not self.garante_filename_path(err_filename, True):\n print('ERROR: there is no path for ' + err_filename)\n if not self.garante_filename_path(summary_filename, True):\n print('ERROR: there is no path for ' + summary_filename)\n \n\n def write(self, message, is_summary = False, is_error = False, display_on_screen = False, data = None):\n msg_type = 'INFO'\n if is_error:\n self.__write_error__(message, data)\n if 'ERROR' in message.upper():\n msg_type = 'ERROR'\n elif 'WARNING' in message.upper():\n msg_type = 'WARNING'\n else:\n msg_type = 'WARNING'\n\n if is_summary:\n self.__write_summary__(message)\n \n self.__write_event__(message, msg_type, data)\n\n if display_on_screen:\n print(message)\n if data != None:\n print(data)\n\n def __write_summary__(self, message, data = None):\n self.__write__(self.summary_filename, message)\n if data != None:\n try:\n self.__write__(self.summary_filename, str(data))\n except: \n self.__write__(self.summary_filename, 'UNABLE TO CONVERT DATA TO STR')\n\n def __write_error__(self, message, data = None):\n self.__write__(self.err_filename, message)\n if data != None:\n try:\n self.__write__(self.err_filename, str(data))\n except: \n self.__write__(self.err_filename, 'UNABLE TO CONVERT DATA TO STR')\n \n def __write_event__(self, message, msg_type, data = None):\n message = self.what_time() + '|' + msg_type + '|' + message.replace(\"\\n\", '_BREAK_')\n self.__write__(self.log_filename, message)\n if data != None:\n try:\n self.__write__(self.log_filename, str(data))\n except: \n self.__write__(self.log_filename, 'UNABLE TO CONVERT DATA TO STR')\n \n\n \n def read(self, filename):\n f = open(filename, 'r')\n c = f.read()\n f.close()\n return c\n\n \n def garante_filename_path(self, filename, delete):\n if os.path.exists(filename):\n r = True\n else:\n path = os.path.dirname(filename)\n if not os.path.exists(path):\n os.makedirs(path)\n r = os.path.exists(path)\n if delete:\n self.delete_filename(filename) \n return r\n\n def delete_filename(self, filename):\n if os.path.isfile(filename):\n try:\n os.remove(filename)\n except:\n print('Unable to delete ' + filename)\n return (not os.path.isfile(filename))\n \n def __write__(self, filename, content):\n f = open(filename, 'a+')\n f.write(content + \"\\n\")\n f.close() \n \n def what_time(self):\n return datetime.now().isoformat() \n \n \n\n \n","sub_path":"src/xml_converter/src/reuse/input_output/old_report.py","file_name":"old_report.py","file_ext":"py","file_size_in_byte":3494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"574814155","text":"#!/usr/bin/env python3\nimport unittest\nfrom panda import Panda\nfrom panda.tests.safety import libpandasafety_py\nimport panda.tests.safety.common as common\nfrom panda.tests.safety.common import CANPackerPanda\nfrom panda.tests.safety.test_hyundai import HyundaiButtonBase\n\nclass TestHyundaiCanfdBase(HyundaiButtonBase, common.PandaSafetyTest, common.DriverTorqueSteeringSafetyTest):\n\n TX_MSGS = [[0x50, 0], [0x1CF, 1], [0x2A4, 0]]\n STANDSTILL_THRESHOLD = 30 # ~1kph\n RELAY_MALFUNCTION_ADDR = 0x50\n RELAY_MALFUNCTION_BUS = 0\n FWD_BLACKLISTED_ADDRS = {2: [0x50, 0x2a4]}\n FWD_BUS_LOOKUP = {0: 2, 2: 0}\n\n MAX_RATE_UP = 2\n MAX_RATE_DOWN = 3\n MAX_TORQUE = 270\n\n MAX_RT_DELTA = 112\n RT_INTERVAL = 250000\n\n DRIVER_TORQUE_ALLOWANCE = 250\n DRIVER_TORQUE_FACTOR = 2\n\n PT_BUS = 0\n STEER_MSG = \"\"\n\n @classmethod\n def setUpClass(cls):\n if cls.__name__ == \"TestHyundaiCanfdBase\":\n cls.packer = None\n cls.safety = None\n raise unittest.SkipTest\n\n def _torque_driver_msg(self, torque):\n values = {\"STEERING_COL_TORQUE\": torque}\n return self.packer.make_can_msg_panda(\"MDPS\", self.PT_BUS, values)\n\n def _torque_cmd_msg(self, torque, steer_req=1):\n values = {\"TORQUE_REQUEST\": torque}\n return self.packer.make_can_msg_panda(self.STEER_MSG, 0, values)\n\n def _speed_msg(self, speed):\n values = {f\"WHEEL_SPEED_{i}\": speed * 0.03125 for i in range(1, 5)}\n return self.packer.make_can_msg_panda(\"WHEEL_SPEEDS\", self.PT_BUS, values)\n\n def _user_brake_msg(self, brake):\n values = {\"BRAKE_PRESSED\": brake}\n return self.packer.make_can_msg_panda(\"BRAKE\", self.PT_BUS, values)\n\n def _user_gas_msg(self, gas):\n values = {\"ACCELERATOR_PEDAL\": gas}\n return self.packer.make_can_msg_panda(\"ACCELERATOR\", self.PT_BUS, values)\n\n def _pcm_status_msg(self, enable):\n values = {\"CRUISE_ACTIVE\": enable}\n return self.packer.make_can_msg_panda(\"SCC1\", self.PT_BUS, values)\n\n def _button_msg(self, buttons, main_button=0, bus=1):\n values = {\n \"CRUISE_BUTTONS\": buttons,\n \"ADAPTIVE_CRUISE_MAIN_BTN\": main_button,\n }\n return self.packer.make_can_msg_panda(\"CRUISE_BUTTONS\", self.PT_BUS, values)\n\n\nclass TestHyundaiCanfdHDA1(TestHyundaiCanfdBase):\n\n TX_MSGS = [[0x12A, 0], [0x1A0, 1], [0x1CF, 0], [0x1E0, 0]]\n RELAY_MALFUNCTION_ADDR = 0x12A\n RELAY_MALFUNCTION_BUS = 0\n FWD_BLACKLISTED_ADDRS = {2: [0x12A, 0x1E0]}\n FWD_BUS_LOOKUP = {0: 2, 2: 0}\n\n STEER_MSG = \"LFA\"\n\n def setUp(self):\n self.packer = CANPackerPanda(\"hyundai_canfd\")\n self.safety = libpandasafety_py.libpandasafety\n self.safety.set_safety_hooks(Panda.SAFETY_HYUNDAI_CANFD, 0)\n self.safety.init_tests()\n\n def _user_gas_msg(self, gas):\n values = {\"ACCELERATOR_PEDAL\": gas}\n return self.packer.make_can_msg_panda(\"ACCELERATOR_ALT\", self.PT_BUS, values)\n\nclass TestHyundaiCanfdHDA1AltButtons(TestHyundaiCanfdHDA1):\n\n def setUp(self):\n self.packer = CANPackerPanda(\"hyundai_canfd\")\n self.safety = libpandasafety_py.libpandasafety\n self.safety.set_safety_hooks(Panda.SAFETY_HYUNDAI_CANFD, Panda.FLAG_HYUNDAI_CANFD_ALT_BUTTONS)\n self.safety.init_tests()\n\n def _button_msg(self, buttons, main_button=0, bus=1):\n values = {\n \"CRUISE_BUTTONS\": buttons,\n \"ADAPTIVE_CRUISE_MAIN_BTN\": main_button,\n }\n return self.packer.make_can_msg_panda(\"CRUISE_BUTTONS_ALT\", self.PT_BUS, values)\n\n def test_button_sends(self):\n \"\"\"\n No button send allowed with alt buttons.\n \"\"\"\n for enabled in (True, False):\n for btn in range(8):\n self.safety.set_controls_allowed(enabled)\n self.assertFalse(self._tx(self._button_msg(btn)))\n\n\nclass TestHyundaiCanfdHDA2(TestHyundaiCanfdBase):\n\n TX_MSGS = [[0x50, 0], [0x1CF, 1], [0x2A4, 0]]\n RELAY_MALFUNCTION_ADDR = 0x50\n RELAY_MALFUNCTION_BUS = 0\n FWD_BLACKLISTED_ADDRS = {2: [0x50, 0x2a4]}\n FWD_BUS_LOOKUP = {0: 2, 2: 0}\n\n PT_BUS = 1\n STEER_MSG = \"LKAS\"\n\n def setUp(self):\n self.packer = CANPackerPanda(\"hyundai_canfd\")\n self.safety = libpandasafety_py.libpandasafety\n self.safety.set_safety_hooks(Panda.SAFETY_HYUNDAI_CANFD, Panda.FLAG_HYUNDAI_CANFD_HDA2)\n self.safety.init_tests()\n\n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/safety/test_hyundai_canfd.py","file_name":"test_hyundai_canfd.py","file_ext":"py","file_size_in_byte":4171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"612145435","text":"import json\nimport ast\nimport nltk\nimport argparse\nfrom datetime import datetime\n\ncategories = [\"rent\", \"travel\", \"transit\", \"gym\", \"donations\", \"food\", \"discretionary\"]\nvalid_actions = [\"add\", \"set budget\", \"report card\", \"breakdown\", \"options\", \"reset\"]\nblank_expenses = \"\"\"{'rent': {'budget': 0, 'spent': 0, 'items': {}},\n 'travel': {'budget': 0, 'spent': 0, 'items': {}},\n 'transit': {'budget': 0, 'spent': 0, 'items': {}},\n 'gym': {'budget': 0, 'spent': 0, 'items': {}},\n 'donations': {'budget': 0, 'spent': 0, 'items': {}},\n 'food': {'budget': 0, 'spent': 0, 'items': {}},\n 'discretionary': {'budget': 0, 'spent': 0, 'items': {}}}\"\"\"\n\n\n### UTILITIES ###\n\n\ndef find_closest(entry, choices=valid_actions, threshold=0.2):\n # Find closest choice for word entered among valid choices based on edit distance\n for choice in choices:\n ed = nltk.edit_distance(choice, entry) / len(choice)\n if ed < 0.2:\n return choice\n return entry\n\n\ndef manage_ledger(action, ledger=None, filename=\"expenses.json\"):\n # Load and save JSON file containing saved ledger\n\n if action == \"open\":\n with open(filename, \"r\") as fp:\n ledger = json.load(fp)\n return ledger\n\n if action == \"close\":\n with open(filename, \"w\") as fp:\n json.dump(ledger, fp)\n\n\ndef reset_all(filename, to_erase=\"spent\"):\n # budget_or_spent should be: \"budget\", \"spent\", or \"both\"py\n ledger = manage_ledger(\"open\", filename=filename)\n if to_erase == \"both\":\n ledger = ast.literal_eval(blank_expenses)\n elif to_erase == \"spent\":\n for category in ledger.keys():\n ledger[category][to_erase] = 0\n ledger[category][\"breakdown\"] = {}\n else:\n for category in ledger.keys():\n ledger[category][to_erase] = 0\n\n manage_ledger(\"close\", ledger=ledger)\n\n\n### MANAGEMENT ###\n\n\ndef enter_item(action, ledger, details):\n # Enter a spending or saving amount\n\n if action == \"spending\":\n\n category, amount, item = details.split(\" \")\n category, amount, item = category.strip(\" \"), float(amount), item.strip(\" \")\n category = find_closest(category, choices=categories) # account for misspellings\n focus = ledger[category]\n\n focus[\"spent\"] = focus[\"spent\"] + amount\n if item not in focus[\"breakdown\"].keys():\n focus[\"breakdown\"][item] = amount\n else:\n focus[\"breakdown\"][item] = focus[\"breakdown\"][item] + amount\n return ledger\n\n if action == \"budget\":\n\n category, amount = details.split(\" \")\n category, amount = category.strip(\" \"), float(amount)\n focus = ledger[category]\n\n focus[\"budget\"] = amount\n return ledger\n\n\ndef add_record(action, fn, details):\n # Open ledger, enter item, close ledger\n ledger = manage_ledger(\"open\", filename=fn)\n ledger = enter_item(action, ledger, details)\n manage_ledger(\"close\", ledger=ledger)\n\n if action == \"spending\":\n print(\"here\")\n print(report_card(fn))\n\n\n### REPORTING ###\n\n\ndef report_card(filename):\n # Print out spending by category\n\n ledger = manage_ledger(\"open\", filename=filename)\n\n rc = \"\\n\"\n rc = rc + \"MONTH TO DATE: {}\".format(datetime.now().strftime(\"%B\")) + \"\\n\"\n\n total_spent = 0\n for category in ledger.keys():\n if ledger[category][\"spent\"] > 0:\n report = round(\n (ledger[category][\"spent\"] / ledger[category][\"budget\"]) * 100\n )\n if report >= 80:\n rc = rc + \"EIGHTY PERCENT USED\" + \"\\n\"\n if report >= 100:\n rc = rc + \"NO MORE BUDGET FOR {}\".format(category) + \"\\n\"\n total_spent += ledger[category][\"spent\"]\n rc = (\n rc\n + \"{}: {}% (${})\".format(\n category.title(),\n str(report),\n \"{:.2f}\".format(ledger[category][\"spent\"]),\n )\n + \"\\n\"\n )\n\n rc = rc + \"Total Spent: ${:.2f}\".format(total_spent) + \"\\n\"\n\n manage_ledger(\"close\", ledger=ledger, filename=filename)\n\n return rc\n\n\ndef report_on_item(filename, category):\n ledger = manage_ledger(\"open\", filename)\n category = ledger[category]\n report = \"\\n\" + \"Budget: {}\".format(category[\"budget\"]) + \"\\n\"\n report = report + \"Spent: {}\".format(category[\"spent\"]) + \"\\n\"\n report = report + \"On: {}\".format(category[\"breakdown\"])\n manage_ledger(\"close\", ledger=ledger)\n return report\n\n\ndef display_options(categories=categories, actions=valid_actions):\n print(\"The possible actions are: {}\".format(\", \".join(actions)))\n print(\"The default categories are: {}\".format(\", \".join(categories)))\n","sub_path":"functions_for_budget_tracker.py","file_name":"functions_for_budget_tracker.py","file_ext":"py","file_size_in_byte":4807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"28464173","text":"import argparse\nimport json\nimport os\nimport sys\nfrom copy import deepcopy\n\nimport supersuit as ss\nfrom pettingzoo.butterfly import (\n cooperative_pong_v3,\n pistonball_v4,\n knights_archers_zombies_v7,\n prospector_v4,\n)\nfrom stable_baselines3 import PPO\nfrom stable_baselines3.common.callbacks import EvalCallback\nfrom stable_baselines3.common.vec_env import VecMonitor\nfrom torch import nn as nn\n\nfrom utils import (\n image_transpose,\n AgentIndicatorWrapper,\n BinaryIndicator,\n GeometricPatternIndicator,\n InvertColorIndicator,\n)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"--env-name\",\n help=\"Butterfly Environment to use from PettingZoo\",\n type=str,\n default=\"pistonball_v4\",\n choices=[\n \"pistonball_v4\",\n \"cooperative_pong_v3\",\n \"knights_archers_zombies_v7\",\n \"prospector_v4\",\n ],\n)\nparser.add_argument(\"--n-runs\", type=int, default=5)\nparser.add_argument(\"--n-evaluations\", type=int, default=100)\nparser.add_argument(\"--timesteps\", type=int, default=0)\nparser.add_argument(\"--num-cpus\", type=int, default=8)\nparser.add_argument(\"--num-eval-cpus\", type=int, default=4)\nparser.add_argument(\"--num-vec-envs\", type=int, default=4)\nargs = parser.parse_args()\n\nparam_file = \"./config/\" + str(args.env_name) + \".json\"\nwith open(param_file) as f:\n params = json.load(f)\n\nprint(\"Hyperparameters:\")\nprint(params)\nmuesli_obs_size = 96\nmuesli_frame_size = 4\nevaluations = args.n_evaluations\ntimesteps = args.timesteps\n\nnet_arch = {\n \"small\": [dict(pi=[64, 64], vf=[64, 64])],\n \"medium\": [dict(pi=[256, 256], vf=[256, 256])],\n}[params[\"net_arch\"]]\n\nactivation_fn = {\n \"tanh\": nn.Tanh,\n \"relu\": nn.ReLU,\n \"elu\": nn.ELU,\n \"leaky_relu\": nn.LeakyReLU,\n}[params[\"activation_fn\"]]\n\npolicy_kwargs = dict(\n net_arch=net_arch,\n activation_fn=activation_fn,\n ortho_init=False,\n)\nagent_indicator_name = params[\"agent_indicator\"]\n\ndel params[\"net_arch\"]\ndel params[\"activation_fn\"]\ndel params[\"agent_indicator\"]\nparams[\"policy_kwargs\"] = policy_kwargs\nparams[\"policy\"] = \"CnnPolicy\"\n\n# Generate env\nif args.env_name == \"prospector_v4\":\n env = prospector_v4.parallel_env()\n agent_type = \"prospector\"\nelif args.env_name == \"knights_archers_zombies_v7\":\n env = knights_archers_zombies_v7.parallel_env()\n agent_type = \"archer\"\nelif args.env_name == \"cooperative_pong_v3\":\n env = cooperative_pong_v3.parallel_env()\n agent_type = \"paddle_0\"\nelif args.env_name == \"pistonball_v4\":\n env = pistonball_v4.parallel_env()\n\nenv.reset()\nnum_agents = env.num_agents\nenv = ss.color_reduction_v0(env)\nenv = ss.pad_action_space_v0(env)\nenv = ss.pad_observations_v0(env)\nenv = ss.resize_v0(\n env, x_size=muesli_obs_size, y_size=muesli_obs_size, linear_interp=True\n)\nenv = ss.frame_stack_v1(env, stack_size=muesli_frame_size)\n\n# Enable black death\nif args.env_name == \"knights-archers-zombies-v7\":\n env = ss.black_death_v2(env)\n\n# Agent indicator wrapper\nif agent_indicator_name == \"invert\":\n agent_indicator = InvertColorIndicator(env, agent_type)\n agent_indicator_wrapper = AgentIndicatorWrapper(agent_indicator)\nelif agent_indicator_name == \"invert-replace\":\n agent_indicator = InvertColorIndicator(env, agent_type)\n agent_indicator_wrapper = AgentIndicatorWrapper(agent_indicator, False)\nelif agent_indicator_name == \"binary\":\n agent_indicator = BinaryIndicator(env, agent_type)\n agent_indicator_wrapper = AgentIndicatorWrapper(agent_indicator)\nelif agent_indicator_name == \"geometric\":\n agent_indicator = GeometricPatternIndicator(env, agent_type)\n agent_indicator_wrapper = AgentIndicatorWrapper(agent_indicator)\nif agent_indicator_name != \"identity\":\n env = ss.observation_lambda_v0(\n env, agent_indicator_wrapper.apply, agent_indicator_wrapper.apply_space\n )\n\nenv = ss.pettingzoo_env_to_vec_env_v0(env)\neval_env = deepcopy(env)\nenv = ss.concat_vec_envs_v0(\n env,\n num_vec_envs=args.num_vec_envs,\n num_cpus=args.num_cpus,\n base_class=\"stable_baselines3\",\n)\nenv = VecMonitor(env)\nenv = image_transpose(env)\n\neval_env = ss.concat_vec_envs_v0(\n eval_env,\n num_vec_envs=args.num_vec_envs,\n num_cpus=args.num_eval_cpus,\n base_class=\"stable_baselines3\",\n)\neval_env = VecMonitor(eval_env)\neval_env = image_transpose(eval_env)\n\nall_mean_rewards = []\nlog_dir = \"./data/\" + args.env_name + \"/\"\nos.makedirs(log_dir, exist_ok=True)\n\nfor i in range(args.n_runs):\n model = PPO(\n env=env,\n tensorboard_log=None,\n # We do not seed the trial\n seed=None,\n verbose=3,\n **params\n )\n\n run_log_dir = log_dir + \"run_\" + str(i)\n\n n_eval_episodes = 5\n eval_freq = timesteps // evaluations // model.get_env().num_envs\n\n eval_callback = EvalCallback(\n eval_env,\n n_eval_episodes=n_eval_episodes,\n log_path=run_log_dir,\n eval_freq=eval_freq,\n deterministic=True,\n render=False\n )\n model.learn(total_timesteps=timesteps, callback=eval_callback)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"45823410","text":"from typing import List\n\n\nclass Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n if len(intervals) <= 1:\n return intervals\n intervals = sorted(intervals, key = lambda l: l[0])\n # print(intervals)\n merged = [intervals[0]]\n # print(merged)\n for cur_interval in intervals[1:]:\n if cur_interval[0] <= merged[-1][1]:\n cur_right = max(merged[-1][1], cur_interval[1])\n merged[-1] = [merged[-1][0], cur_right]\n else:\n merged.append(cur_interval)\n return merged","sub_path":"Week08/56. Merge Intervals.py","file_name":"56. Merge Intervals.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"25536582","text":"# -*-coding:Utf-8 -*\r\n# Files for runnning the program\r\n\r\nimport os\r\nfrom donnees import *\r\nfrom fonctions import *\r\n\r\nrandom_word = choose_word(list_words)\r\nprint(\"Le mot choisi est : {}\".format(random_word))\r\nsecret_word = star_word(random_word)\r\nprint(\"Votre mot mystère : {}\".format(secret_word))\r\n\r\nwon = False\r\nwhile not won:\r\n letter_choose = choose_letter_player()\r\n secret_word = star_word(random_word, letter_choose)\r\n print(\"Le nouveau mot est : {}\".format(secret_word))\r\n \r\n won = is_won(secret_word)","sub_path":"Pendu/pendu.py","file_name":"pendu.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"86392956","text":"import math\n\nfrom done.List import product\n\n\ndef factorsOf(i):\n \"\"\"Finds the factors of i\"\"\"\n for k in range(1, int(i ** .5) + 1):\n if i % k == 0: yield k, int(i // k)\n\n\ndef isPrime(n):\n \"\"\"returns true if n is a prime\"\"\"\n if int(n) != n: return False\n if n in {2, 3, 5, 7}: return True\n if n < 2 or n % 2 == 0 or n % 3 == 0: return False\n\n e = int(n ** .5) + 6\n return all(n % f != 0 and n % (f + 2) != 0 for f in range(5, e, 6))\n\n\ndef nextPrime(i):\n \"\"\"_(5) = 5, _(15) = 17\"\"\"\n i = int(i)\n if i < 3: return 2\n if i < 4: return 3\n i = int(math.ceil(i))\n if i % 2 == 0: i += 1\n while not isPrime(i): i += 2\n return i\n\n\ndef primeGen(a, b):\n \"\"\"_(2,11) = 3, 5, 7, 11\"\"\"\n while a < b:\n a = nextPrime(a + 1)\n yield a\n\n\ndef primify(i):\n \"\"\"_(15) = ...(3,1), (5,1)\"\"\"\n i = int(i)\n prime = 0\n while i != 1:\n prime = nextPrime(prime + 1)\n if i < prime * prime: prime = i\n power = 0\n while i % prime == 0:\n power += 1\n i //= prime\n i = int(i)\n if power > 0:\n yield prime, power\n\n\ndef distinctPrimeFactorsOf(i):\n \"\"\"_(15) = [3,5]\"\"\"\n return [prime for prime, _ in primify(i)]\n\n\ndef totient(i):\n \"\"\"euler's totient\"\"\"\n p = distinctPrimeFactorsOf(i)\n y = i / product(p)\n return int(y * product(x - 1 for x in p))\n\n\nclass PrimalNatural:\n \"\"\"Internally represents numbers as prime factorization\n in order to do some more specific operations more optimally\"\"\"\n\n def __new__(cls, obj):\n self = super(PrimalNatural, cls).__new__(cls)\n\n if issubclass(type(obj), PrimalNatural):\n self.pf = obj.pf # trust in the immutability\n elif type(obj) is dict:\n self.pf = obj\n else:\n if obj == 0:\n raise ValueError(\"0 is not a Natural Number\")\n elif obj < 0:\n raise ValueError(\"negatives are not Natural Numbers\")\n self.pf = dict(primify(obj))\n\n return self\n\n def __mul__(self, other):\n other = PrimalNatural(other)\n return PrimalNatural({k: self.pf.get(k, 0) + other.pf.get(k, 0)\n for k in set(self.pf.keys()).union(other.pf.keys())})\n\n def __truediv__(self, other):\n other = PrimalNatural(other)\n return PrimalNatural({k: self.pf.get(k, 0) - other.pf.get(k, 0)\n for k in set(self.pf.keys()).union(other.pf.keys())})\n\n def __pow__(self, power, modulo=None):\n if modulo is not None: raise NotImplemented\n p = int(power)\n return PrimalNatural({k: self.pf.get(k, 0) * p for k in self.pf})\n\n def __int__(self):\n x = 1\n for p, t in self.pf.items():\n x *= p ** t\n return x\n\n def __eq__(self, other):\n other = PrimalNatural(other)\n return all(self.pf.get(k, 0) == other.pf.get(k, 0)\n for k in set(self.pf.keys()).union(other.pf.keys()))\n\n def coprime(self, other):\n other = PrimalNatural(other)\n return set(self.pf).isdisjoint(other.pf)\n\n @property\n def divisor_count(self):\n x = 1\n for i in self.pf.values():\n x *= i + 1\n return x\n\n def divisor_generator(self):\n yield from self._divisors(1, tuple(self.pf))\n\n @property\n def divisors(self):\n return sorted(self._divisors(1, sorted(self.pf)))\n\n def _divisors(self, curDivisor, arr):\n if not len(arr):\n yield curDivisor\n else:\n prime, arr = arr[0], arr[1:]\n yield from self._divisors(curDivisor, arr)\n for _ in range(self.pf[prime]):\n curDivisor *= prime\n yield from self._divisors(curDivisor, arr)\n\n def __repr__(self):\n return f\"PrimalNatural({self.pf})\"\n\n def __str__(self):\n def K(k, v):\n if v == 1:\n return f\"{k}\"\n elif v == 2:\n return f\"{k}*{k}\"\n else:\n return f\"{k}**{v}\"\n\n return \" * \".join(K(k, self.pf[k]) for k in sorted(self.pf))\n\n @staticmethod\n def from_factors(iterable_of_naturals):\n x = PrimalNatural(1)\n for i in iterable_of_naturals:\n x *= i\n return x\n","sub_path":"done/Number/primes.py","file_name":"primes.py","file_ext":"py","file_size_in_byte":4292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"247582946","text":"from gensim.models import word2vec\nimport pickle\n\nif __name__ == '__main__':\n X_100 = word2vec.Word2Vec.load('result/knock90_result/model.bin')\n\n with open('../data/countries.txt', 'r') as data_in, open('result/knock96_result.dump', 'wb') as data_out:\n countries_vec_list = list()\n for line in data_in:\n country = line.strip().replace(' ', '_')\n if country in X_100:\n countries_vec_list.append((country, X_100[country]))\n\n pickle.dump(countries_vec_list, data_out)\n print('\\n'.join(map(lambda x: '{}'.format(x), countries_vec_list)))\n","sub_path":"Shi-ma/chapter10/knock96.py","file_name":"knock96.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"205438912","text":"#!/usr/bin/env python\nimport socket\nimport json\nimport sys\nimport os\n\nhome = os.path.expanduser(\"~\")\nconfig_folder = os.path.join(home,'.client_smi')\nif not os.path.exists(config_folder):\n os.makedirs(config_folder)\nfile_path = os.path.join(config_folder,'hosts_to_smi.json')\nif(os.path.exists(file_path)):\n with open(file_path) as f:\n hosts = json.load(f)\nelse:\n with open('/usr/local/data/hosts_to_smi.json') as f:\n hosts = json.load(f)\n with open(file_path,'w') as f:\n json.dump(hosts,f,indent=2)\n\nmachines = []\n\nfor h in hosts.keys():\n try:\n\n machine = {}\n machine['ip'] = hosts[h]['ip']\n machine['colors'] = hosts[h]['colors']\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((machine['ip'], 1111))\n s.send(\"smi\")\n\n r = s.recv(9999999)\n a = json.loads(r)\n\n machine['socket'] = s\n machine['name'] = h\n machine['nGPUs'] = len(a['attached_gpus'])\n machine['GPUs'] = []\n for i in range(machine['nGPUs']):\n gpu_info = a['attached_gpus'][i]\n gpu = {}\n machine['GPUs'].append(gpu)\n gpu['host'] = h+'@'+machine['ip']\n gpu['name'] = gpu_info['product_name']\n if machine['nGPUs'] > 1:\n gpu['id'] = machine['name']+':'+str(i)\n else:\n gpu['id'] = machine['name']\n gpu['memory'] = gpu_info['total_memory']/1024\n gpu['processes'] = {}\n machines.append(machine)\n \n except :\n pass\n\nwhile True:\n try:\n for m in machines:\n s = m['socket']\n s.send(\"smi\")\n \n r = s.recv(9999999)\n a = json.loads(r)\n for i in range(m['nGPUs']):\n gpu = m['GPUs'][i]\n gpu_info = a['attached_gpus'][i]\n print(gpu['id'])\n print('gpu: '+str(gpu_info['utilization']['gpu'])+' mem: '+str(100*gpu_info[\"used_memory\"]/(1024*gpu['memory'])) )\n with open(os.path.join(config_folder,'client_'+m['name']+'.json'),'wb') as f:\n json.dump(a,f,indent=2)\n \n except KeyboardInterrupt:\n sys.exit()\n\n","sub_path":"client_smi.py","file_name":"client_smi.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"536766206","text":"import pandas as pd\n\n### test data\ntest_pub_info = pd.read_pickle('E:/DM2/data/pkl/test_pub_info.pkl')\ncna_test_unass = pd.read_pickle('E:/DM2/data/pkl/cna_test_unass.pkl')\ntest_data = cna_test_unass.merge(test_pub_info, 'left', 'paper_id')\ntest_data['author_idx'] = test_data['author_idx'].astype(int)\nprint(test_data['author_idx'].max())\ntest_data['author_name'] = test_data.apply(lambda row: row['authors'][row['author_idx']]['name'], axis=1)\ntest_data['author_org'] = test_data.apply(lambda row: row['authors'][row['author_idx']].get('org'), axis=1)\ntest_data = test_data[['paper_id', 'author_name', 'author_org']]\n\n\ndef convert(name):\n name = name.lower()\n name = name.replace('. ', '_').replace('.', '_').replace(' ', '_').replace('-', '').replace('\\xa0', '_')\n def change(b):\n c = b.split('_')\n if len(c) == 2:\n leni = []\n for i in c:\n leni.append(len(i))\n maxl = 0\n i = 0\n index = 0\n for j in leni:\n if j > maxl:\n maxl = j\n index = i\n i = i+1\n d = ''\n if index == 0:\n d += c[index]\n d += '_'\n d += c[1]\n else:\n d += c[index]\n d += '_'\n d += c[0]\n return d\n return b\n name = change(name)\n def change2(name):\n c = name.split('_')\n d = ''\n d += c[1]+'_'+c[0]\n return d\n if name in ['_hui_zhang']:\n name = 'hui_zhang'\n if name in ['b_liu','liu_b','liu_bin']:\n name = 'bin_liu'\n if name in ['bo_li_0001']:\n name = 'bo_li'\n if name in ['chen_jian','cheng_liang','deng_li','ding_feng','conway_j','dong_chen','fang_hong','han_bin','huang_fei',\n 'jiang_bin','jiang_ming','li_bo','liu_jie','liu_lu','mao_li','tang_bo','wei_fei','xie_jin','xie_tao',\n 'xin_qin','xiong_hui','yang_jun','zhang_bo','zhang_hui','zhang_qiwei','zhang_tong','zhang_wei',\n 'zhou_bing','zhou_ning','tian_he','mukherjee_a','xie_dan']:\n name = change2(name)\n if name in ['dr_hui_xiong']:\n name = 'hui_xiong'\n if name in ['liu,_ling']:\n name = 'ling_liu'\n if name in ['ming_jiang_']:\n name = 'ming_jiang'\n if name in ['nakanishi_hiroshi']:\n name = 'hideaki_takahashi'\n if name in ['tong_zhang_0001']:\n name = 'tong_zhang'\n if name in ['wenjun_zhang_0001']:\n name = 'wenjun_zhang'\n if name in ['xiaoyan_zhang']:\n name = 'xiaoyang_zhang'\n if name in ['xie_d']:\n name = 'dan_xie'\n if name in ['zhou_k','zhou_kun']:\n name = 'kun_zhou'\n if name in ['watanabe_osamu','osamu']:\n name = 'osamu_watanabe'\n return name\n\n\ntest_data['author_name'] = test_data['author_name'].apply(convert)\ntest_data.head()\ntest_data['author_name'].nunique()\ntest_data[test_data['author_org'] == 'South China University of Technology']\n\nwhole_author_name_paper_ids = pd.read_pickle('E:/DM2/data/pkl/whole_author_name_paper_ids.pkl')\nwhole_author_name_paper_ids.head()\n\nprint(set(test_data['author_name'])-set(whole_author_name_paper_ids['author_name']))\nprint(len(set(test_data['author_name'])-set(whole_author_name_paper_ids['author_name'])))\n\ntest_data_ = test_data.merge(whole_author_name_paper_ids[['author_name', 'author_id']], 'left', 'author_name')\ntest_data_.isnull().sum() / len(test_data_)\ntest_data_.head()\ntest_data_ = test_data_.drop(index=(test_data_.loc[pd.isnull(test_data_['author_id'])]).index)\ntest_data_.reset_index()\nprint(test_data_.shape)\ntest_data_.to_pickle('E:/DM2/data/pkl/test_data.pkl')\n","sub_path":"gen_test.py","file_name":"gen_test.py","file_ext":"py","file_size_in_byte":3688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"91451820","text":"from django.shortcuts import render,redirect\nfrom django.contrib import messages\nfrom users.views import profiles\nfrom .models import Project, Tag\nfrom .forms import ProjectForm, ReviewForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.db.models import Q\nfrom .utils import searchProjects,paginationProjects\nfrom django.contrib import messages\n# Create your views here.\n\n\ndef projects(request):\n projects,search_query=searchProjects(request)\n for project in projects:\n project.getVoteCount\n projects,page,custom_range=paginationProjects(request,projects)\n\n\n context={'projects':projects,'search_query':search_query,'page':page,'custom_range':custom_range}\n return render(request,'projects/projects.html',context)\n\ndef project(request,pk):\n projectObj=Project.objects.get(id=pk)\n form=ReviewForm()\n if request.method=='POST':\n form=ReviewForm(request.POST)\n if form.is_valid():\n review=form.save(commit=False)\n review.project=projectObj\n review.owner=request.user.profile\n review.save()\n projectObj.getVoteCount\n messages.success(request,'Your review was successfullt submitted!')\n return redirect('project',pk=projectObj.id)\n context={'projectObj':projectObj,'form':form}\n return render(request,'projects/single-project.html',context)\n\n \n@login_required(login_url=\"login\")\ndef createProject(request):\n \n form=ProjectForm()\n profile=request.user.profile\n\n if request.method==\"POST\":\n newtags=request.POST.get('newtags')\n if newtags:\n newtags=newtags.replace(',',' ')\n newtags=newtags.split()\n \n form=ProjectForm(request.POST,request.FILES)\n \n if form.is_valid():\n project=form.save(commit=False)\n project.owner=request.user.profile\n project.save()\n for tag in newtags:\n tag,created=Tag.objects.get_or_create(name=tag)\n project.tags.add(tag)\n \n messages.success(request,'Project was added successfully!')\n\n return redirect('account')\n\n\n context={'form':form,'profile':profile}\n return render(request,'projects/project_form.html',context)\n\n@login_required(login_url=\"login\")\ndef updateProject(request,pk):\n profile=request.user.profile\n project=profile.project_set.get(id=pk)\n form=ProjectForm(instance=project)\n if request.method==\"POST\":\n newtags=request.POST.get('newtags')\n if newtags:\n newtags=newtags.replace(',',' ')\n newtags=newtags.split()\n \n \n form=ProjectForm(request.POST,request.FILES,instance=project)\n if form.is_valid():\n project=form.save()\n for tag in newtags:\n tag,created=Tag.objects.get_or_create(name=tag)\n project.tags.add(tag)\n \n messages.success(request,'Project was updated successfully!')\n return redirect('account')\n \n\n context={'form':form,'project':project}\n return render(request,'projects/project_form.html',context)\n\n@login_required(login_url=\"login\")\ndef deleteProject(request,pk):\n profile=request.user.profile\n\n project=profile.project_set.get(id=pk)\n if request.method==\"POST\":\n project.delete()\n messages.success(request,'Project was deleted successfully!')\n return redirect('account')\n context={'object':project}\n return render(request,'delete_template.html',context)\n\n\n","sub_path":"projects/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"198224523","text":"from datetime import datetime\nfrom rest_framework.authtoken.models import Token\nfrom re import sub\nclass TestMiddleware:\n\t\"\"\"Easy as duck\"\"\"\n\tdef __init__(self, get_response):\n\t\tself.get_response = get_response\n\n\tdef __call__(self, request):\n\t\theader_token = request.META.get(\"HTTP_AUTHORIZATION\", None)\n\t\tif header_token is not None:\n\t\t\ttoken_key =\tsub('Token ', '', str(header_token))\n\t\t\ttry:\n\t\t\t\ttoken_obj = Token.objects.get(key = token_key)\n\t\t\texcept token_obj.DoesNotExist as e:\n\t\t\t\tlogger.error('Token doesnt exist.', + str(e))\n\t\tresponse = self.get_response(request)\n\n\t\treturn response","sub_path":"todo/api/accounts/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"288001434","text":"import spotipy\nimport spotipy.oauth2 as oauth2\nfrom spotipy import oauth2\nfrom spotipy.oauth2 import SpotifyOAuth\nfrom spotipy.oauth2 import SpotifyClientCredentials\nimport spotipy.util as util\nimport time\nimport requests\nfrom config import spotify_client_id, spotify_client_secret, spotify_redirect_uri, spotify_scope, spotify_user, spotify_playlists, logger\n\nclass spotify_music:\n \n def __init__(self, client_credentials_flow=1):\n self.client_credentials_flow = client_credentials_flow\n if self.client_credentials_flow:\n credentials = SpotifyClientCredentials(client_id=spotify_client_id, client_secret=spotify_client_secret)\n self.sp = spotipy.Spotify(client_credentials_manager=credentials)\n else:\n self.sp_oauth = oauth2.SpotifyOAuth(client_id=spotify_client_id,client_secret=spotify_client_secret,redirect_uri=spotify_redirect_uri,scope=spotify_scope)\n self.token_info = self.sp_oauth.get_cached_token()\n self.spotify_token = self.get_token()\n self.sp = spotipy.Spotify(auth=self.spotify_token)\n \n def get_token(self):\n if not self.token_info:\n auth_url = self.sp_oauth.get_authorize_url()\n print(auth_url)\n response = input('Paste the above link into your browser, then paste the redirect url here: ') # Can automate this bit with BS or Selenium.\n\n code = self.sp_oauth.parse_response_code(response)\n self.token_info = self.sp_oauth.get_access_token(code)\n\n spotify_token = self.token_info['access_token']\n return(spotify_token)\n\n def get_current_user(self):\n return self.sp.current_user()\n\n def refresh_token(self):\n if not self.client_credentials_flow and self.sp_oauth.is_token_expired(self.token_info):\n try:\n self.token_info = self.sp_oauth.refresh_access_token(self.token_info['refresh_token'])\n spotify_token = self.token_info['access_token']\n log1 = 'SPOTIFY TOKEN REFRESHED'\n logger.warning(log1)\n self.sp = spotipy.Spotify(auth=spotify_token)\n return(self.sp)\n except Exception as e:\n logger.error('TOKEN IS EXPIRED BUT FAILED TO REFRESH.')\n logger.exception(e)\n return(self.sp)\n else:\n return(self.sp)\n\n def get_track(self, track_id):\n return self.sp.track(str(track_id))\n\n def get_playlist_track_aggregate(self, spotify_user, spotify_playlists):\n aggregate = {}\n if spotify_playlists == []:\n return aggregate\n else:\n self.sp = self.refresh_token()\n for playlist in spotify_playlists:\n spotify_response = self.sp.user_playlist_tracks(user = spotify_user, playlist_id = playlist, limit=100, offset=0, market='US')['items']\n for track in spotify_response:\n trackInfo = track['track']\n if trackInfo == None:\n logger.warning('Found empty Spotify track, skipping.')\n pass\n else:\n artist_names = [i['name'] for i in trackInfo['artists']]\n try:\n artist_track_name = '{artistName} - {trackName}'.format(artistName = artist_names[0], trackName = trackInfo['name']).replace('.', '').replace('$', 'S')\n except TypeError as te: # catches empty spotify tracks (reason unknown)\n logger.warning('Found empty Spotify track again, skipping.')\n logger.warning(te)\n pass\n try:\n aggregate[artist_track_name]\n except KeyError:\n try:\n aggregate.update({artist_track_name: {'Type': trackInfo['album']['album_type'], \n 'Release Date': trackInfo['album']['release_date'], \n 'Artist Name': artist_names, \n 'Track Name': trackInfo['name'], \n 'Spotify Play Link': trackInfo['external_urls']['spotify'], \n 'Apple Music Play Link': '', \n 'Art': trackInfo['album']['images'][0]['url'], \n 'Track ID': trackInfo['id'], \n 'source': 'Spotify',\n # 'source_playlist': playlist_response['name'],\n # 'source_playlist_url': playlist_response['external_urls']['spotify'], \n # 'source_playlist_id': playlist_response['id'], \n # 'source_playlist_description': playlist_response['description']\n }})\n except TypeError as te: # catches empty spotify tracks (reason unknown)\n logger.exception(te)\n pass\n \n if len(aggregate) == 0:\n logger.error('Failed to Get Apple Aggregate')\n\n log1 = 'FETCHED ' + str(len(aggregate)) + ' ITEMS FROM SPOTIFY'\n logger.info(log1)\n return(aggregate)\n\n def get_play_link(self, track):\n self.sp = self.refresh_token()\n try:\n spotify_response = self.sp.search(track['_id'], limit=1, type='track', market='US')\n try:\n track['track_data']['Spotify Play Link'] = spotify_response['tracks']['items'][0]['external_urls']['spotify']\n return(track)\n except IndexError:\n track['track_data']['Spotify Play Link'] = 'Could not find URL'\n logger.info('Could not find URL from spotify')\n return(track)\n except KeyError as ke:\n track['track_data']['Spotify Play Link'] = 'Could not find URL'\n logger.info('Could not find URL from spotify')\n return(track)\n\nif __name__ == \"__main__\":\n pass","sub_path":"spotify.py","file_name":"spotify.py","file_ext":"py","file_size_in_byte":6378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"527110197","text":"from functools import partial\n\nfrom PyQt5 import QtCore, uic, QtWidgets\nfrom PyQt5.QtWidgets import QFileDialog\nimport _thread\n\n\nimport serial\nimport serial.tools.list_ports\n\n\nimport atexit\nimport subprocess\nimport sys\nimport os\n\nimport tempfile\n\nimport winreg\nimport itertools\n\nfrom Squid_zModem.Squid_zModem import ZModemAPI\n\n\ndef enumerate_serial_ports():\n \"\"\" Uses the Win32 registry to return an\n iterator of serial (COM) ports\n existing on this computer.\n \"\"\"\n path = 'HARDWARE\\\\DEVICEMAP\\\\SERIALCOMM'\n try:\n key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)\n except WindowsError:\n print(\"Your computer must have had a connection to a serial device at least one!\")\n raise EnvironmentError\n\n for i in itertools.count():\n try:\n val = winreg.EnumValue(key, i)\n yield str(val[1])\n except EnvironmentError:\n break\n\n\nFILELOCATIONS = [os.getcwd(), tempfile.mkdtemp()]\n\n\nclass Squid_BT_Interface(QtWidgets.QMainWindow):\n def __init__(self):\n QtWidgets.QWidget.__init__(self)\n uic.loadUi(\"Squid_zGUI.ui\", self)\n\n self.setFixedSize(self.size()) # prevent the user from resizing the window.\n self.setWindowTitle('Squid_zGUI')\n\n # register button functions:\n self.btn_open_Sport.clicked.connect(self._on_btn_open_sport_clicked)\n self.btn_refresh_Sport.clicked.connect(self._on_btn_refresh_sport_clicked)\n self.btn_browse_file2send.clicked.connect(partial(self._openfilenamedialog, 'file2send_loc'))\n self.btn_browse_file2recv.clicked.connect(partial(self._openfilenamedialog, 'file2recv_loc'))\n self.btn_send.clicked.connect(self._on_btn_send_click)\n self.buttonBox.accepted.connect(partial(self._on_buttonbox_input, 'start'))\n self.buttonBox.rejected.connect(partial(self._on_buttonbox_input, 'cancel'))\n\n self._button_crtl('disconnected')\n self.lbl_status.setText('')\n\n # radio button functions:\n self.radioBtn_dl_sel.setChecked(True) # default: get single files...\n\n # refresh serial port list entries:\n self._on_btn_refresh_sport_clicked()\n\n # set temporary file folder for receiving filepath\n self.lineEdit_file2recv.setText(FILELOCATIONS[1])\n\n # create a zmodem object\n self.ZmodemObj = ZModemAPI()\n\n self._ser = None\n\n def _button_crtl(self, state):\n if state == 'disconnected':\n self.btn_browse_file2send.setEnabled(False)\n self.btn_browse_file2recv.setEnabled(False)\n self.btn_send.setEnabled(False)\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).setEnabled(False)\n if state == 'connected':\n self.btn_browse_file2send.setEnabled(True)\n self.btn_browse_file2recv.setEnabled(True)\n self.btn_send.setEnabled(True)\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(True)\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).setEnabled(False)\n if state == 'receiving':\n self.btn_browse_file2send.setEnabled(False)\n self.btn_browse_file2recv.setEnabled(False)\n self.btn_send.setEnabled(False)\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).setEnabled(True)\n if state == 'sending':\n self.btn_browse_file2send.setEnabled(False)\n self.btn_browse_file2recv.setEnabled(False)\n self.btn_send.setEnabled(False)\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).setEnabled(False)\n self.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).setEnabled(False)\n\n def _openfilenamedialog(self, loc):\n options = QFileDialog.Options()\n # options |= QFileDialog.DontUseNativeDialog\n\n if loc == 'file2send_loc':\n filepath, _ = QFileDialog.getOpenFileName(self, \"Open file to send\", \"\",\n \"Squid Config Files (*.CFG)\", options=options)\n self.lineEdit_file2send.setText(filepath)\n FILELOCATIONS[0] = filepath\n elif loc == 'file2recv_loc':\n filepath = QFileDialog.getExistingDirectory(\n self,\n \"Select receive folder\",\n \"/home/my_user_name/\",\n QFileDialog.ShowDirsOnly\n )\n\n self.lineEdit_file2recv.setText(filepath)\n FILELOCATIONS[1] = filepath\n\n # functions connected to GUI objects:\n def _on_btn_open_sport_clicked(self):\n buttontext = self.btn_open_Sport.text()\n # print('button clicked ' + buttontext)\n if buttontext == 'Connect':\n self.btn_open_Sport.setText('Connecting')\n sportname = self.comboBox_Sport.currentText()\n self.lbl_status.setText('opening serial port ' + sportname)\n _thread.start_new_thread(self._openserialport, (sportname, ))\n\n elif buttontext == 'Disconnect':\n self._ser.close()\n self.btn_open_Sport.setText('Connect')\n self.lbl_status.setText('serial port ' + self._ser._port + ' closed')\n self._button_crtl('disconnected')\n self.filelist.clear()\n\n else:\n if self._ser.is_open:\n self._ser.close()\n self.btn_open_Sport.setText('Connect')\n self._button_crtl('disconnected')\n\n def _on_btn_refresh_sport_clicked(self):\n self.comboBox_Sport.clear()\n for portname in enumerate_serial_ports():\n self.comboBox_Sport.addItem(portname)\n\n def _on_buttonbox_input(self, crtl):\n if crtl == 'start':\n receivemode = self._get_radiobtn_dl_state()\n self.recv_thread_id = _thread.start_new_thread(self._receivefiles, (receivemode, ))\n else:\n # print('cancel file transfer')\n # FIXME: kill receive thread! For now we just let the thread crash by closing the serial port... :(\n self._ser.close()\n self.btn_open_Sport.setText('Connect')\n self.lbl_status.setText('File transfer cancelled and serial port closed!')\n self._button_crtl('disconnected')\n self.filelist.clear()\n\n\n def _on_btn_send_click(self):\n self._button_crtl('sending')\n self.lbl_status.setText('sending file: ' + os.path.basename(FILELOCATIONS[0]))\n _thread.start_new_thread(self._sendfile, ())\n\n def _get_radiobtn_dl_state(self):\n if self.radioBtn_dl_sel.isChecked(): # default: get single files...\n return 'sel'\n else:\n return 'all'\n # print(FILELOCATIONS)\n\n def _populate_file_list(self, squid_file_list):\n self.filelist.clear()\n for entry in reversed(squid_file_list):\n item = QtWidgets.QTreeWidgetItem(entry)\n self.filelist.addTopLevelItem(item)\n\n def _openserialport(self, portnum):\n\n # if self._ser.is_open:\n # self._ser.close()\n # self._ser.timeout = 10\n try:\n self._ser = serial.Serial(portnum, 57600, timeout=5, writeTimeout=2)\n except serial.SerialException:\n self.lbl_status.setText('Failed to open serial port: ' + str(serial.SerialException))\n self.btn_open_Sport.setText('Connect')\n return False\n\n self.btn_open_Sport.setText('Disconnect')\n self.lbl_status.setText('serial port ' + portnum + ' open, fetching available file list')\n self.ZmodemObj.ser = self._ser\n squiddir = self.ZmodemObj.squid_dir()\n if not squiddir:\n self.lbl_status.setText('fetching available file list failed - SQUID did not answer!')\n return\n ##############\n ## add sort ##\n ##############\n self._populate_file_list(squiddir)\n self._button_crtl('connected')\n self.lbl_status.setText('SQUID file transfer ready!')\n return True\n\n def _sendfile(self):\n if not self.ZmodemObj.squid_send_file(FILELOCATIONS[0]):\n self.lbl_status.setText('File transmission failed - SQUID did not answer!')\n self._button_crtl('connected')\n self.lbl_status.setText('SQUID file transfer ready!')\n\n def _receivefiles(self, receivemode):\n self._button_crtl('receiving')\n # print('start receiving file(s) ')\n if receivemode == 'sel':\n # get selected filenames to request from the squid:\n getselected = self.filelist.selectedItems()\n if getselected:\n for i in range(len(getselected)):\n basenode = getselected[i]\n filename = basenode.text(0)\n\n self.lbl_status.setText('Downloading file ' + filename)\n if not self.ZmodemObj.squid_recv_file(FILELOCATIONS[1], filename): # FIXME: receiving of binarx files (e.g. FIRMWARE.BIN) is not working because of decoding errors in the ZModem code!\n self.lbl_status.setText('File transmission failed - SQUID did not answer!')\n\n else:\n self.lbl_status.setText('No file selected - aborting download!')\n self._button_crtl('connected')\n return\n\n elif self._get_radiobtn_dl_state() == 'all':\n self.lbl_status.setText('Downloading all files on SQUID SD')\n if not self.ZmodemObj.squid_recv_file(FILELOCATIONS[1], '*'):\n self.lbl_status.setText('File transmission failed - SQUID did not answer!')\n filename = self.ZmodemObj.SquidDIR[0][0] # get some filename to open the explorer on this file location...\n\n if FILELOCATIONS[1].find('\\\\') == -1:\n subprocess.Popen(r'explorer /select,\"%s\"' % (FILELOCATIONS[1] + '/' + filename).replace('/', '\\\\'))\n else:\n subprocess.Popen(r'explorer /select,\"%s\"' % (FILELOCATIONS[1] + '\\\\' + filename))\n self._button_crtl('connected')\n self.lbl_status.setText('SQUID file transfer ready!')\n\n\n def exit_handler(self):\n if self._ser is not None:\n if self._ser.is_open:\n self._ser.close()\n # print('application is ending!')\n\n\n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n window = Squid_BT_Interface()\n atexit.register(window.exit_handler)\n window.show()\n\n\n sys.exit(app.exec_())\n\n","sub_path":"src/Squid_zGUI.py","file_name":"Squid_zGUI.py","file_ext":"py","file_size_in_byte":10567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"563915899","text":"import json\n\nfrom Calf.data import TickData\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom bigdata.apis.db_connection import DBConnection\nfrom bigdata.models import Calendar, BaseModel\nimport datetime as dt\nimport pandas as pd\n\n\n@csrf_exempt\ndef get_five_palte(request):\n rd = json.loads(request.body.decode('utf-8'))\n date = rd.get('date', None)\n code = str(rd.get('code', '000005'))\n if date == None:\n date = Calendar.today()\n else:\n date = dt.datetime.strptime(date, '%Y%m%d')\n data = TickData.read_tickers(code, date, dt.datetime(date.year, date.month, date.day, 23, 59))\n # data = data.fillna(0)\n if len(data):\n cols = ['stock_code', 'datetime', 'amount', 'volume',\n 'B1', 'B2', 'B3', 'B4', 'B5',\n 'S1', 'S2', 'S3', 'S4', 'S5',\n 'B1V', 'B2V', 'B3V', 'B4V', 'B5V',\n 'S1V', 'S2V', 'S3V', 'S4V', 'S5V',\n 'price', ]\n data = data.loc[:, cols]\n data['s1_max'] = data['S1V'].max() * 0.5\n data['s2_max'] = data['S2V'].max() * 0.5\n data['s3_max'] = data['S3V'].max() * 0.5\n data['s4_max'] = data['S4V'].max() * 0.5\n data['s5_max'] = data['S5V'].max() * 0.5\n data['b5_max'] = data['B5V'].max() * 0.5\n data['b4_max'] = data['B4V'].max() * 0.5\n data['b3_max'] = data['B3V'].max() * 0.5\n data['b2_max'] = data['B2V'].max() * 0.5\n data['b1_max'] = data['B1V'].max() * 0.5\n data['v_max'] = data['volume'].max() * 0.5\n data = data.sort_values(by=['datetime'], ascending=True)\n data['datetime'] = data['datetime'].astype('str')\n data = data.to_dict(orient='records')\n return HttpResponse(json.dumps(data))\n return HttpResponse(json.dumps([]))\n\n\n@csrf_exempt\ndef get_five_data(request):\n rd = json.loads(request.body.decode('utf-8'))\n date = rd.get('date', None)\n code = str(rd.get('code', '000005'))\n index = int(rd.get('index', 0))\n\n if date == None or Calendar.today() == dt.datetime.strptime(date, '%Y%m%d'):\n date = Calendar.today()\n # dobj = BaseModel('real_buy_sell_all_stock_code')\n dobj = DBConnection().connect()['real_buy_sell_all_stock_code']\n curror = dobj.find(\n {'date': {'$gte': date, '$lte': dt.datetime(date.year, date.month, date.day, 23, 59)},\n 'stock_code': code},\n {'_id': 0, 'datetime': 1, 'stock_code': 1,\n 'B1_V': 1, 'B2_V': 1, 'B3_V': 1, 'B4_V': 1, 'B5_V': 1,\n 'S1_V': 1, 'S2_V': 1,\n 'S3_V': 1, 'S4_V': 1,\n 'S5_V': 1, 'price': 1, 'volume': 1, 'B1': 1, 'B2': 1, 'B3': 1, 'B4': 1, 'B5': 1,\n 'S1': 1, 'S2': 1,\n 'S3': 1, 'S4': 1,\n 'S5': 1,\n })\n else:\n date = dt.datetime.strptime(date, '%Y%m%d')\n dobj = BaseModel('ticker')\n curror = dobj.query2(\n sql={'date': {'$gte': date, '$lte': dt.datetime(date.year, date.month, date.day, 23, 59)},\n 'stock_code': code},\n fields={'_id': 0, 'datetime': 1, 'stock_code': 1,\n 'B1V': 1, 'B2V': 1, 'B3V': 1, 'B4V': 1, 'B5V': 1,\n 'S1V': 1, 'S2V': 1,\n 'S3V': 1, 'S4V': 1,\n 'S5V': 1, 'price': 1, 'volume': 1, 'B1': 1, 'B2': 1, 'B3': 1, 'B4': 1, 'B5': 1,\n 'S1': 1, 'S2': 1,\n 'S3': 1, 'S4': 1,\n 'S5': 1,\n })\n\n data = []\n if curror.count():\n li = list(dobj.asc(curror, ['datetime']).limit(index + 200))\n # curror=curror.limit(10)\n # curror=curror.\n data = pd.DataFrame(li)\n data = data.rename(\n columns={'S1V': 'S1_V', 'S2V': 'S2_V', 'S3V': 'S3_V', 'S4V': 'S4_V', 'S5V': 'S5_V', 'B1V': 'B1_V',\n 'B2V': 'B2_V',\n 'B3V': 'B3_V', 'B4V': 'B4_V', 'B5V': 'B5_V'})\n\n data = data.drop_duplicates(['datetime'])\n data['datetime'] = data['datetime'].astype('str')\n data['datetime'] = data['datetime'].map(lambda x: x[11:len(x)])\n data['volume'] = data.volume - data.volume.shift(1)\n data = data[data['volume'] > 0]\n data = data.fillna(0)\n data = data.to_dict(orient='records')\n data = data[index]\n\n return HttpResponse(json.dumps(data))\n","sub_path":"bigdata/apis/five_gear_plate.py","file_name":"five_gear_plate.py","file_ext":"py","file_size_in_byte":4385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"390558533","text":"from django.conf.urls import include, url\nfrom django.contrib import admin\n\n\nfrom app.views.account import AccountCreateView, AccountActivateView\n\n\nurlpatterns = [\n url(r'^', include('app.urls')),\n url(r'^accounts/', include('django.contrib.auth.urls')),\n url(r'^accounts/create/', AccountCreateView.as_view(), name=\"account_create\"),\n url(r'^accounts/verify/', AccountActivateView.as_view(), name=\"account_verify\"),\n url(r'^admin/', include(admin.site.urls)),\n]\n","sub_path":"watcher/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"61705003","text":"# Advanced Programming In Python - Lesson 8 Assignment 1: Functional Techniques\n# RedMine Issue - SchoolOps-18\n# Code Poet: Anthony McKeever\n# Start Date: 01/16/2019\n# End Date: 01/16/2019\n\n\"\"\"\nA module for supporting relating customer rentals to inventory.\n\"\"\"\n\nfrom functools import partial\nfrom os import path\n\n\ndef add_furnature(invoice_file, customer_name, item_code,\n item_description, item_monthly_price):\n \"\"\"\n Appends customer rentals to an invoice file.\n Creates the invoice file if it doesn't exist.\n\n :invoice_file: The invoice file to use.\n :customer_name: The name of the customer.\n :item_code: The identified of the rented item.\n :item_description: The description of the rented item.\n :item_monthly_price: The monthly rental price of the item\n \"\"\"\n # Check if file exists and is not empty, if so append new line character to\n # the start of the write value so we don't start the file with a blank line\n use_new_line = path.exists(invoice_file) and path.getsize(invoice_file) > 0\n new_line = \"\\n\" if use_new_line else \"\"\n\n write_val = \"{0}{1},{2},{3},{4:0.2f}\".format(new_line,\n customer_name,\n item_code,\n item_description,\n float(item_monthly_price))\n\n with open(invoice_file, \"a+\") as writer:\n writer.write(write_val)\n\n\ndef single_customer(customer_name, invoice_file):\n \"\"\"\n Return a closure representing a customer. The closure encompases a the\n method \"add_rentals\" which accepts a single parameter.\n\n :invoice_file: The invoice file to use.\n :customer_name: The name of the customer.\n\n Return Value:\n add_rentals(rental_items)\n \"\"\"\n rental_handler = partial(add_furnature,\n invoice_file=invoice_file,\n customer_name=customer_name)\n\n def add_rentals(rental_items):\n \"\"\"\n Adds a collection of rented items to the customer's invoice.\n\n :rental_items: The path to the customer's rented items CSV file.\n \"\"\"\n with open(rental_items, \"r\") as reader:\n # Read file line by line incase the CSV file is giant to prevent\n # out of memory issues.\n item_line = reader.readline()\n\n while item_line:\n item = item_line.split(',')\n rental_handler(item_code=item[0],\n item_description=item[1],\n item_monthly_price=item[2])\n\n item_line = reader.readline()\n\n return add_rentals\n","sub_path":"students/anthony_mckeever/lesson_8/assignment_1/inventory.py","file_name":"inventory.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"311889517","text":"#!/usr/bin/env python\n# coding=utf-8\nimport time\nimport threadpool \ndef sayhello(str):\n print (\"Hello \",str)\n time.sleep(2)\n\nname_list =['xiaozi','aa','bb','cc']\nstart_time = time.time()\npool = threadpool.ThreadPool(10) \nrequests= []\nrequests = threadpool.makeRequests(sayhello, name_list) \nfor req in requests:\n pool.putRequest(req)\npool.wait() \nprint ('%d second'% (time.time()-start_time))\n","sub_path":"util/threadpool/threadpool_test.py","file_name":"threadpool_test.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"644105155","text":"from django.urls import path\r\nfrom django.conf.urls import url\r\nfrom . import views, log_views\r\n\r\nurlpatterns = [\r\n path('', log_views.judgelogin, name='judgelogin'),\r\n path('login', log_views.login, name='login'),\r\n path('logout', log_views.logout, name='logout'),\r\n path('register', log_views.register, name='register'),\r\n path('postlist', views.postlist, name='postlist'),\r\n path('postmsg', views.postmsg, name='postmsg'),\r\n path('likes', views.likes, name='likes'),\r\n]\r\n","sub_path":"mboard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"167806952","text":"import networkx as nx\nc = 0\nn = input()\n\ndef search(t):\n for el in list(inh.successors(t)):\n if el == s[1]:\n ans.append('Yes')\n return True\n elif inh.successors(t) == []:\n break\n else:\n search(el)\n\ninh = nx.DiGraph()\nwhile c < n:\n i = raw_input().split(' ')\n inh.add_node(i[0])\n if len(i) != 1:\n k = len(i)\n j = 2\n h = 0\n while j < k:\n inh.add_node(i[2+h])\n inh.add_edge(i[2+h], i[0])\n j += 1\n h += 1\n c += 1\n\nq = input()\nf = 0\nans = []\nwhile f < q:\n s = raw_input().split(' ')\n if not search(s[0]): \n ans.append('No') \n f += 1\nfor i in ans:\n print(i)\n\n\n \n","sub_path":"Homework/bla_bla6.py","file_name":"bla_bla6.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"438233317","text":"import sys\nimport os\n\nfrom amftrack.util.sys import get_dirname, temp_path\nimport pandas as pd\nimport ast\nfrom scipy import sparse\nimport scipy.io as sio\nimport cv2\nimport imageio.v2 as imageio\nimport numpy as np\nimport scipy.sparse\nimport os\nfrom time import time\nfrom amftrack.pipeline.functions.image_processing.extract_skel import (\n extract_skel_new_prince,\n run_back_sub,\n bowler_hat,\n)\n\nfrom amftrack.util.sys import get_dates_datetime, get_dirname\nimport shutil\n\ni = int(sys.argv[-1])\nop_id = int(sys.argv[-2])\ndirectory = str(sys.argv[1])\n\n\nrun_info = pd.read_json(f\"{temp_path}/{op_id}.json\", dtype={\"unique_id\": str})\nfolder_list = list(run_info[\"folder\"])\nfolder_list.sort()\ndirectory_name = folder_list[i]\nprint(directory_name)\npath_snap = os.path.join(directory, directory_name)\npath_tile = os.path.join(path_snap, \"Img/TileConfiguration.txt.registered\")\ntry:\n tileconfig = pd.read_table(\n path_tile,\n sep=\";\",\n skiprows=4,\n header=None,\n converters={2: ast.literal_eval},\n skipinitialspace=True,\n )\nexcept:\n print(\"error_name\")\n path_tile = os.path.join(path_snap, \"Img/TileConfiguration.registered.txt\")\n tileconfig = pd.read_table(\n path_tile,\n sep=\";\",\n skiprows=4,\n header=None,\n converters={2: ast.literal_eval},\n skipinitialspace=True,\n )\nwith open(path_tile) as f:\n lines = f.readlines()\nlines_modified = []\nfor line in lines[:4]:\n lines_modified.append(line)\nfor line in lines[4:]:\n x = str(float(line.split(\";\")[2].split(\"\\n\")[0].split(\",\")[0][2:]) * 2)\n y = str(float(line.split(\";\")[2].split(\"\\n\")[0].split(\",\")[1][:-1]) * 2)\n line_new = \";\".join([line.split(\";\")[0], line.split(\";\")[1], f\" ({x},{y}) \\n\"])\n lines_modified.append(line_new)\nwith open(path_tile, \"w\") as f:\n for line in lines_modified:\n f.write(f\"{line}\")\n","sub_path":"amftrack/pipeline/scripts/image_processing/change_tile_config.py","file_name":"change_tile_config.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"518931683","text":"# import module from script\nimport sys\nimport os\nimport subprocess\nimport argparse\nimport pathfinder\n\n# Function definations:-\n\n# Clear the terminal\ndef clear_screen():\n if os.name == 'nt':\n os.system('cls')\n else:\n os.system('clear')\n# end of clear_screen\n\n# check for command line arguments\n\n\ndef check_args(args=None):\n if args == None:\n print(\"Please enter the required arguments!\")\n\n parser = argparse.ArgumentParser(\n description=\"pipinstall: a library to download multiple libraries in different domains at once.\")\n parser.add_argument(\"domain_name\",\n help=\"Domain name\",\n type=str)\n\n return parser.parse_args(args)\n# end of check_args\n\n# Main function\n\n\ndef Main():\n\n clear_screen()\n path = pathfinder.domain_path\n print(path)\n print(\"Welcome to pipinstall! A humble try to make our lives easier :')\")\n \n\n\n if check_args(sys.argv[1:]).domain_name:\n required_domain = check_args(sys.argv[1:]).domain_name\n path = os.path.join(path, required_domain) #path=Domains folder/domain_Name\n os.chdir(path) #cwd is now at the domain_Name folder\n\n subprocess.call([sys.executable, \"-m\", \"pip\", \"install\",\"-U\", \"-r\", \"requirements.txt\"])\n\n\n# call Main\nif __name__ == '__main__':\n Main()\n\n","sub_path":"pipinstall.py","file_name":"pipinstall.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"307291105","text":"\"\"\"Test healthcheck and ping\"\"\"\r\nimport json\r\nimport unittest\r\nfrom webapi import APP\r\n\r\n\r\nclass WebApiHealthcheckTests(unittest.TestCase):\r\n \"\"\"Test healthcheck and ping\"\"\"\r\n\r\n def test_ping(self):\r\n \"Ping should return 200\"\r\n response = APP.test_client().get(\"ping\")\r\n self.assertEqual(response.status, \"200 OK\")\r\n\r\n def test_healthcheck(self):\r\n \"Healthcheck should return 200\"\r\n\r\n # Call the api\r\n response = APP.test_client().get(\"healthcheck\")\r\n # Ensure the result is correct\r\n self.assertEqual(response.status, \"200 OK\")\r\n\r\n # Load the response data into json\r\n result = json.loads(response.data)\r\n\r\n # Compare against the expected result\r\n self.assertEqual({'Healthcheck': 'OK'}, result)\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"python/week3/test_healthchecks.py","file_name":"test_healthchecks.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"258420748","text":"#!/usr/local/bin/python\n# -*- coding: utf-8 -*-\n__author__ = 'pavel'\n\nfrom parserBase import ParserBase\nimport globals\n\n#purchaseUrl = \"http://zakupki.gov.ru/223/purchase/public/purchase/info/common-info.html\" \\\n# \"?purchaseId=612198&&purchaseMethodType=ep\"\n\n\n#http://zakupki.gov.ru\n# /223/purchase/public/purchase/info/common-info.html\n# ?purchaseId=628882&purchaseMethodType=IS\n# || || ||\n# \\\\// \\\\// \\\\//\n#http://zakupki.gov.ru\n# /223/purchase/public/purchase/protocol/ip/view-protocol.html\n# ?protocolInfoId=648522&purchaseId=628882\n\nclass Purchase(ParserBase):\n def __init__(self, purchaseParams):\n ParserBase.__init__(self, 'purchase', purchaseParams)\n self.purchaseID = 0\n for purchaseParam in purchaseParams.split(\"&\"):\n try:\n key, val = purchaseParam.split(\"=\")[:2]\n if key == \"purchaseId\":\n self.purchaseID = int(val)\n break\n except:\n pass\n\n def getLastProtocolUrl(self):\n urlForProtocol = \"%s%s?%s\" % (globals.urlBase, globals.urlPaths['protocols'], self.params)\n content = self.geturltext(url=urlForProtocol, showErrorMessage=False)\n if len(content) != 0:\n self.updateSoupFromContent(content)\n #select last protocol if multiple exists\n protocols = self.soup.findAll('p', {'class': 'protocolName'})\n if len(protocols) > 0:\n if (len(protocols) == 1):\n protocol = protocols[0]\n else:\n protocolNumbers = [number.text.split(u'№')[1].strip() for number in protocols]\n protocol = protocols[protocolNumbers.index(max(protocolNumbers))]\n protocolIDValue = int(dict(protocol.attrs)[globals.DOMElementsKeys['purchaseProtocol'][0]])\n proticolPath = \"protocolInfoId=%i&purchaseId=%i\"\n protocolID = proticolPath % (protocolIDValue, self.purchaseID)\n return protocolID\n return None\n\n\n def getLotList(self):\n urlForLot = \"%s%s?%s\" % (globals.urlBase, globals.urlPaths['lotList'], self.params)\n content = self.geturltext(url=urlForLot, showErrorMessage=False)\n if len(content) != 0:\n self.updateSoupFromContent(content)\n table = self.soup.find('table', {'class': 'graytable'})\n keys = [th.text.strip().splitlines()[0].strip() for th in table.thead.findAll('th')[1:]]\n for lot in table.tbody.findAll('tr'):\n values = [td.text.strip().splitlines()[0].strip() for td in lot.findAll('td')[1:]]\n yield dict(zip(keys, values))\n return\n yield\n\n\n def purchaseInfo(self):\n purchaseDict = {}\n for table in self.soup.find('div', {'class': 'tablet'}).findAll('table'):\n nodeName = table.caption.text.strip()\n purchaseDict[nodeName] = {}\n for tr in table.findAll('tr'):\n try:\n (key, value) = tr.findAll('td')[:2]\n purchaseDict[nodeName][key.text.strip()] = value.text.strip()\n except ValueError as err:\n pass\n #skip lines not equal to pattern:\n #<td>key</td><td>value</td>\n return purchaseDict\n\nif __name__ == '__main__':\n twoprotocolpurchase = \"purchaseId=627472&purchaseMethodType=IS\"\n singleprotocolPurchase = \"purchaseId=628882&purchaseMethodType=IS\"\n threeprotocol = \"purchaseId=713262&&purchaseMethodType=is\"\n fourProtocol = \"purchaseId=716070&&purchaseMethodType=is\"\n\n purchaseParcer = Purchase(singleprotocolPurchase)\n print(\"[%s]\" % purchaseParcer.getLastProtocolUrl())\n\n for lot in purchaseParcer.getLotList():\n for k, v in lot.items():\n print(\"%s = %s\" % (k, v))\n\n","sub_path":"goszak/data_crawler/parsers/purchase.py","file_name":"purchase.py","file_ext":"py","file_size_in_byte":3895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"397795053","text":"# coding: utf-8\n\n\"\"\"\n选择排序\n在乱序中选择最小的进行交换位置,放在前边\n假如现在有序列 [54, 26, 93, 17, 77, 31, 44, 55, 20]\n假设最小值是第一个元素,即 54\n从第二个往后找到最小的元素,即17\n让 54 和 17 交换位置,即 [17, 26, 93, 54, 77, 31, 44, 55, 20]\n因为17已经是最小的数了,就没有必要再进行比较了,\n让最小值等于第二个数,即26,重复上述操作\n从第三个往后找到最小的元素,即20\n让 26 和 20 交换位置,即 [17, 20, 93, 54, 77, 31, 44, 55, 26]\n\n。。。\n\n需要重复多少次:\n序列有 n 个数,重复 n-1 次\n\"\"\"\n\ndef select_sort(alist):\n\t# 在做外层,共交换n-1遍\n\tfor j in range(len(alist)-1): # 共交换n-1次\n\t\t# 现做内层,走一遍\n\t\tmax_index = j\n\t\tfor i in range(j+1, len(alist)): # 找最小的元素,要从 j 的下一个开始找到最后一个 \n\t\t\tif alist[max_index] > alist[i]:\n\t\t\t\tmax_index = i # 记录列表中最小元素的下标\n\t\talist[j], alist[max_index] = alist[max_index], alist[j]\n\n\nif __name__ == '__main__':\n\talist = [54, 26, 93, 17, 77, 31, 44, 55, 20]\n\tselect_sort(alist)\n\tprint(alist)\n\n\n","sub_path":"PythonDataStructure/algorithm/03-select_sort.py","file_name":"03-select_sort.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"626413656","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# read csv\nSalary = pd.read_csv(\n r'C:\\Users\\MrFive1001\\Documents\\PycharmProjects\\Kaggle\\learning1\\question1\\lahman-csv_2014-02-14\\Salaries.csv')\nTeam = pd.read_csv(\n r'C:\\Users\\MrFive1001\\Documents\\PycharmProjects\\Kaggle\\learning1\\question1\\lahman-csv_2014-02-14\\Teams.csv')\n\n# head of the table\nprint(Salary.columns)\nprint(Team.columns)\n\n# 分组计算\nsalary = Salary.groupby([Salary.yearID, Salary.teamID], as_index=False).sum()\nprint(salary)\n\n# 合并\nmer = pd.merge(pd.DataFrame(salary), Team[['yearID', 'teamID', 'W']], how='inner', on=['yearID', 'teamID'])\nprint(mer.head(2))\n\n# 画图\n\n# fig = plt.figure()\n# plt.scatter(mer.salary, mer.winRate)\n# plt.show()\n","sub_path":"Algor/MachineLea/000data_analyse/learning1/question1/stat_get.py","file_name":"stat_get.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"231930866","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('solotodo', '0009_producttyperanking'),\n ('hardware', '0005_remove_budget_is_active'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='BudgetActive',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('budget', models.OneToOneField(to='hardware.Budget')),\n ('user_profile', models.ForeignKey(to='solotodo.UserProfile')),\n ],\n ),\n ]\n","sub_path":"hardware/migrations/0006_budgetactive.py","file_name":"0006_budgetactive.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"305953198","text":"#_*_coding=cp949\n#_*_coding: euc-kr\n## 응용예제02\n## 기차 수송량에 따라 순위 매기기\nimport operator # operator 불러오기\n\n## 변수 선언 부분 ##\ntrainTupleList=[('토마스',5),('헨리',8),('에드웓',9),('에밀리',5),\n ('토마스',4),('헨리',7),('토마스',3),('에밀리',8),\n ('퍼시',5),('고든',13)] # 튜플리스트 선언\ntrainDic,trainList={},[] # 딕셔너리 리스트 선언\ntmpTup=None # 임시 변수 선언\ntotalRank,currentRank=1,1 # 전체 순위, 동일한 순위(현재순위) 변수 선언(초기화)\n## 메인 코드 부분 ##\nif __name__==\"__main__\":\n for tmpTup in trainTupleList: # 리스트 값 순서대로 반복\n tName=tmpTup[0] # 이름=리스트 1번째 값 대입\n tWeight=tmpTup[1] # 무게=리스트 2번째 값 대입\n if tName in trainDic: # 대입된 이름이 딕셔너리에 있다면\n trainDic[tName]+=tWeight # 딕셔너리의 동일한 키에 해당하는 값에 무게 추가\n else : # 그 외에는\n trainDic[tName]=tWeight # 새로운 값 등록\n\n print(\"기차 수송량 목록 ==> \", trainTupleList) # 리스트 값 출력 \n print(\"---------------------------\") # 점선 출력\n trainList=sorted(trainDic.items(),key=operator.itemgetter(1),reverse=True)\n # 딕셔너리 값 순서별로 정렬 및 순서 반전 후 리스트에 대입\n print(\"기차\\t총 수송량\\t순위\") # 내용 출력\n print(\"---------------------------\") # 점선 출력\n print(trainList[0][0],'\\t',trainList[0][1],'\\t\\t',currentRank)\n # 리스트의 첫번째 출력(1위 우선 출력)\n for i in range(1,len(trainList)): # 1~리스트 길이까지 반복\n totalRank+=1 # 전체 순위 1 증가\n if trainList[i][1]==trainList[i-1][1] : # 앞기차의 무게와 현재 기차의 무게가 같다면\n pass # if문 pass\n else : # 그렇지 않다면\n currentRank=totalRank #현재 등수에 전체 등수 대입\n print(trainList[i][0],'\\t',trainList[i][1],'\\t\\t',currentRank)\n # 튜플리스트의 i번째 값과 현재 등수 출력\n","sub_path":"Python/과제5/응용예제02-기차 수송량에 따라 순위 매기기.py","file_name":"응용예제02-기차 수송량에 따라 순위 매기기.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"88107504","text":"\"\"\"\n获取阿里云数据方法\n\"\"\"\nimport json\nimport datetime\nimport asyncio\nfrom types import FunctionType\nfrom django.conf import settings\nfrom aliyunsdkcore.client import AcsClient\nfrom aliyunsdkcore.request import CommonRequest\nfrom util.libs import LOCAL_FORMAT, get_logger\n\n\nlogger = get_logger('aliyun.api')\n\n\n# 获取ECS 列表\ndef __get_ecs(client: AcsClient, kwargs) -> list:\n instances_request = CommonRequest(domain=settings.DEPLOY_CONF.get('aliyun_api_address', 'ecs'),\n version='2014-05-26',\n action_name='DescribeInstances')\n instances_request.add_query_param('PageSize', 100)\n return_instances = []\n response = client.do_action_with_exception(instances_request)\n res_instance_list = json.loads(response.decode())['Instances']['Instance']\n return_instances.extend(res_instance_list)\n page_number = 1\n while True:\n page_number += 1\n instances_request.add_query_param('PageNumber', page_number)\n response = client.do_action_with_exception(instances_request)\n res_instance_list = json.loads(response.decode())['Instances']['Instance']\n if not res_instance_list:\n break\n return_instances.extend(res_instance_list)\n\n return return_instances\n\n\n# 获取Disk 信息\ndef __get_disk(client: AcsClient, kwargs) -> list:\n disk_request = CommonRequest(domain=settings.DEPLOY_CONF.get('aliyun_api_address', 'ecs'),\n version='2014-05-26',\n action_name='DescribeDisks')\n disk_request.add_query_param('RegionId', kwargs['region_id'])\n disk_request.add_query_param('InstanceId', kwargs['instance_id'])\n response = client.do_action_with_exception(disk_request)\n res_dict = json.loads(response.decode())\n return res_dict['Disks']['Disk']\n\n\n# 获取RDS 信息\ndef __get_rds(client: AcsClient, kwargs) -> list:\n instances_request = CommonRequest(domain=settings.DEPLOY_CONF.get('aliyun_api_address', 'rds'),\n version='2014-08-15',\n action_name='DescribeDBInstances')\n instances_request.add_query_param('RegionId', kwargs['region_id'])\n instances_request.add_query_param('PageSize', 100)\n response = client.do_action_with_exception(instances_request)\n res_dict = json.loads(response.decode())\n return res_dict['Items']['DBInstance']\n\n\n# 获取nas 信息\ndef __get_nas(client: AcsClient, kwargs) -> list:\n instances_request = CommonRequest(domain=settings.DEPLOY_CONF.get('aliyun_api_address', 'nas'),\n version='2017-06-26',\n action_name='DescribeFileSystems')\n instances_request.add_query_param('RegionId', kwargs['region_id'])\n instances_request.add_query_param('PageSize', 100)\n response = client.do_action_with_exception(instances_request)\n res_dict = json.loads(response.decode())\n return res_dict['FileSystems']['FileSystem']\n\n\n# 获取nas package 信息\ndef __get_nas_package(client: AcsClient, kwargs) -> list:\n instances_request = CommonRequest(domain=settings.DEPLOY_CONF.get('aliyun_api_address', 'nas'),\n version='2016-02-29',\n action_name='DescribeVolumeStoragePackages')\n instances_request.add_query_param('RegionId', kwargs['region_id'])\n instances_request.add_query_param('PageSize', 100)\n response = client.do_action_with_exception(instances_request)\n res_dict = json.loads(response.decode())\n return res_dict['Packages']\n\n\n# 获取vpc 信息\ndef __get_vpn(client: AcsClient, kwargs) -> list:\n instances_request = CommonRequest(domain=settings.DEPLOY_CONF.get('aliyun_api_address', 'vpc'),\n version='2016-04-28',\n action_name='DescribeVpnGateways')\n instances_request.add_query_param('RegionId', kwargs['region_id'])\n response = client.do_action_with_exception(instances_request)\n res_dict = json.loads(response.decode())\n return res_dict['VpnGateways']['VpnGateway']\n\n\n# 获取domain 信息\ndef __get_domain(client: AcsClient, kwargs) -> list:\n instances_request = CommonRequest(domain=settings.DEPLOY_CONF.get('aliyun_api_address', 'domain'),\n version='2018-01-29',\n action_name='QueryDomainList')\n instances_request.add_query_param('RegionId', kwargs['region_id'])\n instances_request.add_query_param('PageSize', 100)\n instances_request.add_query_param('PageNum', 1)\n response = client.do_action_with_exception(instances_request)\n res_dict = json.loads(response.decode())\n return res_dict['Data']['Domain']\n\n\n# 由于阿里云图表数据限制请求数,所以使用时间切割出多次请求的时间\nclass GraphTimeSplit(object):\n\n @staticmethod\n def __base_time_handler(start_time, end_time, count, split_num, time_attr='hours'):\n time_attr_maps = {\n 'hours': datetime.timedelta(hours=split_num),\n 'days': datetime.timedelta(days=split_num)\n }\n time_list = []\n start = start_time\n for _ in range(0, count):\n end = start + time_attr_maps[time_attr]\n time_list.append([start, end])\n start = end\n return time_list\n\n @staticmethod\n def day_0(start_time, end_time):\n return GraphTimeSplit.__base_time_handler(start_time, end_time, 1, 1)\n\n @staticmethod\n def day_1(start_time, end_time):\n return GraphTimeSplit.__base_time_handler(start_time, end_time, 2, 12)\n\n @staticmethod\n def day_3(start_time, end_time):\n return GraphTimeSplit.__base_time_handler(start_time, end_time, 6, 12)\n\n @staticmethod\n def day_7(start_time, end_time):\n return GraphTimeSplit.__base_time_handler(start_time, end_time, 5, 36)\n\n @staticmethod\n def day_30(start_time, end_time):\n return GraphTimeSplit.__base_time_handler(start_time, end_time, 3, 10, time_attr='days')\n\n\n# 获取ecs监控图表信息\ndef __get_graph(client: AcsClient, kwargs) -> list:\n # 这里是使用了协程的玩意来提取数据,不用线程的原因是使用线程可能会更慢(全局锁你懂得)\n #\n # 1 天 period: 60\n # 3 天 period: 60\n # 7 天 period: 300\n # 30 天 period: 900\n def __period_base(period, s_time, e_time):\n try:\n request.add_query_param('Period', period)\n request.add_query_param('StartTime', s_time)\n request.add_query_param('EndTime', e_time)\n response = client.do_action_with_exception(request)\n data_list = json.loads(json.loads(response.decode())['Datapoints'])\n graph_list.extend(data_list)\n except Exception as e:\n logger.error('__period_base has error.')\n logger.exception(e)\n\n async def __period_0(s_time, e_time):\n return __period_base(60, s_time, e_time)\n\n async def __period_60(s_time, e_time):\n return __period_base(60, s_time, e_time)\n\n async def __period_300(s_time, e_time):\n return __period_base(300, s_time, e_time)\n\n async def __period_900(s_time, e_time):\n return __period_base(900, s_time, e_time)\n\n period_maps = {\n 0: __period_0,\n 1: __period_60,\n 3: __period_60,\n 7: __period_300,\n 30: __period_900,\n }\n \"\"\"接收数据格式\n {\n \"metric\": \"cpu_idle\",\n \"region_id\": \"cn-shenzhen\",\n \"days\": 7,\n \"dimensions\": \"[{\"instanceId\": \"i-wz9exmnpyufi62y6dnbc\"}]\"\n }\n \"\"\"\n metric_name = kwargs['metric']\n dimensions = kwargs['dimensions']\n region_id = kwargs['region_id']\n days = kwargs['days']\n namespace = kwargs['namespace']\n end_time = datetime.datetime.now()\n # 0 值为1个小时的数据\n if days == 0:\n start_time = end_time + datetime.timedelta(hours=-1)\n else:\n start_time = end_time + datetime.timedelta(days=-days)\n tmp_address = domain = settings.DEPLOY_CONF.get('aliyun_api_address', 'monitor').split('.')\n tmp_address.insert(1, region_id)\n # 最后的地址如: \tmetrics.cn-shenzhen.aliyuncs.com\n request_address = \".\".join(tmp_address)\n request = CommonRequest(domain=request_address,\n version='2019-01-01',\n action_name='DescribeMetricList')\n request.add_query_param('Namespace', namespace)\n request.add_query_param('Dimensions', dimensions)\n # 来自阿里云 https://help.aliyun.com/document_detail/28619.html?spm=a2c4g.11186623.2.12.5e65659d39LRGT\n metric_numerate = [\n 'cpu_total', # Host.cpu.total,当前消耗的总CPU百分比\n 'cpu_idle', # Host.cpu.idle,当前空闲CPU百分比\n 'memory_usedutilization', # Host.mem.usedutilization,内存使用率\n 'load_1m', # Host.load1,过去1分钟的系统平均负载,Windows操作系统没有此指标\n 'load_5m', # Host.load5, 过去5分钟的系统平均负载,Windows操作系统没有此指标\n 'load_15m', # Host.load15,过去15分钟的系统平均负载,Windows操作系统没有此指标\n 'DiskReadBPS', # 系统磁盘总读BPS\n 'DiskWriteBPS', # 系统磁盘总写BPS\n 'DiskReadIOPS', # 系统磁盘读IOPS\n 'DiskWriteIOPS', # 系统磁盘写IOPS\n 'diskusage_utilization', # Host.disk.utilization,磁盘使用率\n 'disk_readbytes', # Host.disk.readbytes,磁盘每秒读取的字节数\n 'disk_writebytes', # Host.disk.writebytes,磁盘每秒写入的字节数\n 'disk_readiops', # Host.disk.readiops,磁盘每秒的读请求数量\n 'disk_writeiops', # Host.disk.writeiops,磁盘每秒的写请求数量\n 'InternetInRate', # 公网流入带宽\n 'InternetOutRate', # 公网流出带宽\n 'IntranetInRate', # 私网流入带宽\n 'IntranetOutRate', # 私网流出带宽\n ]\n if metric_name not in metric_numerate:\n raise Exception(f'{metric_name} 不在 metric_numerate 里面,请核对。')\n request.add_query_param('MetricName', metric_name)\n time_list = eval(f\"GraphTimeSplit.day_{days}\")(start_time, end_time)\n graph_list = []\n tasks = []\n for i_time in time_list:\n logger.debug(f'''图表时间范围 {i_time[0].strftime(LOCAL_FORMAT)} - {i_time[1].strftime(LOCAL_FORMAT)}''')\n tasks.append(period_maps[days](\n i_time[0].strftime(LOCAL_FORMAT),\n i_time[1].strftime(LOCAL_FORMAT),\n ))\n # print(tasks)\n # 所以如果你asyncio.get_event_loop在主线程中调用一次,\n # 它将自动创建一个循环对象并将其设置为默认值,\n # 但是如果你在一个子线程中再次调用它,你会得到这个错误AssertionError: There is no current event loop in thread ‘Thread-1’.\n # 所以您需要在线程启动时显式创建/设置事件循环\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n loop = asyncio.get_event_loop()\n loop.run_until_complete(asyncio.wait(tasks))\n loop.close()\n return graph_list\n\n\n# 获取ecs监控图表信息\ndef __get_ecs_graph(client: AcsClient, kwargs) -> list:\n # 这是aliyun 云监控 规定的namespace\n kwargs['namespace'] = 'acs_ecs_dashboard'\n return __get_graph(client, kwargs)\n\n\n# 获取aliyun slb 信息\ndef __get_slb(client: AcsClient, kwargs) -> list:\n instances_request = CommonRequest(domain=settings.DEPLOY_CONF.get('aliyun_api_address', 'slb'),\n version='2014-05-15',\n action_name='DescribeLoadBalancers')\n instances_request.set_accept_format('json')\n instances_request.add_query_param('PageSize', 100)\n response = client.do_action_with_exception(instances_request)\n res_instance_list = json.loads(response.decode())\n return res_instance_list.get('LoadBalancers', {}).get('LoadBalancer', [])\n\n\ndef __get_adjust_slb(client: AcsClient, kwargs):\n app_name = kwargs.get('app_name')\n server_id = kwargs.get('server_id')\n weight = kwargs.get('weight')\n lb_id = None\n res_data_dict = None\n slb_list = __get_slb(client, kwargs)\n for slb in slb_list:\n if slb['LoadBalancerName'] == app_name:\n lb_id = slb['LoadBalancerId'] \n \n if lb_id:\n instances_request = CommonRequest(domain=settings.DEPLOY_CONF.get('aliyun_api_address', 'slb'),\n version='2014-05-15',\n action_name='SetBackendServers')\n instances_request.add_query_param('LoadBalancerId', f'{lb_id}')\n instances_request.add_query_param('BackendServers', f'[{{\"ServerId\":\"{server_id}\",\"Weight\":\"{weight}\"}}]')\n response = client.do_action_with_exception(instances_request)\n res_data_dict = json.loads(response.decode())\n return res_data_dict\n\n\ndef __get_rds_graph(client: AcsClient, kwargs):\n metric_numerate = [\n 'MySQL_NetworkTraffic', # MySQL实例平均每秒钟的输入流量,MySQL实例平均每秒钟的输出流量。单位为KB。\n 'MySQL_QPSTPS', # 平均每秒SQL语句执行次数,平均每秒事务数。\n 'MySQL_Sessions', # 当前活跃连接数,当前总连接数。\n 'MySQL_InnoDBBufferRatio', # InnoDB缓冲池的读命中率,InnoDB缓冲池的利用率,InnoDB缓冲池脏块的百分率。\n 'MySQL_InnoDBDataReadWriten', # InnoDB平均每秒钟读取的数据量,InnoDB平均每秒钟写入的数据量。单位为KB。\n 'MySQL_InnoDBLogRequests', # 平均每秒向InnoDB缓冲池的读次数,平均每秒向InnoDB缓冲池的写次数。\n 'MySQL_InnoDBLogWrites', # 平均每秒日志写请求数,平均每秒向日志文件的物理写次数,平均每秒向日志文件完成的fsync()写数量。\n 'MySQL_TempDiskTableCreates', # MySQL执行语句时在硬盘上自动创建的临时表的数量。\n 'MySQL_MyISAMKeyBufferRatio', # MyISAM平均每秒Key Buffer利用率,MyISAM平均每秒Key Buffer读命中率,\n # MyISAM平均每秒Key Buffer写命中率。\n 'MySQL_MyISAMKeyReadWrites', # MyISAM平均每秒钟从缓冲池中的读取次数,MyISAM平均每秒钟从缓冲池中的写入次数,\n # MyISAM平均每秒钟从硬盘上读取的次数,MyISAM平均每秒钟从硬盘上写入的次数。\n 'MySQL_COMDML', # 平均每秒Delete语句执行次数,平均每秒Insert语句执行次数, 平均每秒Insert_Select语句执行次数,\n # 平均每秒Replace语句执行次数,平均每秒Replace_Select语句执行次数,平均每秒Select语句执行次数,平均每秒Update语句执行次数。\n 'MySQL_RowDML', # 平均每秒从InnoDB表读取的行数,平均每秒从InnoDB表更新的行数,平均每秒从InnoDB表删除的行数,\n # 平均每秒从InnoDB表插入的行数,平均每秒向日志文件的物理写次数\n 'MySQL_MemCpuUsage', # MySQL实例CPU使用率(占操作系统总数),MySQL实例内存使用率(占操作系统总数)。\n 'MySQL_IOPS', # MySQL实例的IOPS(每秒IO请求次数)。\n 'MySQL_DetailedSpaceUsage', # MySQL实例空间占用详情:ins_size实例总空间使用量;data_size数据空间;\n # log_size日志空间;tmp_size临时空间;other_size系统空间。\n 'MySQL_CPS', # MySQL实例每秒连接数。\n ]\n metric_name = kwargs.get('metric_name')\n if kwargs.get('metric_name') not in metric_numerate:\n raise Exception(f'{metric_name} 不在 metric_numerate 里面,请核对。')\n instances_request = CommonRequest(domain=settings.DEPLOY_CONF.get('aliyun_api_address', 'rds'),\n version='2014-08-15',\n action_name='DescribeDBInstancePerformance')\n instances_request.add_query_param('DBInstanceId', kwargs.get('db_instance_id'))\n instances_request.add_query_param('Key', metric_name)\n instances_request.add_query_param('StartTime', kwargs.get('start_time'))\n instances_request.add_query_param('EndTime', kwargs.get('end_time'))\n response = client.do_action_with_exception(instances_request)\n res_instance_dict = json.loads(response.decode())\n return res_instance_dict.get('PerformanceKeys').get('PerformanceKey')[0].get('Values').get('PerformanceValue')\n\n\ndef __get_rds_process_list(client: AcsClient, kwargs):\n instances_request = CommonRequest(domain=settings.DEPLOY_CONF.get('aliyun_api_address', 'rds'),\n version='2014-08-15',\n action_name=\"DescribeCloudDBAService\")\n instances_request.add_query_param('ServiceRequestType', 'ShowProcessList')\n instances_request.add_query_param('ServiceRequestParam', \"{\\\"Language\\\":\\\"zh\\\",\\\"Command\\\":\\\"Not Sleep\\\"}\")\n instances_request.add_query_param('DBInstanceId', kwargs.get('db_instance_id'))\n response = client.do_action_with_exception(instances_request)\n res_instance_dict = json.loads(response.decode())\n return json.loads(res_instance_dict.get('AttrData')).get('ProcessList')\n\n\n# 调用入口\ndef get_aliyun_resource(access_key: str, access_secret: str, region_id: str, resource: str='ecs', kwargs=None) -> list:\n if not kwargs:\n kwargs = {}\n client = AcsClient(access_key, access_secret, region_id)\n assert isinstance(eval(f'__get_{resource}'), FunctionType), f'aliyun_api 不存在 {resource} 资源'\n return eval(f'__get_{resource}')(client, kwargs)\n","sub_path":"src/private/cmdb/cloud/aliyun/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":17711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"29573665","text":"# Elaborar um algoritmo que efetue a apresentação do valor de\r\n# conversão em real (R$) de um valor lido em dólar (US$). O algoritmo\r\n# deverá solicitar o valor da cotação do dólar e também a quantidade de\r\n# dólares disponíveis com o usuários\r\n\r\n# Data: 17/02/2020\r\n# Autor: Gustavo Alves da Silva\r\n\r\ndolares = float(input('Quantidade de dinheiro em dólares: US$ '))\r\ncotacao = float(input('Cotação do dólar: R$ '))\r\nreais = dolares * cotacao\r\nprint('A quantidade de dinheiro em reais é de: R$ {:.2f}'.format(reais))","sub_path":"Alg08.py","file_name":"Alg08.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"604005737","text":"import pandas as pd\r\nimport numpy as np\r\nfrom datetime import datetime\r\nimport glob\r\nimport sys\r\nimport re\r\nimport os\r\n\r\nimport utils\r\nfrom utils import data_importer\r\n\r\nimport math\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport tensorflow as tf\r\nfrom tensorflow.python.framework import ops\r\n\r\nfrom sklearn import preprocessing\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n\r\ndef metadata_importer(path):\r\n\twith open(path, 'r') as f:\r\n\t\tdf = pd.read_csv(f)\r\n\r\n\t# change user id from float to str\r\n\tdf['user_id'] = list(map(lambda x: '0' * (3 - len(str(int(x)))) + str(int(x)), df['user_id']))\r\n\r\n\t# change datetime from str to datetime.datetime\r\n\tdf['datetime'] = list(map(lambda s: datetime.strptime(s, '%Y-%m-%d %H:%M:%S'), df['end_time'].values))\r\n\r\n\tprint_with_log('Metadata import complete!')\r\n\treturn df\r\n\r\n\r\ndef label_encoding(y_orig):\r\n\tle = preprocessing.LabelEncoder()\r\n\tle.fit(y_orig)\r\n\ty_orig = le.transform(y_orig)\r\n\r\n\treturn y_orig\r\n\r\n\r\ndef convert_to_one_hot(Y, num_features):\r\n\tY = np.eye(num_features)[Y.reshape(-1)].T\r\n\treturn Y\r\n\r\n\r\ndef calculate_box_plot_characteristics(my_list: list):\r\n\tresult = {}\r\n\t\r\n\tresult[\"minimum\"] = np.min(my_list)\r\n\tresult[\"maximum\"] = np.max(my_list)\r\n\tresult[\"median\"] = np.median(my_list)\r\n\t\r\n\tq1 = np.percentile(my_list, 25)\r\n\tq3 = np.percentile(my_list, 75)\r\n\tiqr = q3 - q1\r\n\tresult[\"lower_quartile\"] = q1\r\n\tresult[\"upper_quartile\"] = q3\r\n\t\r\n\tlower_whisker = q1 - 1.5 * iqr\r\n\tupper_whisker = q3 + 1.5 * iqr\r\n\trpa_sort = np.sort(my_list)\r\n\tfor i in range(len(rpa_sort)):\r\n\t\tif rpa_sort[i] > lower_whisker:\r\n\t\t\tresult[\"lower_whisker\"] = rpa_sort[i]\r\n\t\t\tbreak\r\n\tfor i in reversed(range(len(rpa_sort))):\r\n\t\tif rpa_sort[i] < upper_whisker:\r\n\t\t\tresult[\"upper_whisker\"] = rpa_sort[i]\r\n\t\t\tbreak\r\n\t\r\n\treturn result\r\n\r\n\r\ndef initialize_parameters(params_size: list):\r\n\t\"\"\"\r\n\tInitializes parameters to build a neural network with tensorflow.\r\n\r\n\tReturns:\r\n\tparameters -- a dictionary of tensors containing list W and list b\r\n\t\"\"\"\r\n\r\n\tW = [None for i in range(len(params_size) - 1)]\r\n\tb = [None for i in range(len(params_size) - 1)]\r\n\r\n\tfor i in range(len(params_size) - 1):\r\n\t\tW[i] = tf.get_variable('W'+str(i), [params_size[i+1], params_size[i]], initializer = tf.contrib.layers.xavier_initializer())\r\n\t\tb[i] = tf.get_variable('b'+str(i), [params_size[i+1], 1], initializer = tf.zeros_initializer())\r\n\r\n\tparameters = {'W': W, 'b': b}\r\n\t\r\n\treturn parameters\r\n\r\n\r\ndef forward_propagation(X, parameters):\r\n\t\"\"\"\r\n\tImplements the forward propagation for the model: (LINEAR -> RELU) * k -> LINEAR -> SOFTMAX\r\n\t\r\n\tArguments:\r\n\tX -- input dataset placeholder, of shape (input size, number of examples)\r\n\tparameters -- python dictionary containing parameters list W and list b\r\n\r\n\tReturns:\r\n\tZ_out -- the output of the last LINEAR unit\r\n\t\"\"\"\r\n\t\r\n\t# Retrieve the parameters from the dictionary \"parameters\" \r\n\tW = parameters['W']\r\n\tb = parameters['b']\r\n\r\n\tZ = [None for i in range(len(W) - 1)]\r\n\tA = [None for i in range(len(W) - 1)]\r\n\r\n\tfor i in range(len(W)):\r\n\t\tif i == 0:\r\n\t\t\tZ[i] = tf.matmul(W[i], X) + b[i]\r\n\t\t\tA[i] = tf.nn.relu(Z[i])\r\n\t\telif i != len(W) - 1:\r\n\t\t\tZ[i] = tf.matmul(W[i], A[i-1]) + b[i]\r\n\t\t\tA[i] = tf.nn.relu(Z[i])\r\n\t\telse:\r\n\t\t\tZ_out = tf.matmul(W[i], A[i-1]) + b[i]\r\n\r\n\treturn Z_out\r\n\r\n\r\ndef compute_cost(Z_out, Y, parameters, lambd, m):\r\n\t\"\"\"\r\n\tCompute cost using L2 regularization.\r\n\t\r\n\tArguments:\r\n\tZ_out -- the output of the last LINEAR unit\r\n\tY -- labels placeholder, of shape (number of classes, number of examples)\r\n\tparameters -- python dictionary containing parameters list W and list b\r\n\tlambd -- L2 Regularization parameter\r\n\tm -- number of examples used to calculate L2 Regularization\r\n\r\n\tReturns:\r\n\tcost -- cost with L2 regularization\r\n\t\"\"\"\r\n\t# Retrieve the parameters from the dictionary \"parameters\" \r\n\tW = parameters['W']\r\n\t\r\n\tlogits = tf.transpose(Z_out)\r\n\tlabels = tf.transpose(Y)\r\n\t\r\n\tcost_cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels))\r\n\tif lambd != None:\r\n\t\tcost_L2_regularization = 1/m * lambd/2 * np.sum([tf.square(tf.norm(W[i], ord=2)) for i in range(len(W))])\r\n\telse:\r\n\t\tcost_L2_regularization = 0\r\n\tcost = cost_cross_entropy + cost_L2_regularization\r\n\t\r\n\treturn cost\r\n\r\n\r\ndef random_mini_batches(X, Y, mini_batch_size):\r\n\t\"\"\"\r\n\tCreates a list of random minibatches from (X, Y)\r\n\t\r\n\tArguments:\r\n\tX -- input data, of shape (input size, number of examples)\r\n\tY -- true \"label\" vector\r\n\tmini_batch_size - size of the mini-batches, integer\r\n\t\r\n\tReturns:\r\n\tmini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)\r\n\t\"\"\"\r\n\t\r\n\tm = X.shape[1] # number of training examples\r\n\tmini_batches = []\r\n\t# np.random.seed(seed)\r\n\t\r\n\t# Step 1: Shuffle (X, Y)\r\n\tpermutation = list(np.random.permutation(m))\r\n\tshuffled_X = X[:, permutation]\r\n\tshuffled_Y = Y[:, permutation].reshape((Y.shape[0],m))\r\n\r\n\t# Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.\r\n\tnum_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning\r\n\tfor k in range(0, num_complete_minibatches):\r\n\t\tmini_batch_X = shuffled_X[:, k * mini_batch_size : k * mini_batch_size + mini_batch_size]\r\n\t\tmini_batch_Y = shuffled_Y[:, k * mini_batch_size : k * mini_batch_size + mini_batch_size]\r\n\t\tmini_batch = (mini_batch_X, mini_batch_Y)\r\n\t\tmini_batches.append(mini_batch)\r\n\t\r\n\t# Handling the end case (last mini-batch < mini_batch_size)\r\n\tif m % mini_batch_size != 0:\r\n\t\tmini_batch_X = shuffled_X[:, num_complete_minibatches * mini_batch_size : m]\r\n\t\tmini_batch_Y = shuffled_Y[:, num_complete_minibatches * mini_batch_size : m]\r\n\t\tmini_batch = (mini_batch_X, mini_batch_Y)\r\n\t\tmini_batches.append(mini_batch)\r\n\t\r\n\treturn mini_batches\r\n\r\n\r\ndef model(X_train, Y_train, X_test, Y_test, params_size, learning_rate = 0.005,\r\n\t\t num_epochs = 100, minibatch_size = 1024, lambd = 0.2, print_cost = True, continue_flag=False):\r\n\t\"\"\"\r\n\tImplements a neural network: (LINEAR -> RELU) * k -> LINEAR -> SOFTMAX.\r\n\t\r\n\tArguments:\r\n\tX_train -- training set\r\n\tY_train -- test set\r\n\tX_test -- training set\r\n\tY_test -- test set\r\n\tlearning_rate -- learning rate of the optimization\r\n\tnum_epochs -- number of epochs of the optimization loop\r\n\tminibatch_size -- size of a minibatch\r\n\tlambd -- L2 Regularization parameter\r\n\tprint_cost -- True to print the cost every epochs\r\n\tcontinue_flag -- True to continue from last checkpoint. If continue, make sure that you have only one model in the folder ./nn_mode\r\n\t\"\"\"\r\n\t\r\n\tops.reset_default_graph() # to be able to rerun the model without overwriting tf variables\r\n\t(n_x, m) = X_train.shape # (n_x: input size, m : number of examples in the train set)\r\n\tn_y = Y_train.shape[0] # n_y : output size\r\n\t\r\n\t# Create Placeholders of shape (n_x, n_y)\r\n\tX = tf.placeholder(tf.float32, [n_x, None], name='X')\r\n\tY = tf.placeholder(tf.float32, [n_y, None], name='Y')\r\n\r\n\tparameters = initialize_parameters(params_size)\r\n\tZ_out = forward_propagation(X, parameters)\r\n\tcost = compute_cost(Z_out, Y, parameters, lambd, minibatch_size)\r\n\toptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\r\n\tinit = tf.global_variables_initializer()\r\n\t\r\n\tsaver = tf.train.Saver(max_to_keep=0)\r\n\t\r\n\t# find the number of epochs of last checkpoint\r\n\tstart_epoch = 0\r\n\tif continue_flag:\r\n\t\tfor file in glob.glob('nn_model/*.index'):\r\n\t\t\tstart_epoch = int(re.findall('[0-9]{3,4}', file)[0])\r\n\r\n\t# Start the session to compute the tensorflow graph\r\n\twith tf.Session() as sess:\r\n\t\tif not continue_flag:\r\n\t\t\tsess.run(init)\r\n\t\telse:\r\n\t\t\tsaver.restore(sess, tf.train.latest_checkpoint('nn_model'))\r\n\t\t\r\n\t\t# Do the training loop\r\n\t\tfor epoch in range(start_epoch, num_epochs + 1):\r\n\r\n\t\t\tepoch_cost = 0. # Defines a cost related to an epoch\r\n\t\t\tnum_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set\r\n\t\t\tminibatches = random_mini_batches(X_train, Y_train, minibatch_size)\r\n\r\n\t\t\tfor minibatch in minibatches:\r\n\t\t\t\t# Select a minibatch\r\n\t\t\t\t(minibatch_X, minibatch_Y) = minibatch\r\n\t\t\t\t\r\n\t\t\t\t_ , minibatch_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y})\r\n\t\t\t\tepoch_cost += minibatch_cost / num_minibatches\r\n\r\n\t\t\t# Print the cost every 10 epochs\r\n\t\t\tif print_cost == True and epoch % 10 == 0:\r\n\t\t\t\tprint_with_log(\"Cost after epoch {}: {}\".format(epoch, epoch_cost))\r\n\t\t\t\twrite_cost(epoch_cost)\r\n\t\t\t\t\r\n\t\t\t# Save the model every 100 epochs\r\n\t\t\tif print_cost == True and epoch % 100 == 0:\r\n\t\t\t\t# saver.save(sess, 'nn_model/save_net', global_step=epoch)\r\n\t\t\t\tprint_with_log('----------------------------------')\r\n\t\t\t\tcorrect_prediction = tf.equal(tf.argmax(Z_out), tf.argmax(Y))\r\n\t\t\t\taccuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\r\n\r\n\t\t\t\tprint_with_log(\"Train Accuracy: {}\".format(accuracy.eval({X: X_train, Y: Y_train})))\r\n\t\t\t\tprint_with_log(\"Test Accuracy: {}\".format(accuracy.eval({X: X_test, Y: Y_test})))\r\n\t\t\t\t# print_with_log(\"Saved checkpoint!\")\r\n\t\t\t\tprint_with_log('----------------------------------')\r\n\r\n\t\t# Save the parameters in a variable\r\n\t\tparameters = sess.run(parameters)\r\n\t\tprint_with_log(\"Parameters have been trained!\")\r\n\t\t\r\n\r\ndef compute_accuracies(X_train, Y_train, X_test, Y_test, params_size):\r\n\t(n_x, m) = X_train.shape\r\n\tn_y = Y_train.shape[0]\r\n\t\r\n\t# Create Placeholders of shape (n_x, n_y)\r\n\tX = tf.placeholder(tf.float32, [n_x, None], name='X')\r\n\tY = tf.placeholder(tf.float32, [n_y, None], name='Y')\r\n\r\n\tparameters = initialize_parameters(params_size)\r\n\tZ_out = forward_propagation(X, parameters)\r\n\tcost = compute_cost(Z_out, Y, parameters, lambd, minibatch_size)\r\n\tsaver = tf.train.Saver(max_to_keep=0)\r\n\r\n\twith tf.Session() as sess:\r\n\t\tsaver.restore(sess, tf.train.latest_checkpoint('nn_model'))\r\n\t\tcorrect_prediction = tf.equal(tf.argmax(Z_out), tf.argmax(Y))\r\n\t\taccuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\r\n\r\n\t\tprint_with_log(\"Train Accuracy: {}\".format(accuracy.eval({X: X_train, Y: Y_train})))\r\n\t\tprint_with_log(\"Test Accuracy: {}\".format(accuracy.eval({X: X_test, Y: Y_test})))\r\n\r\n\r\ndef training(train_index, log_path, csv_path):\r\n\twith open(log_path + 'log.txt', 'w') as f:\r\n\t\tf.write('----------- Training #{} ------------\\n'.format(train_index))\r\n\t\t# f.write('----------- learning_rate: {} ------------\\n'.format(learning_rate))\r\n\twith open(log_path + 'costs.txt', 'w') as f:\r\n\t\tf.write('Training #{}\\n'.format(train_index))\r\n\r\n\tdf = metadata_importer(csv_path)\r\n\r\n\tX_orig = df.iloc[:, :4]\r\n\ty_orig = df.iloc[:, 4]\r\n\r\n\t# label encoding\r\n\ty_orig = label_encoding(y_orig)\r\n\tprint_with_log('-----------------------------------')\r\n\tprint_with_log('shape of X_orig: {}'.format(X_orig.shape))\r\n\tprint_with_log('shape of y_orig: {}'.format(y_orig.shape))\r\n\r\n\t# # train set and test set spliting \r\n\tX_train_orig, X_test_orig, y_train_orig, y_test_orig = train_test_split(X_orig, y_orig, test_size=0.3)\r\n\tprint_with_log('shape of X_train_orig: {}'.format(X_train_orig.shape))\r\n\tprint_with_log('shape of y_train_orig: {}'.format(y_train_orig.shape))\r\n\tprint_with_log('shape of X_test_orig: {}'.format(X_test_orig.shape))\r\n\tprint_with_log('shape of y_test_orig: {}'.format(y_test_orig.shape))\r\n\tprint_with_log('-----------------------------------')\r\n\r\n\tmode_set = set(df['mode'].values)\r\n\r\n\t# Flatten the training and test images\r\n\tX_train = np.array(X_train_orig).reshape(X_train_orig.shape[0], -1).T\r\n\tX_test = np.array(X_test_orig).reshape(X_test_orig.shape[0], -1).T\r\n\r\n\t# Convert training and test labels to one hot matrices\r\n\ty_train = convert_to_one_hot(np.array(y_train_orig), len(mode_set))\r\n\ty_test = convert_to_one_hot(np.array(y_test_orig), len(mode_set))\r\n\r\n\tprint_with_log(\"number of training examples = \" + str(X_train.shape[1]))\r\n\tprint_with_log(\"number of test examples = \" + str(X_test.shape[1]))\r\n\tprint_with_log(\"X_train shape: \" + str(X_train.shape))\r\n\tprint_with_log(\"Y_train shape: \" + str(y_train.shape))\r\n\tprint_with_log(\"X_test shape: \" + str(X_test.shape))\r\n\tprint_with_log(\"Y_test shape: \" + str(y_test.shape))\r\n\tprint_with_log('-----------------------------------')\r\n\r\n\t# normalization\r\n\tfor i in range(len(X_train)):\r\n\t\tX_train[i] = X_train[i] / calculate_box_plot_characteristics(X_train[i])['upper_whisker']\r\n\tfor i in range(len(X_test)):\r\n\t\tX_test[i] = X_test[i] / calculate_box_plot_characteristics(X_test[i])['upper_whisker']\r\n\r\n\t# define hyperparameters\r\n\thyperparams = {'params_size': [4, 8, 16, 32, 64, 128, 64, 32, 16, 11], \r\n\t\t\t 'learning_rate': 0.001, \r\n\t\t\t 'num_epochs': 2000, \r\n\t\t\t 'minibatch_size': 128, \r\n\t\t\t 'lambda': 0.1}\r\n\tprint_with_log('hyperparams:')\r\n\tfor item in hyperparams.keys():\r\n\t\tprint_with_log(' - ' + item + ': ' + str(hyperparams[item]))\r\n\tprint_with_log('-----------------------------------')\r\n\tprint_with_log('-------------Training--------------')\r\n\tprint_with_log('-----------------------------------')\r\n\r\n\t# train the model\r\n\tmodel(X_train, y_train, X_test, y_test, \r\n\t\t\thyperparams['params_size'], hyperparams['learning_rate'], hyperparams['num_epochs'], \r\n\t\t\thyperparams['minibatch_size'], hyperparams['lambda'], continue_flag=False)\r\n\r\n\tos.rename(log_path + 'log.txt', log_path + 'log #{}.txt'.format(train_index))\r\n\tos.rename(log_path + 'costs.txt', log_path + 'costs #{}.txt'.format(train_index))\r\n\r\n\r\ndef print_with_log(output):\r\n\tlog_path = './nn_model/'\r\n\tprint(output)\r\n\twith open(log_path + 'log.txt', 'a') as f:\r\n\t\tf.write(output + '\\n')\r\n\r\n\r\ndef write_cost(epoch_cost):\r\n\tlog_path = './nn_model/'\r\n\twith open(log_path + 'costs.txt', 'a') as f:\r\n\t\tf.write(str(epoch_cost) + '\\n')\r\n\r\n\r\ndef main():\r\n\tcsv_path = './metadata_df.csv'\r\n\tlog_path = './nn_model/'\r\n\r\n\tuser_input = input(\"Training #\")\r\n\ttry:\r\n\t\ttrain_index = int(user_input)\r\n\texcept:\r\n\t\traise ValueError(\"Not an integer!\")\r\n\r\n\tif not os.path.exists(log_path):\r\n\t\tos.makedirs(log_path)\r\n\r\n\t# tuning learning rate, from 0.0001 to 1, take logrithmic metric, do 20 times tests\r\n\t# for train_index in range(1, 21):\r\n\t# \tr = -4 * np.random.rand()\r\n\t# \tlearning_rate = 10 ** r\r\n\t# \ttraining(train_index, log_path, csv_path, learning_rate)\r\n\r\n\ttraining(train_index, log_path, csv_path)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n","sub_path":"neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":14209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"439398890","text":"from keras.models import load_model\r\nfrom tensorflow.keras.preprocessing.image import img_to_array\r\nfrom keras.preprocessing import image\r\nimport numpy as np\r\nimport cv2\r\n\r\ndef convertBack(x, y, w, h):\r\n xmin = int(round(x - (w / 2)))\r\n xmax = int(round(x + (w / 2)))\r\n ymin = int(round(y - (h / 2)))\r\n ymax = int(round(y + (h / 2)))\r\n return xmin, ymin, xmax, ymax\r\n\r\n\r\nfilepath = 'Asian_First_Try.h5'\r\n\r\nclass_list = ['Happy', 'Others']\r\n# dimensions of our images\r\nimg_width, img_height = 48, 48\r\n\r\n# Load the model\r\nmodel = load_model(filepath)\r\nmodel.compile(loss='binary_crossentropy',\r\n optimizer='rmsprop',\r\n metrics=['accuracy'])\r\n\r\n\r\n# summarize input and output shape\r\nprint(model.inputs)\r\nprint(model.outputs)\r\n\r\n# predicting images\r\nimg = image.load_img('asian_angry.jpg', target_size=(img_width, img_height))\r\nx = image.img_to_array(img)\r\nx = np.expand_dims(x, axis=0)\r\n\r\nimages = np.vstack([x])\r\nclasses = model.predict_classes(images, batch_size=10)\r\nprint (class_list[classes.astype(int)[0][0]])\r\n\r\n\r\n# face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')\r\n\r\n# orig = cv2.imread('therocksad2.jpg')\r\n# # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n# image = cv2.cvtColor(orig, cv2.COLOR_BGR2RGB)\r\n# image = cv2.resize(image, (64, 64))\r\n\r\n\r\n# faces = face_cascade.detectMultiScale(image, 1.3, 5)\r\n\r\n# image = image.astype(\"float\") / 255.0\r\n\r\n# image = img_to_array(image)\r\n# image = np.expand_dims(image, axis=0)\r\n\r\n\r\n\r\n# for (x,y,w,h) in faces:\r\n \r\n# sub_face = image[y:y+h, x:x+w]\r\n\r\n# # make predictions on the input image\r\n# pred = model.predict(sub_face)\r\n# pred = pred.argmax(axis=1)[0]\r\n# print (pred)\r\n \r\n # img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)\r\n # font = cv2.FONT_HERSHEY_DUPLEX\r\n \r\n # dim = (img_width, img_height)\r\n # # resize image\r\n # resized = cv2.resize(sub_face, dim, interpolation = cv2.INTER_AREA)\r\n\r\n # x = image.img_to_array(resized)\r\n # x = np.expand_dims(x, axis=0)\r\n\r\n # images = np.vstack([x])\r\n # classes = np.argmax(model.predict(images), axis=-1)\r\n # print (classes)\r\n\r\n\r\n # cv2.putText(img,\r\n # class_list[classes.astype(int)[0]],\r\n # # \"test\",\r\n # (40, 40), cv2.FONT_HERSHEY_SIMPLEX, 1,\r\n # (0, 0, 255), 2)\r\n \r\n\r\n# cv2.imshow('img',img)\r\n# cv2.waitKey(0)\r\n# cv2.destroyAllWindows()\r\n","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"32911672","text":"# -*- coding: utf-8 -*-\n\"\"\"The Windows Search DB event formatter.\"\"\"\n\nfrom __future__ import unicode_literals\n\nfrom plaso.formatters import interface\nfrom plaso.formatters import manager\n\nimport sys\n\n'''class WindowsSearchdbFormatter(interface.ConditionalEventFormatter):'''\nclass WindowsSearchdbFormatter(interface.ConditionalEventFormatter):\n \"\"\"Formatter for a Windows Search DB event.\"\"\"\n\n DATA_TYPE = 'windows:searchdb:execution'\n\n FORMAT_STRING_PIECES = [\n 'ID: {ID}',\n 'Name: {Name}',\n 'IType: {IType}',\n 'Owner: {Owner}',\n 'IURL: {IURL}',\n 'IAttr: {IAttr}',\n 'IsFolder: {IsFolder}',\n 'Size: {Size}',\n 'GatherDT: {GatherDT}',\n 'CreateDT: {CreateDT}',\n 'ModifyDT: {ModifyDT}',\n 'AccessDT: {AccessDT}',\n 'SUMMARY: {SUMMARY}',\n 'Title: {Title}',\n 'Subject: {Subject}',\n 'Comment: {Comment}',\n 'Label: {Label}',\n 'Text: {Text}',\n 'APPName: {APPName}',\n\n ]\n\n SOURCE_LONG = 'WinSearchDB'\n SOURCE_SHORT = 'LOG'\n\n FORMAT_LIST = ['ID', 'Name', 'IType', 'Owner', 'IURL', 'IAttr', 'IsFolder', 'Size', 'GatherDT', 'CreateDT', 'ModifyDT', 'AccessDT', 'SUMMARY', 'Title', 'Subject', 'Comment', 'Label', 'Text', 'APPName']\n\n def GetMessages(self, formatter_mediator, event):\n event_values = event.CopyToDict()\n for key in self.FORMAT_LIST:\n ret = event_values.get(key, None)\n event_values[key] = ret\n return self._ConditionalFormatMessages(event_values)\n\nmanager.FormattersManager.RegisterFormatter(WindowsSearchdbFormatter)\n","sub_path":"plaso/formatters/winsearchdb.py","file_name":"winsearchdb.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"150694831","text":"#!/usr/bin/python3\n\"\"\" New module for a view to City objects\n\"\"\"\nfrom api.v1.views import app_views\nfrom flask import jsonify\nfrom flask import abort\nfrom models import storage\nfrom models.state import State\nfrom flask import request\nfrom models.city import City\n\n\n@app_views.route(\"/states/<state_id>/cities\", methods=[\"POST\"],\n strict_slashes=False)\ndef new_city(state_id):\n \"\"\"Creates a City\n \"\"\"\n state = storage.get(State, state_id)\n if state is None:\n abort(404)\n\n new_obj = request.get_json()\n if new_obj is None:\n abort(400, \"Not a JSON\")\n\n if \"name\" not in new_obj.keys():\n abort(400, \"Missing name\")\n\n new_obj[\"state_id\"] = state_id\n new_city = City(**new_obj)\n new_city.save()\n storage.reload()\n return jsonify(new_city.to_dict()), 201\n\n\n@app_views.route(\"/cities/<city_id>\", methods=[\"PUT\"], strict_slashes=False)\ndef update_city(city_id):\n \"\"\"Updates a City object\n \"\"\"\n city = storage.get(City, city_id)\n if city is None:\n abort(404)\n\n new_obj = request.get_json()\n if new_obj is None:\n abort(400, \"Not a JSON\")\n\n for key, value in new_obj.items():\n if key not in [\"id\", \"state_id\", \"created_at\", \"updated_at\"]:\n setattr(city, key, value)\n\n city.save()\n storage.reload()\n return jsonify(city.to_dict()), 200\n\n\n@app_views.route(\"/states/<state_id>/cities\", methods=[\"GET\"],\n strict_slashes=False)\ndef cities_of_state(state_id):\n \"\"\"Retrieves list of all cities in a state\n \"\"\"\n list_res = []\n\n state = storage.get(State, state_id)\n if state is None:\n abort(404)\n cities = storage.all(City)\n for city in cities.values():\n if city.state_id == state.id:\n list_res.append(city.to_dict())\n return jsonify(list_res)\n\n\n@app_views.route(\"/cities/<city_id>\", methods=[\"DELETE\"],\n strict_slashes=False)\ndef delete_city(city_id):\n \"\"\"Deletes a city by its id\n \"\"\"\n city = storage.get(City, city_id)\n if city is None:\n abort(404)\n storage.delete(city)\n storage.save()\n storage.reload()\n return jsonify({}), 200\n\n\n@app_views.route(\"/cities/<city_id>\", methods=[\"GET\"], strict_slashes=False)\ndef city_by_id(city_id):\n \"\"\"Retrieves a City object by its id\n \"\"\"\n city = storage.get(City, city_id)\n if city is None:\n abort(404)\n return jsonify(city.to_dict())\n","sub_path":"api/v1/views/cities.py","file_name":"cities.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"545572772","text":"from flask import (\n Blueprint,\n session,\n request,\n redirect,\n url_for,\n render_template,\n)\nfrom models.board import Board\nfrom routes.auth import bp_user\nfrom routes.topic import bp_topic\nfrom routes import current_user\n\n\nbp_board = Blueprint('bp_board', __name__)\n\n\ndef role_check():\n user = current_user()\n if user is not None and user.role == 1:\n return True\n return False\n\n\n@bp_board.route('/admin')\ndef index():\n if role_check() is False:\n return redirect(url_for('bp_user.login'))\n bs = Board.all()\n return render_template('board/admin_index.html', bs=bs)\n\n\n@bp_board.route('/add', methods=['POST'])\ndef add():\n if role_check() is False:\n return redirect(url_for('bp_user.login'))\n\n form = request.form\n m = Board.new(form)\n return redirect(url_for('bp_topic.index'))\n\n\n@bp_board.route('/delete/<int:board_id>')\ndef delete(board_id):\n board = Board.find(board_id)\n print(board)\n if current_user() is False:\n return redirect(url_for('bp_user.login'))\n m = board.delete()\n if m is not None:\n return redirect(url_for('.index'))\n return redirect(url_for('bp_topic.index'))\n","sub_path":"routes/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"523507557","text":"import torch.nn as nn\n\nclass CNN(nn.Module):\n def __init__(self):\n super(CNN, self).__init__()\n # formula for calculation a dimension after a conv or a pooling:\n # Wout =1+ (Win-F+2P)/S\n # Win width of input, F filter size, P the padding, S the stride\n\n self.layer1 = nn.Sequential(\n nn.Conv2d(1, 32, 5, 1, 2),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2)\n ) # output 14*14 images\n self.layer2 = nn.Sequential(\n nn.Conv2d(32, 64, 5, 1, 2),\n nn.ReLU(),\n nn.MaxPool2d(2, 2)\n ) # output 7*7 images\n self.drop_out = nn.Dropout()\n self.layer3 = nn.Linear(7*7*64, 100)\n self.layer4 = nn.Linear(100, 10)\n\n def forward(self, input):\n out = self.layer1(input)\n out = self.layer2(out)\n out = out.reshape(out.size(0), -1)\n out = self.drop_out(out)\n out = self.layer3(out)\n out = self.layer4(out)\n return out\n","sub_path":"src/mnistCNN/CNN.py","file_name":"CNN.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"294942678","text":"#!/usr/bin/env python3\n#-----------------------------------------------------------------------------\n# Title : EPICS test script\n#-----------------------------------------------------------------------------\n# File : testServer.py\n# Created : 2018-02-28\n#-----------------------------------------------------------------------------\n# This file is part of the rogue_example software. It is subject to \n# the license terms in the LICENSE.txt file found in the top-level directory \n# of this distribution and at: \n# https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html. \n# No part of the rogue_example software, including this file, may be \n# copied, modified, propagated, or distributed except according to the terms \n# contained in the LICENSE.txt file.\n#-----------------------------------------------------------------------------\nimport pyrogue\nimport pyrogue.interfaces.simulation\nimport pyrogue.protocols.epics\nimport pyrogue.utilities.prbs\nimport rogue.interfaces.stream\nimport surf.axi\nimport time\nimport rogue\n\n#rogue.Logging.setLevel(rogue.Logging.Debug)\n\nclass EpicsStream(rogue.interfaces.stream.Slave,rogue.interfaces.stream.Master):\n def __init__(self):\n rogue.interfaces.stream.Slave.__init__(self)\n rogue.interfaces.stream.Master.__init__(self)\n\n def _acceptFrame(self,frame):\n print(\"Got frame: size={}\".format(frame.getPayload()))\n\n def genFrame(self,size):\n frame = self._reqFrame(size,True)\n ba = bytearray(size)\n frame.write(ba,0)\n self._sendFrame(frame)\n\ndef printVal(path,value,disp):\n print(f\"Var set {path}, value {value}, disp {disp}\")\n\ndef setPad(tree):\n for i in range(1000000):\n tree.AxiVersion.ScratchPad.set(i)\n\nclass DummyTree(pyrogue.Root):\n\n def __init__(self):\n\n pyrogue.Root.__init__(self,name='dummyTree',description=\"Dummy tree for example\")\n\n # Use a memory space emulator\n sim = pyrogue.interfaces.simulation.MemEmulate()\n \n # Add Device\n self.add(surf.axi.AxiVersion(memBase=sim,offset=0x0))\n #self.AxiVersion.ScratchPad.addListener(printVal)\n\n self.epicsStream = EpicsStream()\n\n v = (pyrogue.LocalVariable(name='listVar',value=[0,1,2,3,4,5,6,7,8,9,10]))\n v.addListener(printVal)\n self.add(v)\n\n v = (pyrogue.LocalVariable(name='strVar',value=\"test\"))\n v.addListener(printVal)\n self.add(v)\n\n self.ptx = rogue.utilities.Prbs()\n\n self.fifo = rogue.interfaces.stream.Fifo(0, 0x4000000)\n pyrogue.streamConnect(self.ptx,self.fifo)\n\n # Start the tree\n self.start()\n\n self.epics = pyrogue.protocols.epics.EpicsCaServer(base='test',root=self)\n self.es = self.epics.createSlave('slave',0x1000000,'UInt32')\n #self.es = self.epics.createSlave('slave',0x1000,'UInt32')\n self.em = self.epics.createMaster('mast',0x1000,'UInt32')\n self.epics.start()\n self.epics.dump()\n\n\n pyrogue.streamConnect(self.em, self.epicsStream)\n #pyrogue.streamConnect(self.epicsStream, self.es)\n #pyrogue.streamConnect(self.ptx, self.es)\n pyrogue.streamConnect(self.fifo, self.es)\n\nif __name__ == \"__main__\":\n\n dummyTree = DummyTree()\n\n print(\"Running in python main\")\n# try:\n# while True:\n# for i in range(4,16,4):\n# print(\"Sending {}\".format(i))\n# dummyTree.epicsStream.genFrame(i)\n# lst = [i for i in range(i)]\n# print(\"Setting: {}\".format(lst))\n# dummyTree.listVar.set(lst)\n# time.sleep(1)\n# except KeyboardInterrupt:\n# dummyTree.stop()\n\n","sub_path":"epics_interface/scripts/testServer.py","file_name":"testServer.py","file_ext":"py","file_size_in_byte":3678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"134948662","text":"import numpy as np\nfrom gym import utils\nfrom gym.envs.mujoco import mujoco_env\nfrom src.env.util.cost import cheetah_cost_fn\n\n\nclass HalfCheetahEnvNew(mujoco_env.MujocoEnv, utils.EzPickle):\n\n name = 'HalfCheetah'\n\n def __init__(self, cost=cheetah_cost_fn):\n self.cost = cost\n self.step_count = 0\n self.name = 'HalfCheetah'\n self._elapsed_steps = 0\n self._max_episode_steps = 1000\n\n mujoco_env.MujocoEnv.__init__(self, 'half_cheetah.xml', 1)\n utils.EzPickle.__init__(self)\n\n def _step(self, action):\n self._elapsed_steps += 1\n # xposbefore = self.model.data.qpos[0, 0]\n prev_obs = self._get_obs()\n self.do_simulation(action, self.frame_skip)\n # xposafter = self.model.data.qpos[0, 0]\n ob = self._get_obs()\n # reward_ctrl = - 0.1 * np.square(action).sum()\n # reward_run = (xposafter - xposbefore) / self.dt\n # reward = reward_ctrl + reward_run\n # change this part\n reward = self.cost(state=prev_obs, action=action, next_state=ob)\n if self._elapsed_steps >= self._max_episode_steps:\n done = True\n else:\n done = False\n if done is True:\n self.reset()\n\n return ob, reward, done, None\n\n def _get_obs(self):\n return np.concatenate([\n self.model.data.qpos.flat[1:],\n self.model.data.qvel.flat,\n self.get_body_com(\"torso\").flat,\n # self.get_body_comvel(\"torso\").flat,\n ])\n\n def reset_model(self):\n self._elapsed_steps = 0\n qpos = self.init_qpos + self.np_random.uniform(low=-.1, high=.1, size=self.model.nq)\n qvel = self.init_qvel + self.np_random.randn(self.model.nv) * .1\n self.set_state(qpos, qvel)\n return self._get_obs()\n\n def viewer_setup(self):\n self.viewer.cam.distance = self.model.stat.extent * 0.5\n\n def print_log_queue(self):\n pass\n\n def reset(self):\n # print(\"%s reset finished\" % type(self).__name__)\n return self.reset_model()\n\n def init(self):\n print(\"%s init finished\" % type(self).__name__)\n\n\nif __name__ == '__main__':\n a = HalfCheetahEnvNew()\n res, reward, done, info = a.step(action=a.action_space.sample())\n pass\n","sub_path":"src/env/halfCheetahEnv/halfCheetahEnv.py","file_name":"halfCheetahEnv.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"273968113","text":"# snapchat airbnb\n'''\nGiven a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).\n\nExample:\n\nInput: S = \"ADOBECODEBANC\", T = \"ABC\"\nOutput: \"BANC\"\nNote:\n\nIf there is no such window in S that covers all characters in T, return the empty string \"\".\nIf there is such window, you are guaranteed that there will always be only one unique minimum window in S.\n'''\nimport collections\nclass Solution:\n def minWindow(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: str\n \"\"\"\n window = [0] * 128\n targets = collections.Counter(t)\n res = ''\n count = l = 0\n for r in range(len(s)):\n if s[r] in targets:\n if targets[s[r]] > window[ord(s[r])]:\n count += 1\n window[ord(s[r])] += 1\n\n if count == len(t):\n while s[l] not in targets or window[ord(s[l])] > targets[s[l]]:\n if s[l] in targets:window[ord(s[l])] -= 1\n l += 1\n if not res or r-l+1 < len(res):\n res = s[l:r+1]\n return res\n","sub_path":"leetcode/minimumWindowSubstring/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"228576101","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\nProject_name:yzmsb\nFile_name:neimenggu_predict \nCreate on 2016/11/3 下午3:41\n@Author: dfsj\n\"\"\"\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf8')\n\nimport cv2\nimport numpy as np\nimport Levenshtein\nimport logging.config\n\nlogging.config.fileConfig(\"logging.conf\")\nloggerInfo = logging.getLogger(\"infoLogger\")\n\nnp.set_printoptions(threshold='nan', linewidth=10000)\n\n\ndef quzao(im_src):\n img = im_src\n list1 = []\n for i in xrange(img.shape[0]):\n for j in xrange(img.shape[1]): # 去掉背景色(把三个通道值均在180以上的认为是背景)\n if not (img[i, j, 0] > 180 and img[i, j, 1] > 180 and img[i, j, 2] > 180):\n list1.append(img[i, j, ])\n\n b_list = []\n g_list = []\n r_list = []\n for j in xrange(len(list1)):\n b_list.append(list1[j][0])\n g_list.append(list1[j][1])\n r_list.append(list1[j][2])\n b_mean = np.mean(b_list) # 求RGB三通道下各个通道的颜色均值\n g_mean = np.mean(g_list)\n r_mean = np.mean(r_list)\n m = img.shape[0]\n n = img.shape[1]\n pic_array = np.zeros((m, n)) # 初始化二维映射矩阵,用0填充\n for ii in xrange(m): # 三个通道颜色与各自均值的差的绝对值和大于120的认为是背景色或噪音色\n for jj in xrange(n):\n if sum([abs(img[ii, jj, 0] - b_mean), abs(img[ii, jj, 1] - g_mean), abs(img[ii, jj, 2] - r_mean)]) < 50:\n pic_array[ii, jj, ] = 1\n return pic_array.reshape(1, -1)[0]\n\n\ndef yzmsb_preprocess(filename):\n loggerInfo.info('图片名称是:' + filename)\n try:\n im = cv2.imread(filename) # 40, 180\n array_yuzhi = np.zeros((40, 21))\n for i in range(40):\n for j in range(180):\n if im[i, j, 0] > 190 or im[i, j, 1] > 190 or im[i, j, 2] > 190:\n im[i, j, ] = 255, 255, 255\n im_yuzhi = im[:, 130:151, ]\n for i in range(40):\n for j in range(21):\n if im_yuzhi[i, j, 0] < 250 and im_yuzhi[i, j, 1] < 250 or im_yuzhi[i, j, 2] < 250:\n array_yuzhi[i, j] = 1\n if np.sum(array_yuzhi) >= 40:\n im1 = im[:, 26:51, ]\n im2 = im[:, 51:76, ]\n im3 = im[:, 76:101, ]\n a1 = quzao(im1)\n a2 = quzao(im2)\n a3 = quzao(im3)\n result_array = [a1, a2, a3]\n return result_array\n else:\n im1 = im[:, 26:51, ]\n im2 = im[:, 51:76, ]\n im3 = im[:, 76:101, ]\n im4 = im[:, 101:126, ]\n a1 = quzao(im1)\n a2 = quzao(im2)\n a3 = quzao(im3)\n a4 = quzao(im4)\n result_array = [a1, a2, a3, a4]\n return result_array\n except Exception as error:\n loggerInfo.error(filename + str(error))\n\n\ndef pipei(chengyu):\n chengyu_neimemggu = np.loadtxt(\"chengyu_neimenggu.txt\", dtype=str)\n chengyu_neimemggu1 = list(chengyu_neimemggu)\n if '.DS_Store' in chengyu_neimemggu1:\n chengyu_neimemggu1.remove('.DS_Store')\n global flag\n flag = 0\n result = 'error'\n\n for j in xrange(len(chengyu_neimemggu1)):\n if [Levenshtein.hamming(chengyu[i:i + 3], chengyu_neimemggu1[j][i:i + 3]) for i in range(0, 12, 3)].count(0) == 4:\n result = chengyu_neimemggu1[j]\n flag = 1\n break\n if flag == 0:\n for j in xrange(len(chengyu_neimemggu1)):\n if [Levenshtein.hamming(chengyu[i:i + 3], chengyu_neimemggu1[j][i:i + 3]) for i in range(0, 12, 3)].count(\n 0) == 3:\n result = chengyu_neimemggu1[j]\n flag = 1\n break\n if flag == 0:\n for j in xrange(len(chengyu_neimemggu1)):\n if [Levenshtein.hamming(chengyu[i:i + 3], chengyu_neimemggu1[j][i:i + 3]) for i in range(0, 12, 3)].count(\n 0) == 2:\n result = chengyu_neimemggu1[j]\n flag = 1\n break\n if flag == 0:\n for j in xrange(len(chengyu_neimemggu1)):\n if [Levenshtein.hamming(chengyu[i:i + 3], chengyu_neimemggu1[j][i:i + 3]) for i in range(0, 12, 3)].count(\n 0) == 1:\n result = chengyu_neimemggu1[j]\n break\n return result\n\n\ndef yzmsb_model1(item, rfclf):\n\n result = []\n for i in range(len(item)):\n ret = int(rfclf.predict(np.array(item[i]).reshape(1, -1)))\n result.append(ret)\n return result\n\n\ndef yzmsb_model2(item, rfclf):\n result = []\n for i in range(len(item)):\n ret = rfclf.predict(np.array(item[i]).reshape(1, -1))\n result.append(ret[0])\n return result\n\n\ndef yzmsb(filename, rfclf1, rfclf2):\n try:\n a = yzmsb_preprocess(filename)\n if len(a) == 3:\n jieguo = yzmsb_model1(a, rfclf1)\n if jieguo[1] == 10:\n jisuanjieguo = jieguo[0] + jieguo[2]\n loggerInfo.info('图片 %s 的验证结果是: %s + %s = %s' % (filename, jieguo[0], jieguo[2], jisuanjieguo))\n elif jieguo[1] == 11:\n jisuanjieguo = jieguo[0] - jieguo[2]\n loggerInfo.info('图片 %s 的验证结果是: %s - %s = %s' % (filename, jieguo[0], jieguo[2], jisuanjieguo))\n else:\n jisuanjieguo = jieguo[0] * jieguo[2]\n loggerInfo.info('图片 %s 的验证结果是: %s * %s = %s' % (filename, jieguo[0], jieguo[2], jisuanjieguo))\n else:\n jieguo = yzmsb_model2(a, rfclf2)\n jisuanjieguo = ''.join(jieguo)\n jisuanjieguo = pipei(jisuanjieguo)\n loggerInfo.info('图片 %s 的验证结果是: %s ' % (filename, jisuanjieguo))\n\n except Exception as error:\n jisuanjieguo = '0'\n loggerInfo.error('图片 %s 识别错误,原因是: %r ' % (filename, str(error)))\n finally:\n return str(jisuanjieguo)\n\n","sub_path":"yzmsb/neimenggu.py","file_name":"neimenggu.py","file_ext":"py","file_size_in_byte":5919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"585080748","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, tools, api, _\nfrom odoo.exceptions import UserError, ValidationError\nfrom odoo.tools import float_compare\nfrom datetime import timedelta\nfrom odoo.osv import expression\n\nimport logging\nimport datetime\nimport math\n_logger = logging.getLogger(__name__)\n\n\nclass AnalyticLine(models.Model):\n\n _inherit = 'account.analytic.line'\n\n stage_id = fields.Selection([\n # ('forecast', 'Stock'),\n ('draft', '0. Draft'), \n ('lc_review', '1. LC review'), \n ('pc_review', '2. PC review'), \n ('carry_forward', 'Carry Forward'),\n ('adjustment_validation', '4. Adjustment Validation'),\n ('invoiceable', '5. Invoiceable'),\n ('invoiced', '6. Invoiced'),\n ('historical','7. Historical'),\n ('outofscope', 'Out Of Scope'),\n ], default='draft')\n\n lc_comment = fields.Char(string=\"Comment\")\n\n deliverable_id = fields.Many2one(\n 'product.deliverable',\n string='Deliverable',\n related='task_id.sale_line_id.product_id.deliverable_id',\n store=True,\n )\n \n reporting_task_id = fields.Many2one(\n comodel_name = 'project.task',\n compute = '_compute_reporting_task',\n store=True,\n )\n\n reporting_task_id = fields.Many2one(\n comodel_name = 'project.task',\n compute = '_compute_reporting_task',\n store = True,\n )\n\n # Used in order to group by client\n partner_id = fields.Many2one(\n 'res.partner',\n string='Client',\n related='project_id.partner_id',\n store=True,\n )\n\n adjustment_reason_id = fields.Many2one('timesheet.adjustment.reason', string=\"Adjustment Reason\")\n\n time_category_id = fields.Many2one(\n comodel_name='project.time_category',\n string=\"Time Category\",\n )\n\n # Rename description label\n name = fields.Char('External Comment', required=True)\n\n internal_comment = fields.Char(string='')\n\n at_risk = fields.Boolean(string='Timesheet at risk', readonly=True)\n\n # OVERWRITE IN ORDER TO UPDATE LABEL\n unit_amount_rounded = fields.Float(\n string=\"Revised Time\",\n default=0.0,\n copy=False,\n )\n \n required_lc_comment = fields.Boolean(compute='get_required_lc_comment')\n\n rate_id = fields.Many2one(\n comodel_name='product.template',\n default = False,\n readonly = True,\n )\n\n so_line_unit_price = fields.Monetary(\n 'Sales Oder Line Unit Price',\n readonly=True,\n store=True,\n default=0.0,\n )\n\n so_line_currency_id = fields.Many2one(\n 'res.currency',\n related='so_line.currency_id',\n store=True,\n string='Sales Order Currency',\n )\n adj_reason_required = fields.Boolean()\n main_project_id = fields.Many2one(\n 'project.project', string='Main Project',\n domain=[('parent_id', '=', False)],\n )\n\n billability = fields.Selection([\n ('na', 'N/A'),\n ('billable', 'BILLABLE'),\n ('non_billable', 'NON BILLABLE'),],\n compute = '_compute_billability',\n store = True,\n default = 'na',\n )\n \n @api.depends('task_id','task_id.parent_id')\n def _compute_reporting_task(self):\n for ts in self:\n ts.reporting_task_id = ts.task_id.parent_id if ts.task_id.parent_id else ts.task_id\n\n @api.depends('task_id','task_id.parent_id')\n def _compute_reporting_task(self):\n for ts in self:\n ts.reporting_task_id = ts.task_id.parent_id if ts.task_id.parent_id else ts.task_id\n\n @api.depends('project_id')\n def _compute_billability(self):\n timesheets = self.filtered(lambda t: t.is_timesheet and t.project_id)\n for ts in timesheets:\n if ts.project_id.project_type == 'client':\n ts.billability = 'billable'\n else:\n ts.billability = 'non_billable'\n\n\n @api.model\n def show_grid_cell(self, domain=[], column_value='', row_values={}):\n line = self.sudo().search(domain, limit=1)\n date = column_value\n if not line:\n # fetch the latest line\n task_value = row_values.get('task_id')\n task_id = task_value and task_value[0] or False\n if task_id:\n direct_previous_line = self.sudo().search([\n ('date', '<', date),\n ('task_id', '=', task_id),\n ], limit=1, order='date desc')\n if direct_previous_line:\n task_id = direct_previous_line.task_id\n main_project_id = task_id.project_id\n main_project_id = main_project_id or main_project_id.parent_id\n values = {\n 'unit_amount': 0,\n 'date': date,\n 'project_id': direct_previous_line.project_id.id,\n 'task_id': task_id.id,\n 'main_project_id': main_project_id.id,\n 'name': direct_previous_line.name,\n 'time_category_id': direct_previous_line.time_category_id.id,\n }\n line = self.create(values)\n\n form_view_id = self.env.ref('timesheet_grid.timesheet_view_form').id\n return {\n 'name': _('Timesheet'),\n 'type': 'ir.actions.act_window',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': self._name,\n 'res_id': line.id,\n 'view_id': form_view_id,\n 'views': [(form_view_id, 'form')],\n 'target': 'new',\n 'context': {},\n }\n\n @api.multi\n def adjust_grid(self, row_domain, column_field, column_value, cell_field, change):\n \"\"\"\n We override this to avoit the default naming 'Timesheet Adjustment' when using the grid view\n \"\"\"\n if column_field != 'date' or cell_field != 'unit_amount':\n raise ValueError(\n \"{} can only adjust unit_amount (got {}) by date (got {})\".format(\n self._name,\n cell_field,\n column_field,\n ))\n\n additionnal_domain = self._get_adjust_grid_domain(column_value)\n domain = expression.AND([row_domain, additionnal_domain])\n line = self.search(domain)\n\n day = column_value.split('/')[0]\n if len(line) > 1: # copy the last line as adjustment\n line[0].copy({\n #'name': _('Timesheet Adjustment'),\n column_field: day,\n cell_field: change\n })\n elif len(line) == 1: # update existing line\n line.write({\n cell_field: line[cell_field] + change\n })\n else: # create new one\n self.search(row_domain, limit=1).copy({\n #'name': _('Timesheet Adjustment'),\n column_field: day,\n cell_field: change\n })\n return False\n\n @api.model\n def _get_at_risk_values(self, project_id, employee_id):\n project = self.env['project.project'].browse(project_id)\n if project.sale_order_id.state not in ['sale', 'done']:\n return True\n employee_id = self.env['hr.employee'].browse(employee_id)\n\n core_team = project.core_team_id\n if employee_id and core_team:\n project_employee = core_team.consultant_ids | \\\n core_team.ta_ids | \\\n core_team.lead_backup | \\\n core_team.lead_consultant\n if employee_id[0] not in project_employee:\n return True\n return False\n\n @api.model\n def create(self, vals):\n if not self._context.get('migration_mode',False):\n if vals.get('employee_id', False) and vals.get('project_id', False):\n # rounding to 15 mins\n if vals['unit_amount'] % 0.25 != 0:\n old = vals.get('unit_amount', 0)\n vals['unit_amount'] = math.ceil(old * 4) / 4\n\n # check if this is a timesheet at risk\n vals['at_risk'] = self.sudo()._get_at_risk_values(vals.get('project_id'),\n vals.get('employee_id'))\n\n if vals.get('time_category_id') == self.env.ref('vcls-timesheet.travel_time_category').id:\n task = self.env['project.task'].browse(vals['task_id'])\n if task.sale_line_id:\n unit_amount_rounded = vals['unit_amount'] * task.sale_line_id.order_id.travel_invoicing_ratio\n vals.update({'unit_amount_rounded': unit_amount_rounded})\n #else:\n #_logger.info(\"TS FAST create\")\n \n if not vals.get('main_project_id') and vals.get('project_id'):\n project_id = self.env['project.project'].browse(vals['project_id'])\n main_project_id = project_id.parent_id or project_id\n vals['main_project_id'] = main_project_id.id\n\n return super(AnalyticLine, self).create(vals)\n\n @api.multi\n def write(self, vals):\n # we automatically update the stage if the ts is validated and stage = draft\n so_update = False\n orders = self.env['sale.order']\n #_logger.info(\"ANALYTIC WRITE {}\".format(vals))\n\n # we loop the lines to manage specific usecases\n for line in self:\n\n # Timesheet cases\n if line.is_timesheet and line.project_id and line.employee_id:\n\n\n if vals.get('unit_amount', False):\n #the coded amount is changed\n if vals['unit_amount'] % 0.25 != 0:\n old = vals.get('unit_amount', 0)\n vals['unit_amount'] = math.ceil(old * 4) / 4\n \n #we preserve a potential modification of the rounded_value in the past\n delta = vals['unit_amount'] - line.unit_amount\n vals['unit_amount_rounded'] = vals.get('unit_amount_rounded', line.unit_amount_rounded)+delta\n\n # automatically set the stage to lc_review according to the conditions\n if vals.get('validated', line.validated):\n if vals.get('stage_id', line.stage_id) == 'draft':\n vals['stage_id'] = 'lc_review'\n\n # review of the lc needs sudo() to write on validated ts\n if line.stage_id == 'lc_review':\n project = self.env['project.project'].browse(\n vals.get('project_id', line.project_id.id))\n if project.user_id.id == self._uid: # if the user is the lead consultant, we autorize the modification\n self = self.sudo()\n\n # if one of the 3 important value has changed, and the stage changes the delivered amount\n if (vals.get('date', False) or vals.get('unit_amount_rounded',False) or vals.get('stage_id', False)) and (vals.get('stage_id', line.stage_id) in ['invoiced','invoiceable','historical']):\n _logger.info(\"Order timesheet update for {}\".format(line.name))\n so_update = True\n orders |= line.so_line.order_id\n\n # if the sale order line price as not been captured yet\n if vals.get('so_line',line.so_line.id) and line.so_line_unit_price == 0.0:\n task = self.env['project.task'].browse(\n vals.get('task_id', line.task_id.id))\n so_line = self.env['sale.order.line'].browse(\n vals.get('so_line', line.so_line.id))\n\n if task.sale_line_id != so_line: # if we map to a rate based product\n vals['so_line_unit_price'] = so_line.price_unit\n vals['rate_id'] = so_line.product_id.product_tmpl_id.id\n so_update = True\n orders |= line.so_line.order_id\n\n if (vals.get('time_category_id') == self.env.ref('vcls-timesheet.travel_time_category').id or\n (vals.get('unit_amount') and line.time_category_id.id == self.env.ref('vcls-timesheet.travel_time_category').id)) and\\\n line.task_id.sale_line_id:\n unit_amount = vals.get('unit_amount') or line.unit_amount\n vals.update({\n 'unit_amount_rounded': unit_amount * line.task_id.sale_line_id.order_id.travel_invoicing_ratio\n })\n if vals.get('timesheet_invoice_id'):\n vals['stage_id'] = 'invoiced'\n ok = super(AnalyticLine, self).write(vals)\n\n if ok and so_update:\n orders._compute_timesheet_ids()\n # force recompute\n #_logger.info(\"SO UPDATE {} CONTEXT MIG {}\".format(orders.mapped('name'),self._context.get('migration_mode',False)))\n for order in orders:\n order.timesheet_limit_date = order.timesheet_limit_date\n\n return ok\n\n @api.multi\n def finalize_lc_review(self):\n self._finalize_lc_review()\n\n @api.multi\n def _finalize_lc_review(self):\n context = self.env.context\n timesheet_ids = context.get('active_ids',[])\n timesheets = self.env['account.analytic.line'].browse(timesheet_ids)\n if len(timesheets) == 0:\n raise ValidationError(_(\"Please select at least one record!\"))\n\n timesheets_in = timesheets.filtered(lambda r: r.stage_id=='lc_review' and (r.project_id.user_id.id == r.env.user.id or r.env.user.has_group('vcls-hr.vcls_group_superuser_lvl2')))\n timesheets_out = (timesheets - timesheets_in) if timesheets_in else timesheets\n #_logger.info(\"names {} stage {} user {} out {}\".format(timesheets.mapped('name'),timesheets.mapped('stage_id'),timesheets_out.mapped('name')))\n for timesheet in timesheets_in:\n timesheet.sudo().write({'stage_id':'pc_review'})\n if len(timesheets_out) > 0:\n message = \"You don't have the permission for the following timesheet(s) :\\n\"\n for timesheet in timesheets_out:\n message += \" - \" + timesheet.name + \"\\n\"\n raise ValidationError(_(message))\n\n @api.multi\n def finalize_pc_review(self):\n self._pc_change_state('invoiceable')\n\n @api.multi\n def _pc_change_state(self,new_stage='invoiceable'):\n \"\"\"\n THis method covers all the use cases of the project controller, modifying timesheet stages.\n Server actions and buttons are calling this method.\n \"\"\"\n context = self.env.context\n timesheet_ids = context.get('active_ids',[])\n timesheets = self.env['account.analytic.line'].browse(timesheet_ids)\n if len(timesheets) == 0:\n raise ValidationError(_(\"Please select at least one record!\"))\n\n user_authorized = (self.env.user.has_group('vcls-hr.vcls_group_superuser_lvl2') or self.env.user.has_group('vcls_security.group_project_controller'))\n if not user_authorized:\n raise ValidationError(_(\"You need to be part of the 'Project Controller' group to perform this operation. Thank you.\"))\n\n #_logger.info(\"NEW TS STAGE:{}\".format(new_stage))\n\n if new_stage=='invoiceable':\n timesheets_in = timesheets.filtered(lambda r: (r.stage_id=='pc_review' or r.stage_id=='carry_forward'))\n\n #adj_validation_timesheets = timesheets_in.filtered(lambda r: r.required_lc_comment == True)\n #invoiceable_timesheets = (timesheets_in - adj_validation_timesheets) if adj_validation_timesheets else timesheets_in\n\n #adj_validation_timesheets.write({'stage_id': 'adjustment_validation'})\n #invoiceable_timesheets.write({'stage_id': 'invoiceable'})\n timesheets_in.write({'stage_id': 'invoiceable'})\n\n elif new_stage=='outofscope':\n timesheets_in = timesheets.filtered(lambda r: (r.stage_id=='pc_review' or r.stage_id=='carry_forward'))\n _logger.info(\"NEW TS STAGE outofscope:{}\".format(timesheets_in.mapped('name')))\n timesheets_in.write({'stage_id': 'outofscope'})\n\n elif new_stage=='carry_forward':\n timesheets_in = timesheets.filtered(lambda r: (r.stage_id=='pc_review'))\n _logger.info(\"NEW TS STAGE carry_forward:{}\".format(timesheets_in.mapped('name')))\n timesheets_in.write({'stage_id': 'carry_forward'})\n\n else:\n timesheets_in = False\n\n timesheets_out = (timesheets - timesheets_in) if timesheets_in else timesheets\n if len(timesheets_out) > 0:\n message = \"Following timesheet(s) are not in the proper stage to perform the required action:\\n\"\n for timesheet in timesheets_out:\n message += \" - \" + timesheet.name + \"\\n\"\n raise ValidationError(_(message))\n\n @api.multi\n def _finalize_pc_review(self):\n self._pc_change_state('invoiceable')\n\n @api.multi\n def set_outofscope(self):\n self._pc_change_state('outofscope')\n\n @api.multi\n def set_carry_forward(self):\n self._pc_change_state('carry_forward')\n\n @api.depends('user_id')\n def _compute_employee_id(self):\n for record in self:\n if record.user_id:\n resource = self.env['resource.resource'].search([('user_id','=',record.user_id.id)])\n employee = self.env['hr.employee'].search([('resource_id','=',resource.id)])\n record.employee_id = employee\n\n @api.onchange('unit_amount_rounded', 'unit_amount')\n def get_required_lc_comment(self):\n for rec in self:\n #we round to quarter to avoir the minute entry\n if rec.unit_amount % 0.25 != 0:\n rec.unit_amount = math.ceil(rec.unit_amount * 4) / 4\n else:\n pass\n if rec.unit_amount_rounded % 0.25 != 0:\n rec.unit_amount_rounded = math.ceil(rec.unit_amount_rounded * 4) / 4\n else:\n pass\n \n #if the values aren't the same, then we force the lc_comment.\n if float_compare(rec.unit_amount_rounded, rec.unit_amount, precision_digits=2) == 0:\n rec.required_lc_comment = False\n else:\n rec.required_lc_comment = True\n\n @api.onchange('unit_amount_rounded')\n def onchange_adj_reason_readonly(self):\n adj_reason_required = False\n if self.unit_amount != self.unit_amount_rounded:\n adj_reason_required = True\n self.adj_reason_required = adj_reason_required\n\n @api.onchange('main_project_id')\n def onchange_task_id_project_related(self):\n #we clear the existing task_id and project_id if not logged from task\n if not self._context.get('log_from_task',False):\n self.task_id = False\n self.project_id = False\n #we return the proper domain\n if self.main_project_id:\n projects = self.main_project_id | self.main_project_id.child_id\n return {'domain': {\n 'task_id': [('project_id', 'in', projects.ids), ('stage_id.allow_timesheet', '=', True)]\n }}\n\n @api.onchange('task_id')\n def onchange_task_id(self):\n if self._context.get('desc_order_display'):\n self.project_id = self.task_id.project_id\n if not self.main_project_id and self.task_id:\n main_project_id = self.task_id.project_id\n self.main_project_id = main_project_id.parent_id or main_project_id\n\n @api.multi\n def button_details_lc(self):\n view = {\n 'name': _('Details'),\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'account.analytic.line',\n 'view_id': self.env.ref('vcls-timesheet.vcls_timesheet_lc_view_form').id,\n 'type': 'ir.actions.act_window',\n 'target': 'new',\n 'context': {\n 'form_view_initial_mode': 'edit',\n 'force_detailed_view': True,\n 'set_fields_readonly': self.stage_id != 'lc_review'\n },\n 'res_id': self.id,\n }\n return view\n \n @api.multi\n def button_details_pc(self):\n view = {\n 'name': _('Details'),\n 'view_type': 'form',\n 'view_mode': 'form',\n 'res_model': 'account.analytic.line',\n 'view_id': self.env.ref('vcls-timesheet.vcls_timesheet_pc_view_form').id,\n 'type': 'ir.actions.act_window',\n 'target': 'new',\n 'context': {\n 'form_view_initial_mode': 'edit',\n 'force_detailed_view': True,\n },\n 'res_id': self.id,\n }\n return view\n\n def lc_review_approve_timesheets(self):\n self.search([('stage_id', '=', 'lc_review')]).write({'stage_id': 'pc_review'})\n\n def pc_review_approve_timesheets(self):\n self.search([('stage_id', '=', 'pc_review'), ('lc_comment', '=', False)]).\\\n write({'stage_id': 'invoiceable'})\n\n @api.model\n def _smart_timesheeting_cron(self,hourly_offset=0):\n days = hourly_offset//24\n remainder = hourly_offset%24\n now = fields.Datetime.now()\n\n timesheets = self.search([\n ('project_id', '!=', False),\n ('unit_amount', '>', 0),\n ('date', '>', now - timedelta(days=days+7,hours=remainder)),\n ('date', '<', now - timedelta(days=days,hours=remainder)),\n ])\n\n for task in timesheets.mapped('task_id'):\n if task.project_id.parent_id:\n parent_project_id = task.project_id.parent_id\n else:\n parent_project_id = task.project_id\n\n task_ts = timesheets.filtered(lambda t: t.task_id.id == task.id and t.task_id.stage_allow_ts)\n for employee in task_ts.mapped('employee_id'):\n #_logger.info(\"SMART TIMESHEETING: {} on {}\".format(task.name,employee.name))\n #we finally create the ts\n self.create({\n 'date': now + timedelta(days=1),\n 'task_id': task.id,\n 'unit_amount': 0.0,\n 'company_id': task.company_id.id,\n 'project_id': task.project_id.id,\n 'main_project_id': parent_project_id.id,\n 'employee_id': employee.id,\n 'name': \"Smart Timesheeting\",\n })\n\n\n \"\"\"# We look for timesheets of the previous week\n tasks = self.env['project.task'].search([\n ('project_id', '!=', False),\n ('effective_hours', '>', 0),\n ('timesheet_ids.date', '>', fields.Datetime.now() - timedelta(days=7)),\n ('timesheet_ids.date', '<', fields.Datetime.now()),\n ])\n for task in tasks:\n self.create({\n 'date': fields.Date.today(),\n 'task_id': task.id,\n 'amount': 0,\n 'company_id': task.company_id,\n 'project_id': task.project_id.id,\n })\"\"\"\n\n def _timesheet_preprocess(self, vals):\n vals = super(AnalyticLine, self)._timesheet_preprocess(vals)\n if vals.get('project_id'):\n project = self.env['project.project'].browse(vals['project_id'])\n vals['main_project_id'] = project.id or project.parent_id.id\n return vals\n\n @api.multi\n def unlink(self):\n for time_sheet in self:\n if time_sheet.timesheet_invoice_id:\n raise ValidationError(_('You cannot delete a timesheet linked to an invoice'))\n return super(AnalyticLine, self).unlink()\n\n @api.multi\n def _check_can_write(self, values):\n super(AnalyticLine, self)._check_can_write(values)\n if self.filtered(lambda t: t.timesheet_invoice_id):\n if any([field_name in values for field_name in ['unit_amount_rounded']]):\n raise UserError(\n _('You can not modify already invoiced '\n 'timesheets (linked to a Sales order '\n 'items invoiced on Time and material).')\n )\n\n @api.model\n def _force_rate_id(self):\n timesheets = self.search([('is_timesheet','=',True),('employee_id','!=',False),('project_id','!=',False)])\n\n for project in timesheets.mapped('project_id'):\n _logger.info(\"Processing Rate_id for project {}\".format(project.name))\n for map_line in project.sale_line_employee_ids:\n rate_id = map_line.sale_line_id.product_id.product_tmpl_id\n ts = timesheets.filtered(lambda t: t.so_line == map_line.sale_line_id)\n if ts:\n _logger.info(\"Processing Rate_id for map line for {} as {} with {} timesheets\".format(map_line.employee_id.name,rate_id.name,len(ts)))\n ts.write({'rate_id':rate_id.id})\n","sub_path":"vcls-timesheet/models/analytic_account.py","file_name":"analytic_account.py","file_ext":"py","file_size_in_byte":25072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"79149373","text":"\"\"\"\nTactics and checks for Sudoku.\n\nAuthors: Haomin He\nConsulted with: Office Hour, Rickie Kerndt, Daniel Bach. \n\nA tactic is a rule that can be used to determine and/or constrain the\npossible choices for a Sudoku tile.\n\nA check determines whether a given Sudoku board\n(whether complete or incomplete) is legal. A board is\nlegal if it contains only digits and open spaces, and\nif all of the digits are unique in each row, column,\nand 3x3 block.\n\"\"\"\nimport sdkboard\n\n# The following variables are private but global to the module\nglobal groups\nglobal progress\n\ndef prepare(board):\n \"\"\" \n Prepare for checking and solving a sudoku board.\n Args:\n board: An sdkboard.Board object\n Returns:\n nothing\n Effects:\n prepared for check(board) and solve(board)\n \"\"\"\n global groups # rows, columns, and blocks\n\n groups = [ ]\n\n # Rows (we can reuse them from the board)\n for row in range(9):\n groups.append(board.tiles[row])\n \n for column in range(9): #9 groups for the 9 columns,column loop should not be nested inside row loop\n new_empty_list = []\n for row in range(9):\n new_empty_list.append(board.tiles[row][column])\n groups.append(new_empty_list)\n \n for start_row in [0, 3, 6]:\n for start_col in [0, 3, 6]:\n sq_tiles = [ ] \n for row in range(3):\n for col in range(3): \n t = board.tiles[start_row + row][start_col+col]\n sq_tiles.append(t)\n groups.append(sq_tiles)\n\n # We need to know when we are making progress \n for row in board.tiles:\n for tile in row:\n tile.register(progress_listener)\n\n\n \ndef progress_listener(tile, event):\n \"\"\"\n An event listener, used to determine whether we have made\n some progress in solving a Sudoku puzzle. This listener\n will be attached to Sudoku Tile objects, and informed when\n \"determined\" and \"constrained\" events occur.\n Args:\n tile: The tile on which an event occurred\n event: What happened. The events we listen for are \"determined\"\n and \"constrained\"\n Returns: nothing\n Effects: module-global variable progress may be set to True\n \"\"\"\n global progress \n if event == \"determined\" or event == \"constrained\":\n progress = True\n # print(\"Notified of progress!\")\n\ndef good_board(): \n \"\"\"Check that every group (row, column, and block)\n contains unique elements (no duplicate digits).\n Args:\n none (implicit through prepare_board)\n Returns:\n Boolean True iff all groups contain unique elements\n Effects:\n Will announce \"duplicate\" event on tiles that are\n not unique in a group.\n Requires:\n prepare(board) must be called before good_board\n \"\"\"\n Flag = True # whether the board is \"ok so far\" here\n for everyelement in groups:\n dups = set() # reset every time\n available = set(sdkboard.SYMBOLS) # SYMBOLS = frozenset('.123456789')\n for tile in everyelement:\n if (tile.symbol in available):\n if tile.symbol != sdkboard.OPEN:\n available.remove(tile.symbol)\n else: # (tile.symbol not in available)\n dups.add(tile.symbol)\n Flag = False\n for tile in everyelement:\n for dup in dups:\n if tile.symbol == dup:\n tile.announce(\"duplicate\") \n return Flag\ndef solve():\n \"\"\"\n Keep applying naked_single and hidden_single tactics to every\n group (row, column, and block) as long as there is progress.\n Args: \n none\n Requires:\n prepare(board) must be called once before solve()\n use only if good_board() returns True\n Effects: \n May modify tiles in the board passed to prepare(board), \n setting symbols in open tiles, and reducing the possible\n sets in some tiles. \n \"\"\"\n global progress\n progress = True\n while(progress):\n # print(\"***Starting solution round***\")\n progress = False\n # Note that naked_single and hidden_single may indirectly\n # set the progress flag by causing the progress listener to be\n # triggered. \n for group in groups:\n naked_single(group)\n hidden_single(group)\n\ndef naked_single(group):\n \"\"\"Constrain each tile to not contain any of the digits \n that have already been used in the group.\n Args: \n group: a list of 9 tiles in a row, column, or block\n Returns:\n nothing\n Effects:\n For each tile in the group, eliminates \"possible\" elements\n that match a digit used by another tile in the group. If \n this reduces it to one possibility, the selection will be \n made (Tile.remove_choices does this), and progress may be \n signaled.\n \"\"\"\n chosen_num = set()\n for tile in group:\n if (tile.symbol != sdkboard.OPEN):\n chosen_num.add(tile.symbol)\n for tile in group: \n if tile.symbol == sdkboard.OPEN:\n tile.remove_choices(chosen_num) # remove used symbols from \"possible\"\n return\n \n \ndef hidden_single(group):\n \"\"\"Each digit has to go somewhere. For each digit, \n see if there is only one place that digit should \n go. If there is, put it there. \n Args: \n group: a list of 9 tiles in a row, column, or block\n Returns: \n nothing\n Effects: \n For each tile, if it is the only tile that can accept a \n particular digit (according to its \"possible\" set), \n \n \"\"\" \n used = set(sdkboard.DIGITS)\n for tile in group:\n if tile.symbol in used:\n used.remove(tile.symbol) # left available digits\n for symbol in used:\n last_tile = None\n counter = 0\n for tile in group: # count how many tiles can take it\n if tile.symbol == sdkboard.OPEN:\n if symbol in tile.possible:\n counter += 1\n last_tile = tile # remembering the last tile that can take it\n if counter == 1:\n last_tile.determine(symbol)\n return\n'''\nsolve(board):\n \"\"\"Returns True if the board is solvable, \n False if the board is not solvable. \n If it returns True, it also leaves the \n completed board in global variable Solution.\n \"\"\"\n if board is already complete and consistent: \n save board to Solution\n return True\n elif board is inconsistent (that is, good_board() returns False):\n return False\n else:\n # The guess-and-check step\n pick some tile that is OPEN\n prior = current state of board\n for digit in DIGITS:\n tile.symbol = digit\n if solve(board):\n return True\n board = prior\n return False'''\n \n","sub_path":"CIS210 Computer Science I/Projects/p8/sdktactics.py","file_name":"sdktactics.py","file_ext":"py","file_size_in_byte":7212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"143335400","text":"import re\nfrom collections import Counter\n\nWORDS_COUNT = 10\n\n\ndef load_data(filepath):\n with open(filepath, 'r') as raw_content:\n data = raw_content.read()\n return data\n\n\ndef get_most_frequent_words(text):\n wordlist = re.findall(r'\\w+', text.lower())\n return Counter(wordlist).most_common(WORDS_COUNT)\n\n\nif __name__ == '__main__':\n data = load_data('test.txt')\n print(get_most_frequent_words(data))\n","sub_path":"lang_frequency.py","file_name":"lang_frequency.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"312981682","text":"import numpy as np\nimport pytest\n\nfrom pyqumo.distributions import Discrete\n\n\n#\n# Validate distribution creation\n#\ndef test_creation_with_empty_values_raises_error():\n with pytest.raises(ValueError) as excinfo:\n Discrete([])\n assert 'expected non-empty values' in str(excinfo.value).lower()\n\n\n@pytest.mark.parametrize('values,weights', [\n ([10], [0.5, 0.5]),\n ([10, 20], [1.0]),\n])\ndef test_values_and_weights_sizes_must_match(values, weights):\n with pytest.raises(ValueError) as excinfo:\n Discrete(values, weights=weights)\n assert 'values and weights size mismatch' in str(excinfo.value).lower()\n\n\ndef test_weights_must_be_non_negative():\n with pytest.raises(ValueError) as excinfo:\n Discrete([10, 20], [0.5, -0.1])\n assert 'weights must be non-negative' in str(excinfo.value).lower()\n\n\ndef test_weights_sum_must_be_positive():\n with pytest.raises(ValueError) as excinfo:\n Discrete([10, 20], [0, 0])\n assert 'weights sum must be positive' in str(excinfo.value).lower()\n\n\n@pytest.mark.parametrize('values', [[10], [10, 20], [10, 20, 30]])\ndef test_values_get_equal_probability_if_weights_not_given(values):\n disc = Discrete(values)\n expected_p = np.asarray([1. / len(values)] * len(values))\n np.testing.assert_almost_equal(disc.values, values)\n np.testing.assert_almost_equal(disc.prob, expected_p)\n\n\ndef test_creating_discrete_distribution_with_non_normalized_weights():\n values = [10, 20, 30]\n weights = [5, 0, 15]\n disc = Discrete(values, weights)\n np.testing.assert_almost_equal(disc.getp(10), 0.25)\n np.testing.assert_almost_equal(disc.getp(20), 0)\n np.testing.assert_almost_equal(disc.getp(30), 0.75)\n\n\n@pytest.mark.parametrize('values, probs', [\n ({42: 99}, (1.0,)),\n ({42: 13, 34: 13}, (0.5, 0.5)),\n ({10: 0.2, 20: 0.3, 30: 0.5}, (0.2, 0.3, 0.5)),\n])\ndef test_creating_discrete_distribution_with_dictionary(values, probs):\n disc = Discrete(values)\n assert set(disc.values) == set(values.keys())\n np.testing.assert_almost_equal(disc.prob, probs)\n\n\n#\n# Getting probabilities\n#\ndef test_getp_returns_zero_for_any_nonexisting_value():\n disc = Discrete([10, 20])\n assert disc.getp(13) == 0\n assert disc.getp(0) == 0\n\n\n#\n# Counting mean, moment, stddev and variance\n#\n@pytest.mark.parametrize('values, weights, expected', [\n ([10, 20], None, 15),\n ([10, 20], [1, 4], 18),\n ([10, 20, 30], [0.2, 0.3, 0.5], 23),\n])\ndef test_mean_estimation(values, weights, expected):\n disc = Discrete(values, weights)\n assert disc.mean() == expected\n\n\n@pytest.mark.parametrize('values, weights, m1, m2, m3', [\n ([10, 20], None, 15, 250, 4500),\n ([10, 20], [1, 4], 18, 340, 6600),\n ([10, 20, 30], [0.2, 0.3, 0.5], 23, 590, 16100),\n])\ndef test_moment_estimation(values, weights, m1, m2, m3):\n disc = Discrete(values, weights)\n assert disc.moment(1) == m1\n assert disc.moment(2) == m2\n assert disc.moment(3) == m3\n\n\n@pytest.mark.parametrize('k', [-1, 0, 1.1])\ndef test_negative_or_float_moment_parameter_raises_error(k):\n disc = Discrete([10, 20, 30])\n with pytest.raises(ValueError) as excinfo:\n disc.moment(k)\n assert 'positive integer expected' in str(excinfo.value).lower()\n\n\n@pytest.mark.parametrize('values, weights, var', [\n ([10, 20], None, 25.0),\n ([10, 20], [1, 4], 16.0),\n ([10, 20, 30], [0.2, 0.3, 0.5], 61.0),\n])\ndef test_stddev_and_var(values, weights, var):\n disc = Discrete(values, weights)\n np.testing.assert_almost_equal(disc.var(), var)\n np.testing.assert_almost_equal(disc.std(), var ** 0.5)\n\n\n#\n# Test values generation\n#\n@pytest.mark.parametrize('value, n', [(1, 5), (10, 23)])\ndef test_calling_discrete_distribution_with_single_values_returns_it(value, n):\n disc = Discrete([value])\n samples = [disc() for _ in range(n)]\n assert samples == [value] * n\n\n\n@pytest.mark.parametrize('values, weights, n', [\n ([10, 20], None, 1000),\n ([10, 20], [1, 4], 1000),\n ([10, 20, 30], [0.2, 0.3, 0.5], 1000),\n])\ndef test_calling_generates_with_given_pmf(values, weights, n):\n disc = Discrete(values, weights)\n samples = np.asarray([disc() for _ in range(n)])\n est_prob = [sum(samples == i) / len(samples) for i in values]\n\n np.testing.assert_almost_equal(est_prob, disc.prob, 1)\n assert set(samples) == set(values)\n\n\n@pytest.mark.parametrize('values, weights, size', [\n ([10, 20], None, 1000),\n ([10, 20], [1, 4], 1000),\n ([10, 20, 30], [0.2, 0.3, 0.5], 1000),\n])\ndef test_generate_produces_np_array_of_given_size(values, weights, size):\n disc = Discrete(values, weights)\n samples = disc.generate(size)\n est_prob = [sum(samples == i) / len(samples) for i in values]\n\n np.testing.assert_almost_equal(est_prob, disc.prob, 1)\n assert set(samples) == set(values)\n","sub_path":"tests/unit_tests/test_discrete_distribution.py","file_name":"test_discrete_distribution.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"565250538","text":"from tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications import Xception\nfrom tensorflow.keras.applications.xception import preprocess_input\nimport numpy as np\nfrom PIL import Image\nimport tensorflow as tf\nfrom tensorflow.python.keras.backend import set_session\n\n\nconfig = tf.compat.v1.ConfigProto()\nconfig.gpu_options.allow_growth=True\nsess = tf.compat.v1.Session(config=config)\ngraph = tf.compat.v1.get_default_graph()\nset_session(sess)\n\n# See https://keras.io/api/applications/ for details\n\n\nclass FeatureExtractor:\n def __init__(self):\n with graph.as_default():\n self.model = Xception(\n weights=\"imagenet\",\n classes=1000,\n classifier_activation=\"softmax\",\n )\n\n def extract(self, img):\n \"\"\"\n Extract a deep feature from an input image\n Args:\n img: from PIL.Image.open(path) or tensorflow.keras.preprocessing.image.load_img(path)\n Returns:\n feature (np.ndarray): deep feature with the shape=(4096, )\n \"\"\"\n img = Image.open(img)\n img = img.resize((299, 299)) # Xception must take a 299x299 img as an input\n img = img.convert('RGB') # Make sure img is color\n x = image.img_to_array(img) # To np.array. Height x Width x Channel. dtype=float32\n x = np.expand_dims(x, axis=0) # (H, W, C)->(1, H, W, C), where the first elem is the number of img\n x = preprocess_input(x) # Subtracting avg values for each pixel\n with graph.as_default():\n set_session(sess)\n feature = self.model.predict(x)[0] # (1, 4096) -> (4096, )\n return feature / np.linalg.norm(feature) # Normalize\n","sub_path":"feature_extractor.py","file_name":"feature_extractor.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"56935189","text":"#!/usr/bin/env python\n######################################################################################################################\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #\n# #\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance #\n# with the License. A copy of the License is located at #\n# #\n# http://www.apache.org/licenses/LICENSE-2.0 #\n# #\n# or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES #\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions #\n# and limitations under the License. #\n######################################################################################################################\n\nimport pytest\nfrom botocore.stub import Stubber\nfrom shared_util.service_helper import get_service_client\n\nevent_bus_stubber = None\n\n\n@pytest.fixture()\ndef get_event_bus_stubber():\n global event_bus_stubber\n\n if not event_bus_stubber:\n event_bus_client = get_service_client(\"events\")\n event_bus_stubber = Stubber(event_bus_client)\n return event_bus_stubber\n","sub_path":"source/lambda/ingestion-youtube/test/fixtures/event_bus_fixture.py","file_name":"event_bus_fixture.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"282085423","text":"import requests\nimport json\nimport re\nimport string\nimport random\nimport time\nuserName = '1937131977@qq.com'\npassWord = 'h389513'\nheaders0 = {\n\n\"Accept\": \"application/json, text/plain, */*\",\n\"Accept-Encoding\": \"gzip, deflate, br\",\n\"Accept-Language\": \"zh-CN,zh;q=0.9\",\n\"Authorization\": \"bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3d3dy5pdGp1emkuY29tL2FwaS9hdXRob3JpemF0aW9ucyIsImlhdCI6MTU0NDA2MTE0MywiZXhwIjoxNTQ0MTQ3NTQzLCJuYmYiOjE1NDQwNjExNDMsImp0aSI6IlJZVDZnemdvR2Z2akI1RTAiLCJzdWIiOjY3NTc4NywicHJ2IjoiMjNiZDVjODk0OWY2MDBhZGIzOWU3MDFjNDAwODcyZGI3YTU5NzZmNyJ9.7gcJ5ihEYqmth0bcd6UpuwiAW5dlnNfPanYaP1FQxgQ\",\n\"Connection\": \"keep-alive\",\n\"Content-Type\": \"application/json;charset=UTF-8\",\n\"Cookie\": \"acw_tc=76b20f4515440837484458596eaf97ecc7efd719a2e8b8fd47ea7eb486a137; acw_sc__v3=5c08d92a9f83e180062248a442c714b3d61de7d6; gr_user_id=8cff0e21-7ada-4206-8d78-d6d528b10e5b; _ga=GA1.2.1298098159.1544083754; _gid=GA1.2.838980469.1544083754; acw_sc__v2=NWMwOGQ5MmY1Y2VhNDRmNjVlMmM1MGU2YTA3YTI1NDIxNmU3ZmEyOQ==; gr_session_id_eee5a46c52000d401f969f4535bdaa78=c2f91a29-e127-4b9e-94c5-1671dd9e1d25; gr_session_id_eee5a46c52000d401f969f4535bdaa78_c2f91a29-e127-4b9e-94c5-1671dd9e1d25=true; flag=675787-1937131977@qq.com-; _gat_gtag_UA_59006131_1=1\",\n\"Host\": \"www.itjuzi.com\",\n\"Origin\": \"https://www.itjuzi.com\",\n\"Referer\": \"https://www.itjuzi.com/company\",\n\"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1\"\n}\ndef getHeaders():\n url = \"https://www.itjuzi.com/api/authorizations\"\n cookie = ''.join(random.sample(string.ascii_letters + string.digits, 62))\n\n payload = \"{\\\"account\\\":\\\"%s\\\",\\\"password\\\":\\\"%s\\\"}\" % (userName, passWord)\n headers = {\n 'Host': \"www.itjuzi.com\",\n 'Connection': \"keep-alive\",\n 'Content-Length': \"51\",\n 'Accept': \"application/json, text/plain, */*\",\n 'Origin': \"https://www.itjuzi.com\",\n 'User-Agent': \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36\",\n 'Content-Type': \"application/json;charset=UTF-8\",\n 'Referer': \"https://www.itjuzi.com/login?url=%2Fcompany\",\n 'Accept-Encoding': \"gzip, deflate, br\",\n 'Accept-Language': \"zh-CN,zh;q=0.9\",\n 'Cookie': \"acw_tc=%s\" % cookie\n }\n\n response = requests.request(\"POST\", url, data=payload, headers=headers).text\n response = json.loads(response)\n\n token = response['data']['token']\n headers = {\n 'Accept': \"application/json, text/plain, */*\",\n 'Accept-Encoding': \"gzip, deflate, br\",\n 'Accept-Language': \"en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7\",\n 'Authorization': \"%s\" % token,\n 'Connection': \"keep-alive\",\n 'Content-Length': \"146\",\n 'Content-Type': \"application/json;charset=UTF-8\",\n 'Cookie': \"acw_tc=%s;\" % cookie,\n 'Host': \"www.itjuzi.com\",\n 'Origin': \"https://www.itjuzi.com\",\n 'Referer': \"https://www.itjuzi.com/company\",\n 'User-Agent': \"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50\"\n }\n\n return headers\n\n\nheaders0 = getHeaders()\n\n\nurl = \"https://www.itjuzi.com/api/companys\"\n\n\ndef get_invest_info(pageNum,headers):\n #payload = \"{\\\"total\\\":7525,\\\"per_page\\\":20,\\\"page\\\":%s,\\\"type\\\":\\\"\\\",\\\"scope\\\":\\\"\\\",\\\"sub_scope\\\":\\\"\\\",\\\"round\\\":\\\"\\\",\\\"valuation\\\":\\\"\\\",\\\"ipo_platform\\\":\\\"\\\",\\\"equity_ratio\\\":\\\"\\\",\\\"status\\\":\\\"\\\",\\\"prov\\\":\\\"\\\",\\\"city\\\":\\\"\\\",\\\"sort\\\":\\\"year_count\\\",\\\"time\\\":\\\"\\\",\\\"selected\\\":\\\"\\\",\\\"start_time\\\":\\\"\\\",\\\"end_time\\\":\\\"\\\"}\" % pageNum\n payload = \"{\\\"pagetotal\\\":11650,\\\"total\\\":0,\\\"per_page\\\":20,\\\"page\\\":%s,\\\"scope\\\":\\\"\\\",\\\"sub_scope\\\":\\\"\\\",\\\"round\\\":\\\"\\\",\\\"location\\\":\\\"海外\\\",\\\"prov\\\":\\\"\\\",\\\"city\\\":\\\"\\\",\\\"status\\\":\\\"\\\",\\\"sort\\\":\\\"\\\",\\\"selected\\\":\\\"\\\"}\" %pageNum\n payloads = payload.encode('utf-8')\n try :\n response = requests.request('POST', url, headers=headers0, data=payloads)\n ss = response.text.replace('\\n', '')\n sss = json.loads(ss)['data']['data']\n print(str(sss))\n return sss\n\n except requests.exceptions.ConnectionError:\n print('遇到了反爬虫2,休息10秒')\n headers = getHeaders()\n time.sleep(10 + random.random() * 5)\n headers = getHeaders()\n get_invest_info(pageNum=pageNum, headers=headers)\n\n except KeyError:\n print('遇到了反爬虫3,休息10秒,重新生成headers')\n headers = getHeaders()\n print('》》》', headers['Cookie'])\n # time.sleep(10 + random.random() * 5)\n get_invest_info(pageNum=pageNum, headers=headers,charset='utf-8')\n\n\nif __name__ == '__main__':\n pageNum = 382\n while pageNum <= 583:\n try:\n print('爬取第' + str(pageNum) +'页')\n sss = get_invest_info(str(pageNum),headers0)\n with open(\"com_foreign_id.txt\",'a',encoding='utf-8') as file:\n for s in sss:\n file.write(str(s['id']) +'\\n')\n\n print(str(pageNum) +'爬取成功')\n pageNum = pageNum +1\n except TypeError as e:\n pass\n print(e)\n else:\n print('爬虫结束')","sub_path":"scrapy_data/itjuzhi_com_foreign.py","file_name":"itjuzhi_com_foreign.py","file_ext":"py","file_size_in_byte":5259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"518565900","text":"\nclass Node:\n def __init__(self,data, nxt=None):\n self.data = data\n self.nxt = nxt\n\n\nclass linkedList:\n def __init__(self,head=None):\n self.head = Node(head)\n def insert_head(self, val):\n newNode = Node(val,self.head)\n self.head = newNode\n def insert_tail(self,val):\n new_node = Node(val)\n if self.head == None:\n self.head = new_node\n else:\n curr = self.head\n while curr.nxt:\n curr = curr.nxt\n curr.nxt = new_node\n def insert_index(self,val, index):\n new_node = Node(val)\n count = 0\n curr = self.head\n if index == 0:\n temp = self.head\n self.head = new_node\n self.head.nxt = temp\n temp.prev = new_node\n else:\n while curr:\n if (count == index - 1):\n break\n else:\n count += 1\n curr = curr.nxt\n new_node.nxt = curr.nxt\n curr.nxt = new_node\n def printList(self):\n curr = self.head\n while curr:\n print(curr.data)\n curr = curr.nxt\n def find_middle(self):\n fst_ptr = self.head\n slow_ptr = self.head\n while fst_ptr and fst_ptr.nxt:\n fst_ptr = fst_ptr.nxt.nxt\n slow_ptr = slow_ptr.nxt\n print(slow_ptr.data)\n\nnew_node = linkedList()\nnew_node.insert_tail(4)\nnew_node.insert_tail(6)\nnew_node.insert_tail(8)\nnew_node.insert_tail(9)\nnew_node.insert_tail(10)\nnew_node.insert_tail(54)\nnew_node.insert_tail(45)\nnew_node.printList()\nprint(\"-------------\")\nnew_node.find_middle()\n\n","sub_path":"linked-lists/llist-find-middle.py","file_name":"llist-find-middle.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"433437827","text":"import webbrowser;\n\nnew = 2; #open in new tab if possible.\n\ndef display(pos,neg,neu):\n\ttemplate = open(\"template.html\");\n\tlines = template.readlines();\n\tresult = open(\"result.html\",'w');\n\tfor line in lines:\n\t\tif(\"Positive\" in line):\n\t\t\tline = line.replace(\"11\",str(pos));\n\t\telif(\"Negative\" in line):\n\t\t\tline = line.replace(\"2\",str(neg));\n\t\telif(\"Neutral\" in line):\n\t\t\tline = line.replace(\"2\",str(neu));\n\t\tresult.write(line+\"\\n\");\n\t\t#print(line);\n\tresult.close();\n\twebbrowser.open(\"result.html\",new = new);\n\t\nif __name__ == \"__main__\":\n\tpos = int(raw_input(\"Positive: \"));\n\tneg = int(raw_input(\"Negative: \"));\n\tneu = int(raw_input(\"Neutral: \"));\n\tdisplay(pos,neg,neu);\n\traw_input();\n","sub_path":"Source Code/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"264922432","text":"from pyramid.config import Configurator\nfrom sqlalchemy import engine_from_config\nfrom pyramid.authorization import ACLAuthorizationPolicy\nfrom pyramid.authentication import AuthTktAuthenticationPolicy\nimport os\n\nfrom .models import (\n DBSession,\n Base,\n BaseFactory,\n)\n\n\ndef make_session(settings):\n from sqlalchemy.orm import sessionmaker\n engine = engine_from_config(settings, 'sqlalchemy.')\n Session = sessionmaker(bind=engine)\n return Session()\n\n\ndef main(global_config, **settings):\n \"\"\"Return a Pyramid WSGI application.\"\"\"\n if 'DATABASE_URL' in os.environ:\n settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL')\n engine = engine_from_config(settings, 'sqlalchemy.')\n DBSession.configure(bind=engine)\n Base.metadata.bind = engine\n secret = os.environ.get('dsfkljfvjkvnadssvjkbavhfdlbvhfdlv', 'vndjkvbndlv')\n authentication_policy = AuthTktAuthenticationPolicy(secret)\n authorization_policy = ACLAuthorizationPolicy()\n config = Configurator(\n settings=settings,\n authentication_policy=authentication_policy,\n authorization_policy=authorization_policy,\n root_factory=BaseFactory\n )\n config.include('pyramid_jinja2')\n config.add_static_view('static', 'static', cache_max_age=3600)\n config.add_route('index_route', '/')\n config.add_route('new_route', '/add')\n config.add_route('entry_route', '/entries/{id:\\d+}')\n config.add_route('edit_route', '/entries/{id:\\d+}/edit')\n config.add_route('login', '/login')\n config.add_route('logout', '/logout')\n config.scan()\n return config.make_wsgi_app()\n","sub_path":"learning_journal/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"275794756","text":"import glob\nimport os\nfrom typing import Any, Dict, List, Tuple\nimport subprocess\n\nimport numpy as np\nfrom rasterio.windows import Window\nimport srem\n\nfrom constants import OLI_BAND_ID, REFLECTANCE_SCALING_FACTOR\n\n\ndef get_band_id(path: str) -> int:\n band_name = os.path.splitext(os.path.basename(path))[0].split('_')[-1]\n band_id = OLI_BAND_ID[band_name].value\n return band_id\n\n\ndef get_pixel_angle_files(angle_file: str,\n band_id: int,\n output_dir: str) -> Tuple[str, str]:\n cwd = os.getcwd()\n angle_file = os.path.abspath(angle_file)\n os.chdir(output_dir)\n cmd = f'l8_angles {angle_file} BOTH 1 -b {band_id}'\n subprocess.run(cmd, shell=True, check=True, stdout=subprocess.DEVNULL)\n solar_angle_file = glob.glob(os.path.join(output_dir, f'*solar_B0{band_id}.img'))[0]\n sensor_angle_file = glob.glob(os.path.join(output_dir, f'*sensor_B0{band_id}.img'))[0]\n os.chdir(cwd)\n return solar_angle_file, sensor_angle_file\n\n\ndef srem_worker(data: List[np.ndarray],\n window: Window,\n ij: int,\n global_args: Dict[Any, Any]) -> np.ndarray:\n nodata_mask = (data[0] == 0)\n surface_reflectance = srem.srem(\n toa_reflectance=data[0],\n wavelength=global_args['wavelength'],\n solar_azimuth_angle_deg=data[1] / 100.,\n solar_zenith_angle_deg=data[2] / 100.,\n sensor_azimuth_angle_deg=data[3] / 100.,\n sensor_zenith_angle_deg=data[4] / 100.,\n )\n # surface reflectance is scaled in this example.\n scaled_sr = \\\n surface_reflectance * REFLECTANCE_SCALING_FACTOR\n # crop values less than 1 for defining 1 as minimum value.\n scaled_sr[scaled_sr < 1] = 1\n scaled_sr[nodata_mask] = 0\n scaled_sr = scaled_sr.astype(global_args['dtype'])\n scaled_sr = np.expand_dims(scaled_sr, axis=0)\n return scaled_sr\n","sub_path":"examples/landsat8/src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"588730158","text":"__author__ = 'Krzysztof'\n\nimport pygame\nimport os\nfrom pygame.locals import *\n#directions\nRIGHT = 'right'\nLEFT = 'left'\n\n#colors\nWHITE = pygame.Color(255, 255, 255)\nBLACK = pygame.Color(0, 0, 0)\nRED = pygame.Color(255, 0, 0)\nBLUE = pygame.Color(0, 0, 255)\nGREEN = pygame.Color(0, 255, 0)\n\n#buttons\nB_NEW_GAME = 'new_game.png'\nB_NEW_GAME_SEL = 'new_game_selected.png'\nB_OPTIONS = 'options.png'\nB_OPTIONS_SEL = 'options_selected.png'\nB_EXIT = 'exit_game.png'\nB_EXIT_SEL = 'exit_game_selected.png'\n\n#player\nP_BASIC = 'woytek_64x64.png'\nP_STANDING = 'woytek_still.png'\nP_RUNNING = 'woytek_run_zgunem.png'\nP_UP = 'woytek_up.png'\nP_DOWN = 'woytek_down.png'\nP_FIRE = 'woytek_fire1.png'\nP_FIRE_RUN = 'woytek_run_fire.png'\nP_FIRE_UP = 'woytek_fire1.png'\nP_FIRE_DOWN = 'woytek_fire1.png'\n\nP_ALG_STANDING = 'algier.still.png'\nP_ALG_RUNNING = 'algier.run.png'\nP_ALG_UP = 'algier_up.png'\nP_ALG_DOWN = 'algier_down.png'\n\n#enemy\nE_BASIC = 'policeman64x64.png'\nE_STANDING = 'policeman.still.png'\nE_RUNNING = 'policeman.run.png'\nE_DEATH = 'policeman_death.png'\n\n#music\nM_THEME = 'menu music.wav'\nM_FIGHT = 'fight.mid'\n\n#sfx\nSFX_FLASHBANG = 'Flashbang-Kibblesbob-899170896.wav'\nSFX_BING = 'A-Tone-His_Self-1266414414.wav'\nSFX_BLAST = 'Blast-SoundBible.com-2068539061.wav'\nSFX_ROCKET = 'Bottle Rocket-SoundBible.com-332895117.wav'\n\n#backgrounds\nBG_CITY = 'background1-720_CC.png'\n\n#weaponry\nW_GRENADE = 'grenade.png'\nW_EXPLOSION = 'wybuch_prealpha.png'\nW_ROCKET = 'rocket.png'\nW_SMOKE_TRACE = 'wybuch_grey.png'\n\n\n#miscellaneous\nMISC_QUOTE_BANNER = 'wojtek_banner.jpg'\nMISC_NEBULA_MENU = 'main_menu_2'\nMISC_BULLET = 'bullet.png'\nMISC_BLASTER_BULLET = 'blaster_bullet.png'\nMISC_PLAYER_AV = 'rozal_px.png'\nMISC_PLAYER_AV_ALG = 'magic_yolo.png'\nMISC_MEATBALL = 'meatball.png'\nMISC_MEDKIT = 'health_64.png'\nMISC_MENU_BG = 'startscreen.png'\nMISC_ICON = 'qa_icon.png'\n\n#converts\npygame.init()\npygame.display.set_mode((0, 0), pygame.RESIZABLE | pygame.DOUBLEBUF)\n\ndef set_image(img=W_SMOKE_TRACE):\n imageName = os.path.join('img', img)\n image = pygame.image.load(imageName)\n c_image = 1\n rect = image.get_rect()\n image = pygame.transform.scale(image, (int(rect.w), int(rect.h)))\n num_image = rect.w/rect.h\n rect = image.get_rect()\n rect.h = rect.h\n rect.w = rect.w/num_image\n return [image.convert_alpha(), c_image, num_image, rect]\n\nE_STANDING_LOAD = set_image(img=E_STANDING)\nE_RUNNING_LOAD = set_image(img=E_RUNNING)\nE_DEATH_LOAD = set_image(img=E_DEATH)\nSMOKE_TRACE_IMAGE_DATA = set_image(img=W_SMOKE_TRACE)\nMEATBALL_TRACE_IMAGE_DATA = set_image(img=MISC_MEATBALL)","sub_path":"rozi_engine/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":2571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"627444176","text":"#!/usr/bin/env python\n\nimport argparse\nimport sqlite3\nimport json\nimport paho.mqtt.client as mqtt\nimport datetime\n\nfrom timer import Timer\nfrom logger import Logger\n\nlogger = Logger()\n\nclass fileNode:\n def __init__(self, _sender=None, _path=None, _name=None, _mode=None, _ino=None, _dev=None, _nlink=None, _uid=None, _gid=None, _size=None, _mtime=None, _ctime=None, _hash=None):\n sender = _sender\n path = _path\n name = _name\n mode = _mode\n ino = _ino\n dev = _dev\n nlink = _nlink\n uid = _uid\n gid = _gid\n size = _size\n mtime = _mtime\n ctime = _ctime\n hash = _hash\n\n\n\ndef on_connect(client, userdata, flags, rc):\n if rc:\n logger.log('Unable to connect to broker on {}:{} {}'.format(client._host, client._port, mqtt.error_string(rc)), level='ERROR')\n #client.reconnect()\n\n else:\n logger.log('Connected to broker on {}:{}'.format(client._host, client._port))\n\n\n for topic in client.topics:\n if client.verbose:\n logger.log('Subscribing to topic {}'.format(topic))\n\n client.subscribe(topic, qos=2)\n\n\ndef on_disconnect(client, userdata, rc):\n if rc:\n logger.log('Unexpected disconnected from broker: {}'.format(mqtt.error_string(rc)), level='ERROR')\n else:\n logger.log('Disconnected from broker: {}'.format(mqtt.error_string(rc)))\n\n\ndef on_message(client, userdata, msg):\n\n client.msg_count += 1\n\n if client.verbose:\n logger.log('Message from broker: {} {}'.format(msg.topic, msg.payload))\n\n topic = msg.topic\n sender = json.loads(str(msg.payload, encoding='utf-8'))['sender']\n message = json.loads(str(msg.payload, encoding='utf-8'))['message']\n\n if topic == \"library/file/get\":\n cur = client.db.cursor()\n cur.execute(\"SELECT COUNT(id) as count FROM files;\")\n\n elif topic == \"library/file/insert\":\n if node_exist(client, sender, message['path'], message['name']):\n update_file(client, sender, message)\n else:\n insert_file(client, sender, message)\n\n elif topic == \"library/file/update\":\n if node_exist(client, sender, message['path'], message['name']):\n update_file(client, sender, message)\n\n elif topic == \"library/directory/insert\":\n if node_exist(client, sender, message['path'], message['name']):\n update_directory(client, sender, message)\n else:\n insert_directory(client, sender, message)\n\n elif topic == \"library/directory/update\":\n if node_exist(client, sender, message['path'], message['name']):\n update_directory(client, sender, message)\n\n else:\n logger.log('Unhandled topic \\\"{}\\\"'.format(topic))\n\n\ndef node_exist(client, sender, path, name):\n hits = 0\n c = client.db.cursor()\n for nodeType in ['files', 'directories']:\n c.execute('SELECT COUNT(id) as count FROM {} WHERE sender=? AND path=? AND name=?;'.format(nodeType), (sender, path, name))\n row = c.fetchone()\n\n if row['count'] >= 1:\n hits += row['count']\n\n return hits\n\n\n\ndef insert_file(client, sender, message):\n # INSERT\n c = client.db.cursor()\n logger.log('Inserting File {}:{}/{}'.format(sender, message['path'], message['name']))\n c.execute('INSERT INTO files (sender, path, name, mode, ino, dev, nlink, uid, gid, size, mtime, ctime, hash) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (\n sender,\n message['path'],\n message['name'],\n message['mode'],\n message['ino'],\n message['dev'],\n message['nlink'],\n message['uid'],\n message['gid'],\n message['size'],\n message['mtime'],\n message['ctime'],\n message['hash']\n ))\n client.db.commit()\n\n\ndef update_file(client, sender, message):\n # UPDATE\n c = client.db.cursor()\n c.execute('SELECT * FROM files WHERE sender=? AND path=? AND name=?;', (sender, message['path'], message['name']))\n row = c.fetchone()\n\n logger.log('Checking file {}:{}/{}'.format(sender, message['path'], message['name']))\n for key in row.keys():\n if (key == 'id'\n or key == 'sender'\n or key == 'sqltime'):\n\n continue\n\n try:\n if row[key] != message[key]:\n if key == 'hash' and message[key] != None:\n logger.log('- Updating {key}:{old} => {new}'.format(key=key, new=message[key], old=row[key]))\n c.execute('UPDATE files SET {}=? where id=?'.format(key), (message[key], row['id']))\n except KeyError as e:\n continue\n\n client.db.commit()\n\n\ndef insert_directory(client, sender, message):\n #INSERT\n c = client.db.cursor()\n logger.log('Inserting Directory {}:{}/{}'.format(sender, message['path'], message['name']))\n c.execute('INSERT INTO directories (sender, path, name, children, mode, ino, dev, nlink, uid, gid, mtime, ctime) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (\n sender,\n message['path'],\n message['name'],\n message['children'],\n message['mode'],\n message['ino'],\n message['dev'],\n message['nlink'],\n message['uid'],\n message['gid'],\n message['mtime'],\n message['ctime']\n ))\n client.db.commit()\n\n\ndef update_directory(client, sender, message):\n # UPDATE\n c = client.db.cursor()\n c.execute('SELECT * FROM directories WHERE sender=? AND path=? AND name=?;', (sender, message['path'], message['name']))\n row = c.fetchone()\n\n logger.log('Checking directory {}:{}/{}'.format(sender, message['path'], message['name']))\n for key in row.keys():\n if (key == 'id'\n or key == 'sender'\n or key == 'sqltime'):\n\n continue\n\n if row[key] != message[key]:\n logger.log('- Updating {key}:{old} => {new}'.format(key=key, new=message[key], old=row[key]))\n c.execute('UPDATE directories SET {}=? where id=?'.format(key), (message[key], row['id']))\n\n client.db.commit()\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-v', '--verbose', action='store_true', help='enable verbose mode')\n parser.add_argument('--host', default='localhost', help='host addr')\n parser.add_argument('--port', default=1883, type=int, help='host port')\n parser.add_argument('--keepalive', default=60, type=int, help='keepalive')\n parser.add_argument('--ident', default=None, help='MQTT ident')\n parser.add_argument('--db', default=':memory:', help='sqlite database file')\n parser.add_argument('--dbschema', help='sqlite database schema')\n parser.add_argument('--db-export', help='if set sqlite database will be exported of exit')\n args = parser.parse_args()\n\n logger.ident = 'DB'\n\n client = mqtt.Client(args.ident)\n client.verbose = args.verbose\n client.on_connect = on_connect\n client.on_disconnect = on_disconnect\n client.on_message = on_message\n client.username_pw_set(args.ident)\n client.topics = [\n 'library/file/get',\n 'library/file/insert',\n 'library/file/update',\n 'library/directory/get',\n 'library/directory/insert',\n 'library/directory/update'\n ]\n client.dbfile = args.db\n # https://sqlite.org/pragma.html\n client.db = sqlite3.connect('file:{}?mode=rwc&cache=shared'.format(client.dbfile), uri=True)\n #client.db = sqlite3.connect(client.dbfile, timeout=30, isolation_level='Exclusive')\n #client.db = sqlite3.connect(client.dbfile, timeout=30)\n #c = client.db.cursor()\n #c.execute('PRAGMA journal_mode = OFF')\n client.db.execute('PRAGMA journal_mode = WAL;')\n #client.db.execute('PRAGMA journal_mode = MEMORY;')\n #PRAGMA schema.journal_mode = DELETE | TRUNCATE | PERSIST | MEMORY | WAL | OFF\n #client.db.execute('PRAGMA locking_mode = NORMAL;')\n #client.db.execute('PRAGMA locking_mode = EXCLUSIVE;')\n client.db.execute('PRAGMA wal_autocheckpoint=10000;')\n client.db.execute('PRAGMA synchronous = NORMAL;')\n #client.db.execute('PRAGMA synchronous = OFF;')\n #PRAGMA schema.synchronous = 0 | OFF | 1 | NORMAL | 2 | FULL | 3 | EXTRA;\n #c.execute(\"PRAGMA max_page_count = 195313\")\n #c.execute(\"PRAGMA page_size = 512\")\n client.db.execute('PRAGMA threads = 4;')\n #c.execute(\"ATTACH DATABASE 'file:memdb1?mode=memory&cache=shared' AS aux1\")\n\n client.db.row_factory = sqlite3.Row\n client.msg_count = 0\n if args.dbschema:\n with open(args.dbschema, 'r') as f:\n if args.verbose:\n logger.log('Running schema \\\"{}\\\" on db'.format(args.dbschema))\n c = client.db.cursor()\n c.executescript(f.read())\n client.db.commit()\n\n query_timer = Timer()\n try:\n client.connect(args.host, args.port, 60)\n\n try:\n client.loop_forever()\n\n except KeyboardInterrupt:\n logger.log('Server interupted from user')\n client.disconnect()\n\n except ConnectionRefusedError as e:\n logger.log('{}:{} {}'.format(args.host, args.port, e), level='ERROR')\n\n\n\n if args.db_export:\n if client.verbose:\n logger.log('Exporting db to disk.', end=\"\")\n\n with open(args.db_export, 'w') as f:\n for line in client.db.iterdump():\n f.write('%s\\n' % line)\n if client.verbose:\n logger.log('.', end=\"\")\n\n if client.verbose:\n logger.log('done')\n\n client.db.execute('PRAGMA wal_checkpoint(TRUNCATE);')\n client.db.execute('PRAGMA optimize;')\n client.db.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"server/tripme_mqtt_server.py","file_name":"tripme_mqtt_server.py","file_ext":"py","file_size_in_byte":9819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"10849574","text":"# https://leetcode.com/problems/flipping-an-image\n\n# https://leetcode.com/problems/flipping-an-image/solution\n\n\nclass Solution:\n # 11.23%\n def flipAndInvertImage(self, A):\n row, column = len(A), len(A[0])\n for r in range(row):\n i, j = 0, column - 1\n while i < j:\n A[r][i], A[r][j] = A[r][j], A[r][i]\n i += 1\n j -= 1\n for c in range(column):\n A[r][c] = 0 if 1 == A[r][c] else 1\n return A\n\n\ns = Solution()\ndata = [([[1,1,0],[1,0,1],[0,0,0]], [[1,0,0],[0,1,0],[1,1,1]]),\n ([[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]], [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]),\n ]\nfor A, expected in data:\n real = s.flipAndInvertImage(A)\n print('{}, expected {}, real {}, result {}'.format(A, expected, real, expected == real))\n","sub_path":"python/problem-matrix/flipping_an_image.py","file_name":"flipping_an_image.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"399859596","text":"import os\ntotal=0\ndef file_size(path):\n total=os.path.getsize(path)\n if os.path.isdir(path):\n for item in os.listdir(path):\n child_path=os.path.join(path,item)\n total+=file_size(child_path)\n return total\n\npath='/Users/harshavardanmanam/Documents/ds_algo_in_python/Chapter1'\nprint(os.path.isdir(path))\nprint(os.path.getsize(path))\nprint(os.listdir(path))\nprint(file_size(path))","sub_path":"Chapter 4/file_size.py","file_name":"file_size.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"298294484","text":"# Copyright (C) 2018 Atsushi Togo\n# All rights reserved.\n#\n# This file is part of phonopy.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n#\n# * Neither the name of the phonopy project nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport sys\nimport numpy as np\nfrom ase.atoms import Atoms\nfrom ase.io import write\nfrom ase.build import bulk\nfrom ase.calculators.emt import EMT\nfrom hiphive.structure_generation import generate_mc_rattled_structures\nfrom hiphive.utilities import get_displacements\nfrom hiphive import ClusterSpace, StructureContainer, ForceConstantPotential\nfrom hiphive.fitting import Optimizer\n\n\ndef get_fc2(supercell,\n primitive,\n displacements,\n forces,\n atom_list=None,\n options=None,\n log_level=0):\n if options is None:\n option_dict = {}\n else:\n option_dict = decode_options(options)\n\n structures = []\n for d, f in zip(displacements, forces):\n structure = Atoms(cell=supercell.cell,\n scaled_positions=supercell.scaled_positions,\n numbers=supercell.numbers,\n pbc=True)\n structure.new_array('displacements', d)\n structure.new_array('forces', f)\n structure.calc = None\n structures.append(structure)\n\n cutoffs = [option_dict['cutoff'], ]\n cs = ClusterSpace(structures[0], cutoffs)\n print(cs)\n cs.print_orbits()\n\n sc = StructureContainer(cs)\n for structure in structures:\n sc.add_structure(structure)\n print(sc)\n\n opt = Optimizer(sc.get_fit_data())\n opt.train()\n print(opt)\n\n fcp = ForceConstantPotential(cs, opt.parameters)\n print(fcp)\n\n\ndef decode_options(options):\n option_dict = {}\n for pair in options.split(','):\n key, value = [x.strip() for x in pair.split('=')]\n if key == 'cutoff':\n option_dict[key] = float(value)\n return option_dict\n","sub_path":"phonopy/interface/hiphive.py","file_name":"hiphive.py","file_ext":"py","file_size_in_byte":3291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"576253824","text":"import os\n\nCOMPILER = \"g++\"\nSOURCE = [\n \"./src/*.cpp\",\n \"./lib/imgui/imgui*.cpp\",\n \"./lib/imgui/examples/imgui_impl_sdl.cpp\",\n \"./lib/imgui/examples/imgui_impl_opengl3.cpp\",\n \"./lib/imgui/examples/libs/gl3w/GL/gl3w.c\",\n \"./lib/imgui_sdl/imgui_sdl.cpp\"\n]\nSOURCE = \" \".join(SOURCE)\n\n# The name of our executable\nEXECUTABLE = \"spritetool.so\"\n\n# You can can add other arguments as you see fit.\n# What does the \"-D MAC\" command do?\nARGUMENTS = \"-D MAC -std=c++17 -fPIC\" + \" -o \" + EXECUTABLE\n\n# Which directories do we want to include.\nINCLUDES = [\n \"./include/\",\n \"./include/pybind11/include/\",\n \"/Library/Frameworks/SDL2.framework/Headers\",\n \"/Library/Frameworks/SDL2_image.framework/Headers\",\n \"/Library/Frameworks/SDL2_mixer.framework/Headers\",\n \"/Library/Frameworks/SDL2_ttf.framework/Headers\",\n \"./lib/imgui\",\n \"./lib/imgui/examples\",\n \"./lib/imgui/examples/libs/gl3w\",\n \"./lib/imgui_sdl\"\n]\nINCLUDES = ['-I{0}'.format(inc) for inc in INCLUDES]\nINCLUDES = (\" \".join(INCLUDES)) + \" \" + \"`python3 -m pybind11 --includes`\"\n\n# What libraries do we want to include\nDEFAULT_LIBS = \"-framework OpenGl -framework CoreFoundation\"\nLIBRARY_PREFIX = \"-F/Library/Frameworks\"\nLIBRARIES = [\n \"SDL2\",\n \"SDL2_image\",\n \"SDL2_mixer\",\n \"SDL2_ttf\"\n]\nLIBRARIES = ['-framework {0}'.format(lib) for lib in LIBRARIES]\nLIBRARIES = DEFAULT_LIBS + \" \" + LIBRARY_PREFIX + \" \" + \\\n (\" \".join(LIBRARIES)) + \" \" + \"`python3-config --ldflags`\"\n\n# Build a string of our compile commands that we run in the terminal\ncompileString = [\n COMPILER,\n ARGUMENTS,\n INCLUDES,\n SOURCE,\n LIBRARIES\n]\ncompileString = \" \".join(compileString)\n\n# Print out the compile string\nprint(compileString)\n\n# Run our command\nos.system(compileString)\n","sub_path":"Engine/gui/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"641744610","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('office', '0002_syndicate'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='syndicate',\n name='created_at',\n field=models.DateTimeField(default=datetime.datetime.now, verbose_name=b'Data do Cadastro', blank=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='syndicate',\n name='status',\n field=models.BooleanField(default=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='syndicate',\n name='user',\n field=models.ForeignKey(default=None, verbose_name=b'Usu\\xc3\\xa1rio', to=settings.AUTH_USER_MODEL),\n preserve_default=False,\n ),\n ]\n","sub_path":"apps/office/migrations/0003_auto_20150926_1424.py","file_name":"0003_auto_20150926_1424.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"29674076","text":"#!/usr/bin/python\n\"\"\"\n (C) Copyright 2020-2021 Intel Corporation.\n\n SPDX-License-Identifier: BSD-2-Clause-Patent\n\"\"\"\n\nimport time\n\nfrom ior_test_base import IorTestBase\nfrom dmg_utils import check_system_query_status\n\n\nclass CrashIor(IorTestBase):\n # pylint: disable=too-many-ancestors\n \"\"\"Test class Description: DAOS server does not need to be restarted\n when the application crashes.\n :avocado: recursive\n \"\"\"\n\n def setUp(self):\n \"\"\"Set up test before executing.\"\"\"\n super().setUp()\n self.dmg = self.get_dmg_command()\n\n def test_crashior(self):\n \"\"\"Jira ID: DAOS-4332.\n\n Test Description:\n DAOS server does not need to be restarted when the application\n crashes.\n\n Use Cases:\n Run IOR over dfuse.\n Cancel IOR in the middle of io.\n Check daos server does not need to be restarted when the\n application crashes.\n\n :avocado: tags=all,daosio,hw,medium,ib2,full_regression,crashior\n \"\"\"\n # run ior and crash it during write process\n self.run_ior_with_pool()\n # check if ior write has started\n self.check_subprocess_status()\n # allow 50 secs of write to happen\n time.sleep(50)\n # kill ior process in the middle of IO\n self.stop_ior()\n\n # obtain server rank info using 'dmg system query -v'\n scan_info = self.dmg.system_query(verbose=True)\n # check for any crashed servers after killing ior in the middle\n if not check_system_query_status(scan_info):\n self.fail(\"One or more server crashed\")\n\n # run ior again and crash it during read process\n self.run_ior_with_pool()\n # allow write to finish which is set at stonewalling limit of 100 sec\n # hence allowing extra 5 secs for read to begin\n time.sleep(105)\n # check if ior read process started\n self.check_subprocess_status(\"read\")\n # kill ior process in middle of read process\n self.stop_ior()\n\n # obtain server rank info using 'dmg system query -v'\n scan_info = self.dmg.system_query(verbose=True)\n # check for any crashed servers after killing ior in the middle\n if not check_system_query_status(scan_info):\n self.fail(\"One or more server crashed\")\n\n # run ior again if everything goes well till now and allow it to\n # complete without killing in the middle this time to check\n # if io goes as expected after crashing it previously\n self.run_ior_with_pool()\n self.job_manager.wait()\n","sub_path":"src/tests/ftest/ior/crash_ior.py","file_name":"crash_ior.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"52452882","text":"from datetime import datetime\n\nfrom flask import url_for\n\nfrom kron import db, is_ok, ModelEventListeners\n\n\ndocuments_authors = db.Table(\n \"documents_authors\",\n db.Column(\"document_id\", db.Integer, db.ForeignKey(\"documents.id\")),\n db.Column(\"person_id\", db.Integer, db.ForeignKey(\"people.id\"))\n)\n\ndocuments_people = db.Table(\n \"documents_people\",\n db.Column(\"document_id\", db.Integer, db.ForeignKey(\"documents.id\")),\n db.Column(\"person_id\", db.Integer, db.ForeignKey(\"people.id\"))\n)\n\ndocuments_topics = db.Table(\n \"documents_topics\",\n db.Column(\"document_id\", db.Integer, db.ForeignKey(\"documents.id\")),\n db.Column(\"topic_id\", db.Integer, db.ForeignKey(\"topics.id\"))\n)\n\n\nclass Document(db.Model):\n __tablename__ = \"documents\"\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(128), unique=True)\n dates = db.Column(db.UnicodeText)\n citations = db.Column(db.UnicodeText)\n notes = db.Column(db.UnicodeText)\n last_update = db.Column(db.DateTime)\n box_id = db.Column(db.Integer, db.ForeignKey(\"boxes.id\"))\n authors = db.relationship(\n \"Person\", secondary=documents_authors,\n backref=db.backref(\"documents_by\", lazy=\"dynamic\"))\n people = db.relationship(\n \"Person\", secondary=documents_people,\n backref=db.backref(\"documents_in\", lazy=\"dynamic\"))\n topics = db.relationship(\n \"Topic\", secondary=documents_topics, backref=\"documents\")\n\n def __init__(self, title, dates=None, citations=None, notes=None):\n db.Model.__init__(self)\n self.title = title\n self.dates = dates\n self.citations = citations\n self.notes = notes\n\n @staticmethod\n def from_dict(data):\n data = data.get(\"document\")\n if not is_ok(data):\n raise TypeError(\"Missing data: document\")\n if not is_ok(data.get(\"title\")):\n raise TypeError(\"Missing data: document.title\")\n if (Document.query.filter_by(title=data[\"title\"]).first() or\n len(data[\"title\"]) >= 128):\n raise TypeError(\"Invalid data: document.title\")\n return Document(\n title=data[\"title\"],\n dates=data.get(\"dates\"),\n citations=data.get(\"citations\"),\n notes=data.get(\"notes\")\n )\n\n def get_url(self, full=False):\n return url_for(\"kron.get_document\", id=self.id, _external=full)\n\n def __repr__(self):\n return \"<Document {id}>\".format(id=self.id)\n\n\ndb.event.listen(Document.title, \"set\", ModelEventListeners.on_update)\ndb.event.listen(Document.box_id, \"set\", ModelEventListeners.on_update)\ndb.event.listen(Document.dates, \"set\", ModelEventListeners.on_update)\ndb.event.listen(Document.citations, \"set\", ModelEventListeners.on_update)\ndb.event.listen(Document.notes, \"set\", ModelEventListeners.on_update)\n","sub_path":"kron/models/document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":2826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"389544000","text":"import prompts\nfrom color import color\n\nclass Ability:\n ## abilities are for the player and generally lower the read speed of their opponents\n def __init__(self, name, desc, mpreq, effect, uses, stat):\n self.name = name\n self.desc = desc\n self.mpreq = mpreq\n self.effect = effect\n self.max_uses = uses\n self.uses = self.max_uses\n self.stat = stat\n \n def refresh(self):\n self.uses = self.max_uses\n \n def useCounter(self):\n if self.uses > 0:\n self.uses -= 1\n return 1\n elif self.uses == 0:\n return 0\n \n def use(self, target, mon):\n if target.stats['Determination'] >= self.mpreq:\n if self.useCounter() is 1:\n damage = self.effect\n if (mon.stats[self.stat] - self.effect) < 0:\n while (mon.stats[self.stat] > 0) and (damage > 0):\n damage -= 1\n mon.stats[self.stat] -= 1\n print()\n print(color.YELLOW + \"Using {0}, you dealt {1} damage to {2}'s {3}.\\nYou have {4} uses remaining.\".format(self.name, damage, mon.name, self.stat, self.uses) + color.END)\n print()\n prompts.prompt('Continue')\n else:\n mon.stats[self.stat] -= self.effect\n print()\n print(color.YELLOW + \"Using {0}, you dealt {1} damage to {2}'s {3}.\\nYou have {4} uses remaining.\".format(self.name, damage, mon.name, self.stat, self.uses) + color.END)\n print()\n prompts.prompt('Continue')\n elif self.useCounter() is 0:\n print()\n prompts.prompt('NoUses')\n print()\n prompts.prompt('Continue')\n else:\n print()\n prompts.prompt('NoStat')\n print()\n prompts.prompt('Continue')\n \n","sub_path":"abilities.py","file_name":"abilities.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"230381981","text":"from graphics import *\nfrom button import Button\n\ndef main():\n win = GraphWin(\"Smiley Face\")\n win.setCoords(0, 0, 10, 10)\n win.setBackground(\"green\")\n\n eyesButt = Button(win, Point(3, 1), 3, 1, \"Eyes\")\n talkButt = Button(win, Point(7, 1), 3, 1, \"Talk\")\n quitButt = Button(win, Point(5, 9), 2, 1, \"Quit\") \n eyesButt.activate()\n talkButt.activate()\n quitButt.activate()\n\n head = Circle(Point(5, 5), 3)\n head.draw(win)\n\n eyeOne = Circle(Point(4, 6), 0.5)\n eyeOne.draw(win)\n\n eyeTwo = Circle(Point(6, 6), 0.5)\n eyeTwo.draw(win)\n\n mouth = Line(Point(4, 4), Point(6, 4))\n mouth.draw(win)\n \n pt = win.getMouse()\n indexOne = 0\n indexTwo = 0\n while not quitButt.clicked(pt):\n if eyesButt.clicked(pt):\n # print \"EyesButton pressed\"\n indexOne += 1\n # print indexOne\n \n # eyes go up\n if indexOne % 2 == 1:\n eyeOne.undraw()\n eyeTwo.undraw()\n eyeOne = Circle(Point(4, 6.3), 0.5)\n eyeTwo = Circle(Point(6, 6.3), 0.5)\n eyeOne.draw(win)\n eyeTwo.draw(win)\n \n # eyes go down\n if indexOne % 2 == 0:\n eyeOne.undraw()\n eyeTwo.undraw()\n eyeOne = Circle(Point(4, 6), 0.5)\n eyeTwo = Circle(Point(6, 6), 0.5)\n eyeOne.draw(win)\n eyeTwo.draw(win)\n\n if talkButt.clicked(pt):\n # print \"TalkButton pressed\"\n indexTwo += 1\n # print indexTwo\n\n #mouth closed\n if indexTwo % 2 == 1:\n mouth.undraw()\n mouth = Rectangle(Point(4, 4), Point(6, 3.5))\n mouth.draw(win)\n\n if indexTwo % 2 == 0:\n mouth.undraw()\n mouth = Line(Point(4, 4), Point(6, 4))\n mouth.draw(win)\n \n pt = win.getMouse()\n\n win.close()\n \nmain()\n","sub_path":"Programming - Python/SmileyFace/Lab.py","file_name":"Lab.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"618735197","text":"#-*- coding: UTF-8 -*-\nimport threading\nimport time\nimport redis\nimport yaml\nfrom operator import itemgetter\nfrom AverageLine import AverageLine\nimport timeit\n\n\nclass Config:\n def __init__(self, fn_config:str):\n self.config_flist = self.init_flist()\n self.config_optlist = self.init_optlist()\n self.config_slist = self.init_slist(fn_config)\n print(self.config_flist)\n print(self.config_optlist)\n print(self.config_slist)\n\n def init_flist(self):\n conn = redis.Redis(host=\"168.36.1.115\", port=6380, password=\"\", charset='gb18030', errors='replace',\n decode_responses=True)\n pre = \"qdb:securityex:derivatives:\"\n code = \"CODE\"\n t = ['IC', 'IF', 'IH']\n d = dict()\n for i in t:\n for j in range(1, 5):\n d[i + \"0\" + str(j)] = conn.get(pre + i + \"0\" + str(j) + \":CODE\")\n return d\n\n def init_optlist(self):\n conn = redis.Redis(host=\"168.36.1.170\", port=6379, password=\"\", charset='gb18030', errors='replace',\n decode_responses=True)\n keys = conn.keys()\n\n re = dict()\n num = 0\n for key in keys:\n if key.startswith(\"OPLST:01\"):\n num = num + 1\n # print(key)\n code = conn.hget(key, 'InstrumentCode')\n re_key = code[7:]\n if not re_key in re.keys():\n re[re_key] = ['', '']\n if code[6] == 'P':\n re[re_key][1] = conn.hget(key, 'InstrumentID')\n if code[6] == 'C':\n re[re_key][0] = conn.hget(key, 'InstrumentID')\n # print(num)\n return re\n\n def init_slist(self,filename: str):\n with open(filename, 'r') as file:\n cont = file.read()\n res = yaml.load(cont, Loader=yaml.FullLoader)\n return res['config']['slist']\n\n\ndef second(key:str):\n print(\"It is \" + str(key),time.time(),time.localtime())\n\n\nclass PeriodAPP():\n def __init__(self, firstrange:list, secondrange: list):\n self.currentDate = str(time.localtime().tm_year) + \"-\" + str(time.localtime().tm_mon) + \"-\" + str(time.localtime().tm_mday) #> \"2019-07-11\"\n\n self.f_starttime = time.mktime(time.strptime(self.currentDate + \" \" + firstrange[0] , \"%Y-%m-%d %H:%M:%S\")) # > 1563785375.0012558\n self.f_endtime = time.mktime(time.strptime(self.currentDate + \" \" + firstrange[1] , \"%Y-%m-%d %H:%M:%S\")) # > 1563785475.0012558\n self.s_starttime = time.mktime(time.strptime(self.currentDate + \" \" + secondrange[0] , \"%Y-%m-%d %H:%M:%S\")) # > 1563785575.0012558\n self.s_endtime = time.mktime(time.strptime(self.currentDate + \" \" + secondrange[1] , \"%Y-%m-%d %H:%M:%S\")) # > 1563785675.0012558\n\n self.config = Config(\"redis_mdld.yaml\")\n # self.a5s = AverageLine(0)\n # self.a10s = AverageLine(1)\n # self.a15s = AverageLine(2)\n # self.a30s = AverageLine(3)\n # self.a1m = AverageLine(4)\n # self.a3m = AverageLine(5)\n # self.a5m = AverageLine(6)\n # self.a10m = AverageLine(7)\n # self.a15m = AverageLine(8)\n # self.a30m = AverageLine(9)\n # self.a1h = AverageLine(10)\n # self.a2h = AverageLine(11)\n # self.a4h = AverageLine(12)\n # self.a1d = AverageLine(13)\n self.conn_r = redis.Redis(host=\"168.36.1.115\", port=6379, password=\"\", charset='gb18030', errors='replace',\n decode_responses=True)\n self.conn_w = redis.Redis(host=\"168.36.1.116\", port = 6379, password=\"\", charset='gb18030',errors=\"replace\",\n decode_responses=True)\n self.conn_r2 = redis.Redis(host=\"192.168.40.134\", port=6379, password=\"\", charset='gb18030', errors='replace',\n decode_responses=True)\n\n def timeit(func):\n def test(self):\n start = time.perf_counter()\n func(self)\n end = time.perf_counter()\n print(\"period time used: \", end - start)\n return test\n\n def vcompute(self, xingquan_list:list, time:str, pe:int, cur_ts:int, j:int, conn_w):\n # print(p_run[j])\n\n if pe < xingquan_list[0]['XingQuan'] or pe > xingquan_list[len(xingquan_list) - 1]['XingQuan']:\n if j == 0:\n print(\"PE-500在行权价以外\")\n return\n if j == 1:\n print(\"PE在行权价以外\")\n return\n if j == 2:\n print(\"PE+500在行权价以外\")\n return\n cont = {1:\"0000\", 0:\"N050\", 2:\"0050\"}.get(j, \"xxxx\")\n\n i = 0\n while i < len(xingquan_list):\n if pe < xingquan_list[i]['XingQuan']:\n # print(p_runj,xingquan_list[i]['XingQuan'])\n pre_c_p = 1.0 * (float(xingquan_list[i - 1]['C_Latest']) - float(xingquan_list[i]['C_Latest'])) / (\n float(xingquan_list[i]['XingQuan']) - float(xingquan_list[i-1]['XingQuan'])) * (\n float(xingquan_list[i]['XingQuan']) - float(pe)) + float(xingquan_list[i][\n 'C_Latest'])\n pre_p_p = 1.0 * (float(xingquan_list[i]['P_Latest']) - float(xingquan_list[i-1]['P_Latest'])) / (\n float(xingquan_list[i]['XingQuan']) - float(xingquan_list[i-1]['XingQuan'])) * (\n float(pe) - float(xingquan_list[i - 1]['XingQuan'])) + float(xingquan_list[i - 1][\n 'P_Latest'])\n pre_c_sp1 = 1.0 * (float(xingquan_list[i - 1]['C_SP1']) - float(xingquan_list[i]['C_SP1'])) / (\n float(xingquan_list[i]['XingQuan']) - float(xingquan_list[i - 1]['XingQuan'])) * (\n float(xingquan_list[i]['XingQuan']) - float(pe) ) + \\\n float(xingquan_list[i]['C_SP1'])\n pre_p_sp1 = 1.0 * (float(xingquan_list[i]['P_SP1']) - float(xingquan_list[i-1]['P_SP1'])) / (\n float(xingquan_list[i]['XingQuan']) - float(xingquan_list[i-1]['XingQuan'])) * (\n float(pe) - float(xingquan_list[i - 1]['XingQuan'])) + float(xingquan_list[i - 1][\n 'P_SP1'])\n pre_c_bp1 = 1.0 * (float(xingquan_list[i-1]['C_BP1']) - float(xingquan_list[i]['C_BP1'])) / (\n float(xingquan_list[i]['XingQuan']) - float(xingquan_list[i - 1]['XingQuan'])) * (\n float(xingquan_list[i]['XingQuan']) - float(pe)) + \\\n float(xingquan_list[i]['C_BP1'])\n pre_p_bp1 = 1.0 * (float(xingquan_list[i]['P_BP1']) - float(xingquan_list[i-1]['P_BP1'])) / (\n float(xingquan_list[i]['XingQuan']) - float(xingquan_list[i-1]['XingQuan'])) * (\n float(pe) - float(xingquan_list[i - 1]['XingQuan'])) + float(xingquan_list[i - 1][\n 'P_BP1'])\n # print(xingquan_list[i]['C_Latest'],xingquan_list[i]['P_Latest'])\n # print({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1},{'LATEST': pre_p_p, 'SP1': pre_p_sp1, 'BP1': pre_p_bp1})\n conn_w.hmset(\"MDLD:\" + str(cur_ts) + \":V:C\" + time + 'MV' + cont,\n {'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # if j == 1:\n # self.a5s.vc00queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a10s.vc00queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a15s.vc00queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a30s.vc00queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a1m.vc00queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a3m.vc00queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a5m.vc00queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a10m.vc00queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a15m.vc00queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a30m.vc00queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a1h.vc00queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a2h.vc00queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a4h.vc00queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # if j == 2:\n # self.a5s.vc05queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a10s.vc05queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a15s.vc05queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a30s.vc05queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a1m.vc05queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a3m.vc05queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a5m.vc05queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a10m.vc05queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a15m.vc05queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a30m.vc05queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a1h.vc05queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a2h.vc05queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a4h.vc05queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # if j == 0:\n # self.a5s.vcn5queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a10s.vcn5queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a15s.vcn5queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a30s.vcn5queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a1m.vcn5queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a3m.vcn5queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a5m.vcn5queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a10m.vcn5queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a15m.vcn5queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a30m.vcn5queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a1h.vcn5queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a2h.vcn5queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n # self.a4h.vcn5queue[time].append({'LATEST': pre_c_p, 'SP1': pre_c_sp1, 'BP1': pre_c_bp1,'pe':pe})\n\n conn_w.hmset(\"MDLD:\" + str(cur_ts) + \":V:P\" + time + 'MV' + cont,\n {'LATEST': pre_p_p, 'SP1': pre_p_sp1, 'BP1': pre_p_bp1,'pe':pe})\n d = {'LATEST': pre_p_p, 'SP1': pre_p_sp1, 'BP1': pre_p_bp1,'pe':pe}\n # if j == 1:\n # self.a5s.vp00queue[time].append(d)\n # self.a10s.vp00queue[time].append(d)\n # self.a15s.vp00queue[time].append(d)\n # self.a30s.vp00queue[time].append(d)\n # self.a1m.vp00queue[time].append(d)\n # self.a3m.vp00queue[time].append(d)\n # self.a5m.vp00queue[time].append(d)\n # self.a10m.vp00queue[time].append(d)\n # self.a15m.vp00queue[time].append(d)\n # self.a30m.vp00queue[time].append(d)\n # self.a1h.vp00queue[time].append(d)\n # self.a2h.vp00queue[time].append(d)\n # self.a4h.vp00queue[time].append(d)\n # if j == 2:\n # self.a5s.vp05queue[time].append(d)\n # self.a10s.vp05queue[time].append(d)\n # self.a15s.vp05queue[time].append(d)\n # self.a30s.vp05queue[time].append(d)\n # self.a1m.vp05queue[time].append(d)\n # self.a3m.vp05queue[time].append(d)\n # self.a5m.vp05queue[time].append(d)\n # self.a10m.vp05queue[time].append(d)\n # self.a15m.vp05queue[time].append(d)\n # self.a30m.vp05queue[time].append(d)\n # self.a1h.vp05queue[time].append(d)\n # self.a2h.vp05queue[time].append(d)\n # self.a4h.vp05queue[time].append(d)\n # if j == 0:\n # self.a5s.vpn5queue[time].append(d)\n # self.a10s.vpn5queue[time].append(d)\n # self.a15s.vpn5queue[time].append(d)\n # self.a30s.vpn5queue[time].append(d)\n # self.a1m.vpn5queue[time].append(d)\n # self.a3m.vpn5queue[time].append(d)\n # self.a5m.vpn5queue[time].append(d)\n # self.a10m.vpn5queue[time].append(d)\n # self.a15m.vpn5queue[time].append(d)\n # self.a30m.vpn5queue[time].append(d)\n # self.a1h.vpn5queue[time].append(d)\n # self.a2h.vpn5queue[time].append(d)\n # self.a4h.vpn5queue[time].append(d)\n break\n i = i + 1\n\n def getTime(self,key):\n currentTime = key + int(time.mktime(time.strptime(self.currentDate + \" \" + \"00:00:00\" , \"%Y-%m-%d %H:%M:%S\"))) - 3600\n # print(time.localtime(currentTime).tm_hour,time.localtime(currentTime).tm_min,time.localtime(currentTime).tm_sec)\n return str(time.localtime(currentTime).tm_hour) + \":\" + str(time.localtime(currentTime).tm_min) + \":\" + str(time.localtime(currentTime).tm_sec)\n\n @timeit\n def run(self):\n key = int(time.time())-int(time.mktime(time.strptime(self.currentDate + \" \" + \"00:00:00\" , \"%Y-%m-%d %H:%M:%S\"))) + 3600 # > 1563785675\n print(\"当前时间:\" + str(key),self.getTime(key))\n conn_r = self.conn_r.pipeline(transaction=False)\n conn_w = self.conn_w.pipeline(transaction=False)\n\n cur_ts = key\n conn_w.set(\"MDLD:cur_ts\",cur_ts)\n pre = 'KZ:F'\n f_d_list = dict()\n # print(\"期货列表\")\n for keyname, key in self.config.config_flist.items():\n # print(pre+key+\":LATEST\",pre+key+\":BP1\",pre+key+\":SP1\")\n conn_r.mget([pre+key+\":LATEST\",pre+key+\":BP1\",pre+key+\":SP1\"])\n\n pre = 'KZ:'\n pre1 = 'KZ:JZ0000KZE'\n\n for key in self.config.config_slist:\n conn_r.mget([pre + key + \":LATEST\", pre+key + \":BP1\", pre + key + \":SP1\"])\n conn_r.mget([pre1 + key[1:] +\":NEW\", pre1 + key[1:] + \":B1\", pre1 + key[1:] + \":S1\"])\n conn_r2 = self.conn_r2.pipeline(transaction=False)\n # print(\"期权列表\")\n op_c_p_price = list()\n date_list = set()\n for pxname, (icode_c, icode_p)in self.config.config_optlist.items():\n #> '1909M02750': ['10001709', '10001710']\n # print(item[0][:4])\n conn_r2.hmget(\"MD:01\" + icode_c,'Latest','SP1','BP1') #> \"MD:0110001709\"\n conn_r2.hmget(\"MD:01\" + icode_p,'Latest','SP1','BP1')\n r1_result = conn_r.execute()\n r2_result = conn_r2.execute()\n # print(r1_result, r2_result)\n r1_index = 0\n for keyname, key in self.config.config_flist.items():\n # print(pre+key+\":LATEST\",pre+key+\":BP1\",pre+key+\":SP1\")\n latest, bp1, sp1 = r1_result[r1_index]\n r1_index = r1_index + 1\n d = dict()\n d['LATEST'] = latest\n d['BP1'] = bp1\n d['SP1'] = sp1\n # print(d)\n # self.a5s.fqueue[key].append(d)\n # self.a10s.fqueue[key].append(d)\n # self.a15s.fqueue[key].append(d)\n # self.a30s.fqueue[key].append(d)\n # self.a1m.fqueue[key].append(d)\n # self.a3m.fqueue[key].append(d)\n # self.a5m.fqueue[key].append(d)\n # self.a10m.fqueue[key].append(d)\n # self.a15m.fqueue[key].append(d)\n # self.a30m.fqueue[key].append(d)\n # self.a1h.fqueue[key].append(d)\n # self.a2h.fqueue[key].append(d)\n # self.a4h.fqueue[key].append(d)\n f_d_list[keyname] = d\n conn_w.hmset(\"MDLD:\" + str(cur_ts) + \":F:F\" + key, d)\n pre = 'KZ:'\n pre1 = 'KZ:JZ0000KZE'\n # print(\"现货列表\")\n pe = 0\n pe300 = 0\n pe500 = 0\n pe_510050_SP1 = 0\n pe_510050_BP1 = 0\n jz_510050_SP1 = 0\n jz_510050_BP1 =0\n pe_510300_SP1 = 0\n pe_510300_BP1 = 0\n jz_510300_SP1 = 0\n jz_510300_BP1 =0\n pe_510500_SP1 = 0\n pe_510500_BP1 = 0\n jz_510500_SP1 = 0\n jz_510500_BP1 =0\n for key in self.config.config_slist:\n latest, bp1, sp1 = r1_result[r1_index]\n r1_index = r1_index + 1\n d = dict()\n d['LATEST'] = latest\n d['BP1'] = bp1\n d['SP1'] = sp1\n # print(d)\n conn_w.hmset(\"MDLD:\" + str(cur_ts) + \":S:\" + key,d)\n new, b1, s1 = r1_result[r1_index]\n r1_index = r1_index + 1\n if new == None:\n new = 0\n if b1 == None:\n b1 = 0\n if s1 == None:\n s1 = 0\n d2 = dict()\n d2['LATEST'] = new\n d2['BP1'] = b1\n d2['SP1'] = s1\n # self.a5s.squeue[key].append(d)\n # self.a10s.squeue[key].append(d)\n # self.a15s.squeue[key].append(d)\n # self.a30s.squeue[key].append(d)\n # self.a1m.squeue[key].append(d)\n # self.a3m.squeue[key].append(d)\n # self.a5m.squeue[key].append(d)\n # self.a10m.squeue[key].append(d)\n # self.a15m.squeue[key].append(d)\n # self.a30m.squeue[key].append(d)\n # self.a1h.squeue[key].append(d)\n # self.a2h.squeue[key].append(d)\n # self.a4h.squeue[key].append(d)\n # print(d)\n conn_w.hmset(\"MDLD:\" + str(cur_ts) + \":JZ:\" + key,d2)\n if key == \"S510050\":\n pe = int(d['LATEST'])\n pe_510050_SP1 = int(d['SP1'])\n pe_510050_BP1 = int(d['BP1'])\n jz_510050_SP1 = float(d2['SP1'])\n jz_510050_BP1 = float(d2['BP1'])\n if key == \"S510300\":\n pe300 = int(d['LATEST'])\n pe_510300_SP1 = int(d['BP1'])\n pe_510300_BP1 = int(d['SP1'])\n jz_510300_SP1 = float(d2['SP1'])\n jz_510300_BP1 = float(d2['BP1'])\n if key == \"S510500\":\n pe500 = int(d['LATEST'])\n pe_510500_SP1 = int(d['SP1'])\n pe_510500_BP1 = int(d['BP1'])\n jz_510500_SP1 = float(d2['SP1'])\n jz_510500_BP1 = float(d2['BP1'])\n # conn_r = redis.Redis(host=\"168.36.1.170\", port=6379, password=\"\", charset='gb18030', errors='replace',\n # decode_responses=True)\n # print(\"期权列表\")\n op_c_p_price = list()\n date_list = set()\n r2_index = 0\n for pxname, (icode_c, icode_p)in self.config.config_optlist.items():\n #> '1909M02750': ['10001709', '10001710']\n # print(item[0][:4])\n date_list.add(pxname[:4]) #> “1909”\n tem1 = dict()\n tem1['Latest'], tem1['SP1'], tem1['BP1'] = r2_result[r2_index] #> \"MD:0110001709\"\n r2_index = r2_index + 1\n tem2 = dict()\n tem2['Latest'], tem2['SP1'], tem2['BP1'] = r2_result[r2_index]\n r2_index = r2_index + 1\n # print(tem1, tem2)\n if tem1['Latest'] == None or tem1['BP1'] == None or tem1['SP1'] == None or tem2['Latest'] == None or tem2['SP1'] == None or tem2['BP1'] == None:\n continue\n # print(tem1)\n price_dict= dict()\n price_dict['Name'] = pxname\n price_dict['XingQuan'] = int(pxname[-5:]) * 10 #> \"02750\"\n price_dict['C_Latest'] = tem1['Latest']\n price_dict['C_BP1'] = tem1['BP1']\n price_dict['C_SP1'] = tem1['SP1']\n price_dict['P_Latest'] = tem2['Latest']\n price_dict['P_BP1'] = tem2['BP1']\n price_dict['P_SP1'] = tem2['SP1']\n op_c_p_price.append(price_dict)\n # print(tem1)\n # print(tem2)\n if tem1['Latest'] != None and tem1['BP1'] != None and tem1['SP1'] != None:\n td = {\"LATEST\": tem1['Latest'], 'BP1': tem1['BP1'], 'SP1': tem1['SP1']}\n conn_w.hmset(\"MDLD:\" + str(cur_ts) + \":OP:\" + \"C\" + pxname, td)\n\n # self.a5s.opcqueue[pxname].append(td)\n # self.a10s.opcqueue[pxname].append(td)\n # self.a15s.opcqueue[pxname].append(td)\n # self.a30s.opcqueue[pxname].append(td)\n # self.a1m.opcqueue[pxname].append(td)\n # self.a3m.opcqueue[pxname].append(td)\n # self.a5m.opcqueue[pxname].append(td)\n # self.a10m.opcqueue[pxname].append(td)\n # self.a15m.opcqueue[pxname].append(td)\n # self.a30m.opcqueue[pxname].append(td)\n # self.a1h.opcqueue[pxname].append(td)\n # self.a2h.opcqueue[pxname].append(td)\n # self.a4h.opcqueue[pxname].append(td)\n if tem2['Latest'] != None and tem2['SP1'] != None and tem2['BP1'] != None:\n td = {\"LATEST\":tem2['Latest'],'BP1':tem2['BP1'],'SP1':tem2['SP1']}\n conn_w.hmset(\"MDLD:\" + str(cur_ts) + \":OP:\" + \"P\" + pxname, td)\n # self.a5s.oppqueue[pxname].append(td)\n # self.a10s.oppqueue[pxname].append(td)\n # self.a15s.oppqueue[pxname].append(td)\n # self.a30s.oppqueue[pxname].append(td)\n # self.a1m.oppqueue[pxname].append(td)\n # self.a3m.oppqueue[pxname].append(td)\n # self.a5m.oppqueue[pxname].append(td)\n # self.a10m.oppqueue[pxname].append(td)\n # self.a15m.oppqueue[pxname].append(td)\n # self.a30m.oppqueue[pxname].append(td)\n # self.a1h.oppqueue[pxname].append(td)\n # self.a2h.oppqueue[pxname].append(td)\n # self.a4h.oppqueue[pxname].append(td)\n px = int(pxname[-5:])*10\n pc = int(tem1['Latest'])\n pp = int(tem2['Latest'])\n po= px + pc - pp\n a5 = po - pe\n pcbp1 = int(tem1['BP1'])\n ppsp1 = int(tem2['SP1'])\n pcsp1 = int(tem1['SP1'])\n ppbp1 = int(tem2['BP1'])\n a5s = px + pcbp1 - ppsp1 - pe\n a5b = px + pcsp1 - ppbp1 - pe\n d = dict()\n d['LATEST'] = a5\n d['BP1'] = a5b\n d['SP1'] = a5s\n d['Pe'] = pe\n # self.a5s.a5queue[pxname].append(d)\n # self.a10s.a5queue[pxname].append(d)\n # self.a15s.a5queue[pxname].append(d)\n # self.a30s.a5queue[pxname].append(d)\n # self.a1m.a5queue[pxname].append(d)\n # self.a3m.a5queue[pxname].append(d)\n # self.a5m.a5queue[pxname].append(d)\n # self.a10m.a5queue[pxname].append(d)\n # self.a15m.a5queue[pxname].append(d)\n # self.a30m.a5queue[pxname].append(d)\n # self.a1h.a5queue[pxname].append(d)\n # self.a2h.a5queue[pxname].append(d)\n # self.a4h.a5queue[pxname].append(d)\n conn_w.hmset(\"MDLD:\" + str(cur_ts) + \":A5:\" + pxname,d)\n conn_w.set(\"MDLD:\" + str(cur_ts) + \":PO:\" + pxname,po)\n for key in self.config.config_flist.keys():\n d = dict()\n if key.startswith(\"IH\"):\n d[\"B\"] = int(f_d_list[key]['BP1'])//1000 - pe_510050_SP1\n d[\"S\"] = int(f_d_list[key]['SP1'])//1000 - pe_510050_BP1\n d[\"L\"] = int(f_d_list[key]['LATEST'])//1000 - pe\n d[\"C\"] = int(f_d_list[key]['BP1'])//1000 - jz_510050_SP1 * 10000\n d[\"R\"] = int(f_d_list[key]['SP1'])//1000 - jz_510050_BP1 * 10000\n elif key.startswith(\"IF\"):\n d[\"B\"] = int(f_d_list[key]['BP1'])//1000 - pe_510300_BP1\n d[\"S\"] = int(f_d_list[key]['SP1'])//1000 - pe_510300_BP1\n d[\"L\"] = int(f_d_list[key]['LATEST'])//1000 - pe300\n d[\"C\"] = int(f_d_list[key]['BP1'])//1000 - jz_510300_SP1 * 10000\n d[\"R\"] = int(f_d_list[key]['SP1'])//1000 - jz_510300_BP1 * 10000\n elif key.startswith(\"IC\"):\n d[\"B\"] = int(f_d_list[key]['BP1'])//1000 - pe_510500_BP1\n d[\"S\"] = int(f_d_list[key]['SP1'])//1000 - pe_510500_BP1\n d[\"L\"] = int(f_d_list[key]['LATEST'])//1000 - pe500\n d[\"C\"] = int(f_d_list[key]['BP1'])//1000 - jz_510500_SP1 * 10000\n d[\"R\"] = int(f_d_list[key]['SP1'])//1000 - jz_510500_BP1 * 10000\n conn_w.hmset(\"MDLD:\" + str(cur_ts) + \":A13:\" + key, d)\n\n # for i in range(len(op_c_p_price)-1):\n # t = 0\n # while t < len(op_c_p_price) - 1:\n # if op_c_p_price[t]['XingQuan'] > op_c_p_price[t+1]['XingQuan']:\n # temp_d = op_c_p_price[t]\n # op_c_p_price[t] = op_c_p_price[t+1]\n # op_c_p_price[t+1] = temp_d\n # t = t+1\n # print(op_c_p_price)\n op_c_p_price = sorted(op_c_p_price,key = lambda x: x['XingQuan'])\n # print(op_c_p_price)\n date_list = list(date_list)\n date_list.sort() #> ['1908', '1909', '1912', '2003']\n dangyue_c_p_price = list()\n xiayue_c_p_price = list()\n xiaji_c_p_price = list()\n geji_c_p_price = list()\n for i in range(len(op_c_p_price)):\n if op_c_p_price[i]['Name'].startswith(date_list[0]):\n dangyue_c_p_price.append(op_c_p_price[i])\n elif op_c_p_price[i]['Name'].startswith(date_list[1]):\n xiayue_c_p_price.append(op_c_p_price[i])\n elif op_c_p_price[i]['Name'].startswith(date_list[2]):\n xiaji_c_p_price.append(op_c_p_price[i])\n elif op_c_p_price[i]['Name'].startswith(date_list[3]):\n geji_c_p_price.append(op_c_p_price[i])\n # print(dangyue_c_p_price)\n # print(xiayue_c_p_price)\n # print(xiaji_c_p_price)\n # print(geji_c_p_price)\n pe_p = pe + 500\n pe_n = pe - 500\n p_run = [pe_n,pe,pe_p]\n for i, p_runj in enumerate(p_run):\n if len(dangyue_c_p_price) != 0 :\n self.vcompute(dangyue_c_p_price, dangyue_c_p_price[0]['Name'][:4],p_runj,cur_ts,i,conn_w)\n if len(xiayue_c_p_price) != 0:\n self.vcompute(xiayue_c_p_price, xiayue_c_p_price[0]['Name'][:4],p_runj,cur_ts,i,conn_w)\n if len(xiaji_c_p_price) != 0:\n self.vcompute(xiaji_c_p_price,xiaji_c_p_price[0]['Name'][:4],p_runj,cur_ts,i,conn_w)\n if len(geji_c_p_price) != 0:\n self.vcompute(geji_c_p_price,geji_c_p_price[0]['Name'][:4],p_runj,cur_ts,i,conn_w)\n conn_w.execute()\n # for i in range(20):\n # self.a5s.run(cur_ts,conn_w)\n # self.a5s.run(cur_ts,conn_w)\n # self.a10s.run(cur_ts,conn_w)\n # self.a15s.run(cur_ts,conn_w)\n # self.a30s.run(cur_ts,conn_w)\n # self.a1m.run(cur_ts,conn_w)\n # self.a3m.run(cur_ts,conn_w)\n # self.a5m.run(cur_ts,conn_w)\n # self.a10m.run(cur_ts,conn_w)\n # self.a15m.run(cur_ts,conn_w)\n # self.a30m.run(cur_ts,conn_w)\n # self.a1h.run(cur_ts,conn_w)\n # self.a2h.run(cur_ts,conn_w)\n # self.a4h.run(cur_ts,conn_w)\n # self.a1d.run(cur_ts,conn_w)\n\n def start(self):\n print(\"上班啦\")\n print(\"上午:\")\n self.operate([self.f_starttime,self.f_endtime],57600)\n print(\"下午:\")\n self.operate([self.s_starttime,self.s_endtime],45000)\n print(\"下班啦\")\n\n def operate(self, interval:list, last_sec:int):\n\n start_time = interval[0]\n end_time = interval[1]\n if time.time() > end_time:\n return\n ctime = time.time()\n if ctime < start_time:\n print(\"等待开盘\")\n conn_w = self.conn_w\n # self.a5s.initalYesData(conn_w,last_sec)\n # self.a10s.initalYesData(conn_w,last_sec)\n # self.a15s.initalYesData(conn_w,last_sec)\n # self.a30s.initalYesData(conn_w,last_sec)\n # self.a1m.initalYesData(conn_w,last_sec)\n # self.a3m.initalYesData(conn_w,last_sec)\n # self.a5m.initalYesData(conn_w,last_sec)\n # self.a10m.initalYesData(conn_w,last_sec)\n # self.a15m.initalYesData(conn_w,last_sec)\n # self.a30m.initalYesData(conn_w,last_sec)\n # self.a1h.initalYesData(conn_w,last_sec)\n # self.a2h.initalYesData(conn_w,last_sec)\n # self.a4h.initalYesData(conn_w,last_sec)\n # self.a1d.initalYesData(conn_w,last_sec)\n interval = int(start_time) - time.time()\n if interval > 0:\n time.sleep(interval)\n self.run()\n\n ctime = time.time()\n if ctime >= start_time and ctime <= end_time:\n time.sleep(int(time.time())+1 - time.time())\n while time.time() < end_time:\n self.run()\n time1 = time.time()\n time.sleep(int(time.time())+1 - time.time())\n if int(time.time()) - int(time1) != 1:\n print(\"miss one\")\n self.run()\n\n\n\ndef main():\n # print(type(time.localtime().tm_mon),time.localtime().tm_year,time.localtime().tm_mday)\n t = PeriodAPP([\"09:30:00\",\"11:30:00\"],[\"13:02:00\",\"16:00:00\"])\n t.start()\n # time.sleep(10)\n # t.join()\n # print(5)\n\nif __name__=='__main__':\n main()\n\n","sub_path":"src/RealTimeData/testNewThread.py","file_name":"testNewThread.py","file_ext":"py","file_size_in_byte":31615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"325351483","text":"from multiprocessing import Process\nimport time\n\nclass SubProcess(Process):\n def __init__(self, name):\n Process.__init__(self)\n self.name = name\n \n def run(self):\n print(f'[sub] {self.name} start')\n time.sleep(5)\n print(f'[sub] {self.name} end')\n \nif __name__ == '__main__':\n print('[main] start')\n p = SubProcess(name='start coding')\n p.start()\n time.sleep(1)\n ## process alive check\n if p.is_alive():\n p.terminate()\n \n print('[main] end')","sub_path":"multi_processing_03.py","file_name":"multi_processing_03.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"525807059","text":"from __future__ import unicode_literals\nfrom rest_framework.pagination import PageNumberPagination, CursorPagination\nfrom collections import OrderedDict\nfrom django.core.paginator import InvalidPage\nfrom django.utils import six\nfrom rest_framework.exceptions import NotFound\nfrom rest_framework.response import Response\n\nclass InfinitePagination(CursorPagination):\n ordering = 'action_time'\n\nclass InfiniteScroll(PageNumberPagination):\n \"\"\"\n Infinite scroll pagination that takes the pk of the\n last returned item as a query parameter. For example:\n http://api.example.org/accounts/?last=4\n \"\"\"\n\n # Client can control the page using this query parameter.\n last_item_query_param = 'last'\n\n def paginate_queryset(self, queryset, request, view=None):\n \"\"\"\n Paginate a queryset if required, either returning a\n page object, or `None` if pagination is not configured for this view.\n \"\"\"\n page_size = self.get_page_size(request)\n if not page_size:\n return None\n column = view.infinite_scroll_column\n last = request.query_params.get(self.last_item_query_param, 1)\n filter_args = {\"%s_gt\" % column: last}\n queryset = queryset.filter(**filter_args)\n\n paginator = self.django_paginator_class(queryset, page_size)\n try:\n self.page = paginator.page(1)\n except InvalidPage as exc:\n msg = self.invalid_page_message.format(\n page_number=1, message=six.text_type(exc)\n )\n raise NotFound(msg)\n\n if paginator.num_pages > 1 and self.template is not None:\n # The browsable API should display pagination controls.\n self.display_page_controls = True\n\n self.request = request\n return list(self.page)\n\n def get_paginated_response(self, data):\n return Response(OrderedDict([\n ('count', self.page.paginator.count),\n ('next', self.get_next_link()),\n ('previous', self.get_previous_link()),\n ('results', data)\n ]))","sub_path":"pagination.py","file_name":"pagination.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"294731307","text":"# external dependencies\nfrom filelock import FileLock\n\n# built-in modules\nimport json\nimport logging\nimport sys\nimport os\nimport time\n\nclass CommandModule:\n \"\"\"\n Provides communication between CV and FW to send data and instructions via JSON files\n\n ...\n\n Attributes\n ----------\n __pogiData : dict\n dictionary of plane-out ground-in (POGI) data to be read from the POGI json file\n __pigoData : dict\n dictionary of plane-in ground-out (PIGO) data to be written to the PIGO json file\n pogiFileDirectory : str\n string containing directory to POGI file\n pigoFileDirectory : str\n string containing directory to PIGO file\n __pogiLock : filelock.FileLock\n FileLock used to lock the POGI file when being read\n __pigoLock : filelock.FileLock\n FileLock used to lock the PIGO file when being written\n __logger : logging.Logger\n Logger for outputing log messages\n\n note: pogiData and pigoData are currently specified in https://docs.google.com/document/d/1j7zZJAirZ91-UeNFV-kRFMhTaT8Swr9J8PcyvD0fPpo/edit\n\n\n Methods\n -------\n __init__(pogiFileDirectory=\"\", pigoFileDirectory=\"\")\n __read_from_pogi_file()\n __write_to_pigo_file()\n __is_null(value)\n\n get_error_code() -> int\n get_current_altitude() -> int\n get_current_airspeed() -> int\n get_is_landed() -> float\n get_euler_angles_of_camera() -> dict\n get_euler_angles_of_plane() -> dict\n get_gps_coordinates() -> dict\n\n set_gps_coordinates(gpsCoordinates: dict)\n set_ground_commands(groundCommands: dict)\n set_gimbal_commands(gimbalCommands: dict)\n set_begin_landing(beginLanding: bool)\n set_begin_takeoff(beginTakeoff: bool)\n set_disconnect_autopilot(disconnectAutoPilot: bool)\n\n @property pogiDirectory()\n @pogiDirectory.setter pogiDirectory(pogiFileDirectory: str)\n @property pigoDirectory()\n @pigoDirectory.setter pigoDirectory(pigoFileDirectory: str)\n \"\"\"\n\n def __init__(self, pogiFileDirectory: str, pigoFileDirectory: str):\n \"\"\"\n Initializes POGI & PIGO empty dictionaries, file directories, and file locks, and logger\n\n Parameters\n ----------\n pogiFileDirectory: str\n String of POGI file directory\n pigoFileDirectory: str\n String of POGI file directory\n \"\"\"\n self.__logger = logging.getLogger()\n self.__pogiData = dict()\n self.__pigoData = dict()\n self.pogiFileDirectory = pogiFileDirectory\n self.pigoFileDirectory = pigoFileDirectory\n self.__pogiLock = FileLock(pogiFileDirectory + \".lock\")\n self.__pigoLock = FileLock(pigoFileDirectory + \".lock\")\n\n def __read_from_pogi_file(self):\n \"\"\"\n Decodes JSON data from pogiFileDirectory JSON file and stores it in pogiData dictionary\n \"\"\"\n try:\n with self.__pogiLock, open(self.pogiFileDirectory, \"r\") as pogiFile:\n self.__pogiData = json.load(pogiFile)\n except json.decoder.JSONDecodeError:\n raise json.decoder.JSONDecodeError(\"The given POGI file has no data to read\")\n\n def __write_to_pigo_file(self):\n \"\"\"\n Encodes pigoData dictionary as JSON and stores it in pigoFileDirectory JSON file\n \"\"\"\n if not bool(self.__pigoData):\n raise ValueError(\"The current PIGO data dictionary is empty\")\n with self.__pigoLock, open(self.pigoFileDirectory, \"w\") as pigoFile:\n json.dump(self.__pigoData, pigoFile, ensure_ascii=False, indent=4, sort_keys=True)\n\n def get_error_code(self) -> int:\n \"\"\"\n Returns the error code from the POGI file\n\n Returns\n -------\n int:\n Error code\n \"\"\"\n self.__read_from_pogi_file()\n errorCode = self.__pogiData[\"errorCode\"]\n\n if errorCode is None:\n raise ValueError(\"errorCode not found in the POGI json file\")\n if type(errorCode) is not int:\n raise TypeError(\"errorCode found in POGI file is not an int\")\n \n return errorCode\n\n def get_current_altitude(self) -> int:\n \"\"\"\n Returns the current altitude from the POGI file\n\n Returns\n -------\n int:\n Current altitude of the plane\n \"\"\"\n self.__read_from_pogi_file()\n currentAltitude = self.__pogiData[\"currentAltitude\"]\n\n if currentAltitude is None:\n raise ValueError(\"currentAltitude not found in the POGI json file. Exiting...\")\n if type(currentAltitude) is not int:\n raise TypeError(\"currentAltitude in the POGI file was not an int. Exiting...\")\n\n return currentAltitude\n\n def get_current_airspeed(self) -> int:\n \"\"\"\n Returns the current airspeed from the POGI file\n\n Returns\n -------\n int:\n Current airspeed of the plane\n \"\"\"\n self.__read_from_pogi_file()\n currentAirspeed = self.__pogiData[\"currentAirspeed\"]\n\n if currentAirspeed is None:\n raise ValueError(\"currentAirspeed not found in the POGI json file. Exiting...\")\n if type(currentAirspeed) is not int:\n raise TypeError(\"currentAirspeed in the POGI file was not an int. Exiting...\")\n\n return currentAirspeed\n\n def get_is_landed(self) -> bool:\n \"\"\"\n Returns if the plane has landed from the POGI file\n\n Returns\n -------\n bool:\n True if plane landed, else False\n \"\"\"\n self.__read_from_pogi_file()\n isLanded = self.__pogiData[\"isLanded\"]\n\n if isLanded is None:\n raise ValueError(\"isLanded not found in the POGI json file. Exiting...\")\n if type(isLanded) is not bool:\n raise TypeError(\"isLanded in the POGI file was not an int. Exiting...\")\n\n return isLanded\n\n def get_euler_angles_of_camera(self) -> dict:\n \"\"\"\n Returns the euler coordinates of the camera on the plane from the POGI file\n\n Returns\n -------\n dict:\n Returns a dictionary that contains a set of three euler coordinates with names z, y, x\n \"\"\"\n self.__read_from_pogi_file()\n eulerAnglesOfCamera = self.__pogiData[\"eulerAnglesOfCamera\"]\n\n if eulerAnglesOfCamera is None:\n raise ValueError(\"eulerAnglesOfCamera not found in the POGI json file. Exiting...\")\n if type(eulerAnglesOfCamera) is not dict:\n raise TypeError(\"eulerAnglesOfCamera in the POGI file was not a float. Exiting...\")\n for key in (\"z\", \"y\", \"x\"):\n if key not in eulerAnglesOfCamera.keys():\n raise KeyError(\"{} key not found in eulerAnglesOfCamera\".format(key))\n for key in (\"z\", \"y\", \"x\"):\n if eulerAnglesOfCamera[key] is None:\n raise ValueError(\"{} in eulerAnglesOfCamera is null\".format(key))\n for key in (\"z\", \"y\", \"x\"):\n if type(eulerAnglesOfCamera[key]) is not float:\n raise TypeError(\"{} in eulerAnglesOfCamera must be a float\".format(key))\n\n return eulerAnglesOfCamera\n\n def get_euler_angles_of_plane(self) -> dict:\n \"\"\"\n Returns the euler coordinates of the plane itself from the POGI file\n\n Returns\n -------\n dict:\n Returns a dictionary that contains a set of three euler coordinates with names z, y, x\n \"\"\"\n self.__read_from_pogi_file()\n eulerAnglesOfPlane = self.__pogiData[\"eulerAnglesOfPlane\"]\n\n if eulerAnglesOfPlane is None:\n raise ValueError(\"eulerAnglesOfPlane not found in the POGI json file. Exiting...\")\n if type(eulerAnglesOfPlane) is not dict:\n raise TypeError(\"eulerAnglesOfPlane in the POGI file was not a float. Exiting...\")\n for key in (\"z\", \"y\", \"x\"):\n if key not in eulerAnglesOfPlane.keys():\n raise KeyError(\"{} key not found in eulerAnglesOfPlane\".format(key))\n for key in (\"z\", \"y\", \"x\"):\n if eulerAnglesOfPlane[key] is None:\n raise ValueError(\"{} in eulerAnglesOfPlane is null\".format(key))\n for key in (\"z\", \"y\", \"x\"):\n if type(eulerAnglesOfPlane[key]) is not float:\n raise TypeError(\"{} in eulerAnglesOfPlane must be a float\".format(key))\n\n return eulerAnglesOfPlane\n\n def get_gps_coordinates(self) -> dict:\n \"\"\"\n Returns the gps coordinates of the plane from the POGI file\n\n Returns\n -------\n dict:\n Returns a dictionary that contains GPS coordinate data with latitude, longitude, and altitude\n \"\"\"\n self.__read_from_pogi_file()\n gpsCoordinates = self.__pogiData[\"gpsCoordinates\"]\n\n if gpsCoordinates is None:\n raise ValueError(\"gpsCoordinates not found in the POGI json file. Exiting...\")\n if type(gpsCoordinates) is not dict:\n raise TypeError(\"gpsCoordinates in the POGI file was not a float. Exiting...\")\n for key in (\"latitude\", \"longitude\", \"altitude\"):\n if key not in gpsCoordinates.keys():\n raise KeyError(\"{} key not found in gpsCoordinates\".format(key))\n for key in (\"latitude\", \"longitude\", \"altitude\"):\n if gpsCoordinates[key] is None:\n raise ValueError(\"{} in gpsCoordinates is null\".format(key))\n for key in (\"latitude\", \"longitude\", \"altitude\"):\n if type(gpsCoordinates[key]) is not float:\n raise TypeError(\"{} in gpsCoordinates must be a float\".format(key))\n\n return gpsCoordinates\n\n def set_gps_coordinates(self, gpsCoordinates: dict):\n \"\"\"\n Write GPS coordinates to PIGO JSON file\n\n Paramaters\n ----------\n gpsCoordinates: dict\n Dictionary that contains GPS coordinate data with latitude, longitude, and altitude\n \"\"\"\n if gpsCoordinates is None:\n raise ValueError(\"gpsCoordinates must be a dict and not None.\")\n if type(gpsCoordinates) is not dict:\n raise TypeError(\"gpsCoordinates must be a dict and not {}\".format(type(gpsCoordinates)))\n for attribute in (\"latitude\", \"longitude\", \"altitude\"):\n if attribute not in gpsCoordinates.keys():\n raise KeyError(\"gpsCoordinates must contain {} key\".format(attribute))\n for key in gpsCoordinates.keys():\n if type(gpsCoordinates[key]) is not float:\n raise TypeError(\"gpsCoordinates {} key must be a float\".format(key))\n\n self.__pigoData.update({\"gpsCoordinates\" : gpsCoordinates})\n self.__write_to_pigo_file()\n\n def set_ground_commands(self, groundCommands: dict):\n \"\"\"\n Write ground commands to PIGO JSON file\n\n Paramaters\n ----------\n groundCommands: dict\n Dictionary that contains ground commands with heading and latestDistance\n \"\"\"\n if groundCommands is None:\n raise ValueError(\"groundCommands must be a dict and not None.\")\n if type(groundCommands) is not dict:\n raise TypeError(\"groundCommands must be a dict and not {}\".format(type(groundCommands)))\n for key in (\"heading\", \"latestDistance\"):\n if key not in groundCommands.keys():\n raise KeyError(\"groundCommands must contain {} key\".format(key))\n for key in (\"heading\", \"latestDistance\"):\n if type(groundCommands[key]) is not float:\n raise TypeError(\"groundCommands {} key must be a float\".format(key))\n\n self.__pigoData.update({\"groundCommands\" : groundCommands})\n self.__write_to_pigo_file()\n\n def set_gimbal_commands(self, gimbalCommands: dict):\n \"\"\"\n Write gimbal commands to PIGO JSON file\n\n Paramaters\n ----------\n gimbalCommands: dict\n Dictionary that contains gimbal commands with pitch and yaw angles named y and z respectively\n \"\"\"\n if gimbalCommands is None:\n raise ValueError(\"gimbalCommands must be a dict and not None.\")\n if type(gimbalCommands) is not dict:\n raise TypeError(\"gimbalCommands must be a dict and not {}\".format(type(gimbalCommands)))\n for key in (\"z\", \"y\"):\n if key not in gimbalCommands.keys():\n raise KeyError(\"gimbalCommands must contain {} key\".format(key))\n for key in (\"z\", \"y\"):\n if type(gimbalCommands[key]) is not float:\n raise TypeError(\"gimbalCommands {} key must be a float\".format(key))\n\n self.__pigoData.update({\"gimbalCommands\" : gimbalCommands})\n self.__write_to_pigo_file()\n\n def set_begin_landing(self, beginLanding: bool):\n \"\"\"\n Write begin landing command to PIGO JSON file\n\n Paramaters\n ----------\n beginLanding: bool\n Boolean containing whether or not to initiate landing sequence\n \"\"\"\n if beginLanding is None:\n raise ValueError(\"beginLanding must be a bool and not None.\")\n if type(beginLanding) is not bool:\n raise TypeError(\"beginLanding must be a bool and not {}\".format(type(beginLanding)))\n\n self.__pigoData.update({\"beginLanding\" : beginLanding})\n self.__write_to_pigo_file()\n\n def set_begin_takeoff(self, beginTakeoff: bool):\n \"\"\"\n Write begin takeoff command to PIGO JSON file\n\n Paramaters\n ----------\n beginTakeoff: bool\n Boolean containing whether or not to initiate takeoff sequence\n \"\"\"\n if beginTakeoff is None:\n raise ValueError(\"beginTakeoff must be a bool and not None.\")\n if type(beginTakeoff) is not bool:\n raise TypeError(\"beginTakeoff must be a bool and not {}\".format(type(beginTakeoff)))\n\n self.__pigoData.update({\"beginTakeoff\" : beginTakeoff})\n self.__write_to_pigo_file()\n\n def set_disconnect_autopilot(self, disconnectAutoPilot: bool):\n \"\"\"\n Write disconnect autopilot to PIGO JSON file\n\n Paramaters\n ----------\n disconnectAutoPilot: bool\n Boolean containing whether or not to disconnect auto pilot\n \"\"\"\n if disconnectAutoPilot is None:\n raise ValueError(\"disconnectAutopilot must be a bool and not None.\")\n if type(disconnectAutoPilot) is not bool:\n raise TypeError(\"disconnectAutopilot must be a bool and not {}\".format(type(disconnectAutoPilot)))\n\n self.__pigoData.update({\"disconnectAutoPilot\" : disconnectAutoPilot})\n self.__write_to_pigo_file()\n\n @property\n def pigoFileDirectory(self):\n \"\"\"\n Return PIGO JSON file directory\n\n Returns\n ----------\n __pigoFileDirectory: str\n Contains directory to PIGO JSON file\n \"\"\"\n return self.__pigoFileDirectory\n\n @pigoFileDirectory.setter\n def pigoFileDirectory(self, pigoFileDirectory: str):\n \"\"\"\n Sets PIGO JSON file directory\n\n Parameters\n ----------\n pigoFileDirectory: str\n Contains directory to PIGO JSON file\n \"\"\"\n if pigoFileDirectory is None:\n raise ValueError(\"PIGO File Directory must be a str and not None.\")\n if type(pigoFileDirectory) is not str:\n raise TypeError(\"PIGO File Directory must be a str and not {}\".format(type(pigoFileDirectory)))\n if not os.path.isfile(pigoFileDirectory):\n raise FileNotFoundError(\"The PIGO file directory must be a valid file\")\n if not pigoFileDirectory.endswith(\".json\"):\n raise ValueError(\"The PIGO file directory must have a '.json' file extension\")\n self.__pigoFileDirectory = pigoFileDirectory\n\n @property\n def pogiFileDirectory(self):\n \"\"\"\n Return POGI JSON file directory\n\n Returns\n ----------\n __pogiFileDirectory: str\n Contains directory to POGI JSON file\n \"\"\"\n return self.__pogiFileDirectory\n\n @pogiFileDirectory.setter\n def pogiFileDirectory(self, pogiFileDirectory: str):\n \"\"\"\n Sets POGI JSON file directory\n\n Parameters\n ----------\n pogiFileDirectory: str\n Contains directory to POGI JSON file\n \"\"\"\n if pogiFileDirectory is None:\n raise ValueError(\"POGI File Directory must be a str and not None.\")\n if type(pogiFileDirectory) is not str:\n raise TypeError(\"POGI File Directory must be a str and not {}\".format(type(pogiFileDirectory)))\n if not os.path.isfile(pogiFileDirectory):\n raise FileNotFoundError(\"The POGI file directory must be a valid file\")\n if not pogiFileDirectory.endswith(\".json\"):\n raise ValueError(\"The POGI file directory must have a '.json' file extension\")\n self.__pogiFileDirectory = pogiFileDirectory","sub_path":"modules/commandModule/commandModule.py","file_name":"commandModule.py","file_ext":"py","file_size_in_byte":16850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"25924834","text":"#!/usr/bin/env python\n# detect_EDK-means.py\n# The python script is used to cluster event time series using Euclidean Distance K-means.\n# @Author : wwt\n# @Date : 2018-1 2-20\n\nimport numpy as np\nfrom common import common_funcs\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plot\nimport sys\nimport yaml\n\n\n\ndef fit(train_file='data_std.txt', config='parameters.yaml', model_file='', slotting=True, plotting=False):\n \"\"\"\n # train the model(s) on the given data set, within each time slot if enabled\n # the model will be saved to local disk as specified by the 'model_save_path' in cfg\n :param train_file: contains data to fit\n :param config: configuration file path\n :param model_file: specified model file to store pre-trained model(s), save to the one specified in cfg if not given\n :param slotting: if True then load slotting configs from cfg(default = parameters.yaml), no slotting if False\n :param plotting: if True then plot the decisions on training data, no plotting if False\n :return: decision functions on training data\n \"\"\"\n print(\"INFO@detect_EDK-means: loading cfg file...\")\n # load yaml config file\n with open(config, 'r') as cfg:\n params = yaml.load(cfg)\n\n ''' load input data config '''\n headlines = params['headlines']\n num_channels = params['num_channels']\n channel_fmt_list_py3 = [] # data format\n channel_fmt_list_py2 = []\n for ch in params['data_format_py3']:\n channel_fmt_list_py3.append(tuple(ch))\n for ch in params['data_format_py2']:\n channel_fmt_list_py2.append(tuple(ch))\n\n if train_file == '': # use file path specified in config if not given as an argument\n train_file = params['data_file']\n data_rescaling = params['rescale']\n JZLogFrame_type = np.dtype(channel_fmt_list_py3)\n if sys.version_info[0] < 3: # for py2\n JZLogFrame_type = np.dtype(channel_fmt_list_py2)\n\n # the range of data to learn\n start_hour_shift = 0\n training_data_range_limit = params['training_data_range_limit']\n\n ''' load slotting config '''\n slot_size = params['slot_size']\n if slot_size == -1 or not slotting:\n slot_size = 24\n num_models = 24 / slot_size if 24 % slot_size == 0 else 24 / slot_size + 1\n\n ''' load model params '''\n model_name = params['model_name']\n n_cls = params['num_clusters']\n decisions_save_path = params['decision_save_path']\n model_save_path = model_file if model_file else params['model_save_path']\n\n # read data from the cleaned, normalized/standardized data set\n train_data = common_funcs.read_data(train_file,\n skips=headlines,\n cols=tuple(range(num_channels + 1)),\n datatype=JZLogFrame_type)\n # determine left bound and right bound\n if training_data_range_limit == [-1, -1]: # default setting in config file\n training_data_range_limit = [0, len(train_data)]\n else:\n training_data_range_limit[0] = max(training_data_range_limit[0], 0) # left bound\n training_data_range_limit[1] = min(training_data_range_limit[1], len(train_data)) # right bound\n start_date = train_data[training_data_range_limit[0]][0]\n train_data = train_data[training_data_range_limit[0]: training_data_range_limit[1]]\n\n #print(train_data)\n print(\"INFO@detect_EDK-means: Number of slots = %d\" % num_models)\n print(\"INFO@detect_EDK-means: Model training in each slot starts...\")\n\n # slotting\n slots = common_funcs.get_fixed_slot_frame_sets(train_data, slot_size, True, 'date')\n # training_set_decisions set, should be temporally sequential from start_hour_shift to end_h\n glob_decisions_map = list(range(training_data_range_limit[0], training_data_range_limit[1]))\n model_set = {}\n\n # fit/train model one by one for each slot\n model_id = 0\n for slot in slots:\n time_seq = np.array(slot)[:, 0].tolist() # get timestamp sequence and transform it to hour-index sequence\n for k in range(len(time_seq)):\n time_seq[k] = common_funcs.count_hours_from_str(time_seq[k]) # convert stamp to absolute time\n time_seq[k] -= common_funcs.count_hours_from_str(start_date) # further trans to hour index starting from 0\n\n kmeans_model = KMeans(n_clusters=n_cls)\n kmeans_model.fit(np.delete(np.array(slot), 0, 1)) # feed timestamp-stripped slot data\n\n print(\"INFO@EDK-means: EDK-means cluster centers of MODEL #%d:\" % model_id)\n for c in kmeans_model.cluster_centers_:\n print(c)\n # cache each slot-wise model\n model_set['EDK-means model#'+str(model_id)+' centers'] = kmeans_model.cluster_centers_.tolist()\n print(\"INFO@EDK-means: model id%s stored.\" % id(kmeans_model))\n model_id += 1\n\n # force minor class label to be '-1', and positive label '1'\n local_decisions_map = kmeans_model.labels_.tolist() # 0 or 1 originally\n zeroes = local_decisions_map.count(0)\n ones = local_decisions_map.count(1)\n minor_class = 0 if zeroes < ones else 1\n for k in range(len(local_decisions_map)):\n local_decisions_map[k] = -1 if local_decisions_map[k] == minor_class else 1\n\n # mapping training_set_decisions of this slot-local model to the global decision map\n for idx in range(len(time_seq)):\n glob_decisions_map[time_seq[idx]] = local_decisions_map[idx] # store training_set_decisions\n\n # dump models to disk\n print(\"INFO@EDK-means: Dumping models into %s\" % model_save_path)\n with open(model_save_path, 'w+') as msp:\n yaml.dump(model_set, msp)\n\n print(\"INFO@EDK-means: pos_count=%d, neg_count=%d\" % (glob_decisions_map.count(1), glob_decisions_map.count(-1)))\n\n # save training data decisions to disk\n print(\"INFO@EDK-means: Dumping decisions of training data into %s\" % decisions_save_path)\n decisions_with_stamps = np.array([train_data, glob_decisions_map]).T\n common_funcs.save_data(decisions_save_path, decisions_with_stamps, linenum=False)\n\n # plot decisions on training data\n if plotting:\n plot.scatter(range(training_data_range_limit[0], training_data_range_limit[1]), glob_decisions_map, s=1 ** 2)\n plot.hlines(y=0, xmin=training_data_range_limit[0], xmax=training_data_range_limit[1], linestyles='dashed')\n plot.title(model_name + \"\\ndecision map (+1/-1 denotes normality/anomaly)\")\n plot.show()\n\n return decisions_with_stamps\n\n\ndef detect(test_file='', config='parameters.yaml', model_file='saved_model.yaml', plotting=True):\n \"\"\"\n # Detect anomalies in the specified data from a file using pre-trained models\n :param test_file: data file containing test data in the format like:\n # time, event-crond, event-rsyslogd, event-session, event-sshd, event-su\n 2018-06-29-00, 0.147, -0.223, 0.571, -0.594, 1.298\n 2018-06-29-01, -0.215, -0.223, 0.696, -0.597, 1.443\n :param config: configuration file path, identical to the one used in training(fitting)\n :param model_file: model file containing pre-trained model(s)\n :param plotting: if True then plot the decisions on test data, no plotting if False\n :return: decisions on the test data\n \"\"\"\n print(\"INFO@detect_EDK-means: loading cfg file...\")\n # load yaml config file\n with open(config, 'r') as cfg:\n params = yaml.load(cfg)\n\n ''' load input data config '''\n headlines = params['headlines']\n num_channels = params['num_channels']\n channel_fmt_list_py3 = [] # data format\n channel_fmt_list_py2 = []\n for ch in params['data_format_py3']:\n channel_fmt_list_py3.append(tuple(ch))\n for ch in params['data_format_py2']:\n channel_fmt_list_py2.append(tuple(ch))\n\n if test_file == '': # use file path specified in config if not given as an argument\n test_file = params['data_file']\n data_rescaling = params['rescale']\n JZLogFrame_type = np.dtype(channel_fmt_list_py3)\n if sys.version_info[0] < 3: # for py2\n JZLogFrame_type = np.dtype(channel_fmt_list_py2)\n\n ''' load slotting config '''\n slot_size = params['slot_size']\n if slot_size == -1:\n slot_size = 24\n num_models = 24 / slot_size if 24 % slot_size == 0 else 24 / slot_size + 1\n\n ''' load model params '''\n model_name = params['model_name']\n n_cls = params['num_clusters']\n decisions_save_path = params['decision_save_path']\n model_save_path = params['model_save_path']\n\n test_data_range_lim = params['test_data_range_limit']\n # read data from the cleaned, normalized/standardized data set\n test_data = common_funcs.read_data(test_file,\n skips=headlines,\n cols=tuple(range(num_channels + 1)),\n datatype=JZLogFrame_type)\n # determine left bound and right bound\n if test_data_range_lim == [-1, -1]: # default setting in config file\n test_data_range_lim = [0, len(test_data)]\n else:\n test_data_range_lim[0] = max(test_data_range_lim[0], 0) # left bound\n test_data_range_lim[1] = min(test_data_range_lim[1], len(test_data)) # right bound\n start_date = test_data[test_data_range_lim[0]][0]\n end_date = test_data[test_data_range_lim[1] - 1][0]\n test_data = test_data[test_data_range_lim[0]: test_data_range_lim[1]]\n\n\n # load model(s) from file\n print(\"INFO@detect_EDK-means: loading model(s)...\")\n with open(model_file) as f:\n models = yaml.load(f)\n print(\"INFO@detect_EDK-means: %d model(s) are loaded into memory...\" % len(models))\n\n # slotting\n slot_id = 0\n slots = common_funcs.get_fixed_slot_frame_sets(test_data, slot_size, True, 'date')\n glob_decisions_map = list(range(test_data_range_lim[0], test_data_range_lim[1])) # decisions map\n for slot in slots:\n time_seq = np.array(slot)[:, 0].tolist() # get timestamp sequence and transform it to hour-index sequence\n for k in range(len(time_seq)):\n time_seq[k] = common_funcs.count_hours_from_str(time_seq[k]) # convert stamp to absolute time\n time_seq[k] -= common_funcs.count_hours_from_str(start_date) # further trans to hour index starting from 0\n\n # load the corresponding slot-wise model\n kmeans_model = KMeans(n_clusters=n_cls)\n kmeans_model.cluster_centers_ = np.array(models['EDK-means model#' + str(slot_id) + ' centers'])\n\n # make decisions for test data in this slot\n local_decisions_map = kmeans_model.predict(np.delete(np.array(slot), 0, 1)).tolist() # timestamp stripped\n\n # force minor class label to be '-1', and positive label '1'\n zeroes = local_decisions_map.count(0)\n ones = local_decisions_map.count(1)\n minor_class = 0 if zeroes < ones else 1\n for k in range(len(local_decisions_map)):\n local_decisions_map[k] = -1 if local_decisions_map[k] == minor_class else 1\n\n # mapping training_set_decisions of this slot-local model to the global decision map\n for idx in range(len(time_seq)):\n glob_decisions_map[time_seq[idx]] = local_decisions_map[idx] # store training_set_decisions\n\n # ready for the next slot\n slot_id += 1\n\n print(\"INFO@EDK-means: pos_count=%d, neg_count=%d\" % (glob_decisions_map.count(1), glob_decisions_map.count(-1)))\n\n # plot results\n if plotting:\n plot.scatter(range(test_data_range_lim[0], test_data_range_lim[1]), glob_decisions_map, s=1 ** 2)\n plot.hlines(y=0, xmin=test_data_range_lim[0], xmax=test_data_range_lim[1], linestyles='dashed')\n plot.title(model_name + \"\\ndecision map (+1/-1 denotes normality/anomaly)\")\n plot.xlabel('Timeline(hour)')\n plot.text(test_data_range_lim[0], -0.5, start_date, rotation=90)\n plot.text(test_data_range_lim[1], -0.5, end_date, rotation=90)\n plot.show()\n\n print(\"INFO@EDK-means: detection finished, decisions returned...\")\n return glob_decisions_map\n\n\ndef get_model_params(model_file='saved_model.yaml'):\n \"\"\"\n # return model parameters\n :param model_file: the file path where the model is saved\n :return: model parameters\n \"\"\"\n params = {}\n with open(model_file, 'r') as mf:\n models = yaml.load(mf)\n\n params['num_models(slots)'] = len(models)\n params['models'] = models\n\n return params\n\n### test examples\n#fit(train_file='data_std.txt', config='parameters.yaml', slotting=True, plotting=True)\n#print(detect(test_file='data_std.txt',config='parameters.yaml',model_file='saved_model.yaml',plotting=True))\n#print(get_model_params(model_file='saved_model.yaml'))\n","sub_path":"detect_algos/EDK-means/detect_EDK-means.py","file_name":"detect_EDK-means.py","file_ext":"py","file_size_in_byte":12702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"570837501","text":"import re\nimport time\nimport unicodedata\n\nfrom vocabulary import Vocabulary\n\n# TODO: Make it variable\nMAX_LENGTH = 10 # Maximum sentence length to consider\nMIN_COUNT = 3 # Minimum word count threshold for trimming\n\n\n# thanks to https://stackoverflow.com/a/518232/2809427\ndef unicode_to_ascii(s):\n\t\"\"\" Turn a Unicode string to plain ASCII \"\"\"\n\t# The normal form D (NFD) is also called canonical decomposition,\n\t# and translates each character into its decomposed form.\n\t#\n\t# NOTE: Even if two Unicode strings are standardized\n\t# and look the same for a human reader,\n\t# if one has combined characters and the other does not,\n\t# they may not be equal in a comparison.\n\t# That's why we normalize into D form in order to\n\t# be compliant with the comparison of the rest of the corpus\n\treturn ''.join(\n\t\tc for c in unicodedata.normalize('NFD', s)\n\t\tif unicodedata.category(c) != 'Mn'\n\t)\n\n\n# TODO: Decrypt this function\ndef normalize_string(s):\n\t\"\"\" Lowercase, trim, and remove non-letter characters \"\"\"\n\t# Lowercase, str -> list\n\ts = unicode_to_ascii(s.lower().strip())\n\t# Replace multi .!? into a simple punctuation\n\ts = re.sub(r\"([.!?])\", r\" \\1\", s)\n\ts = re.sub(r\"[^a-zA-Z.!?]+\", r\" \", s)\n\ts = re.sub(r\"\\s+\", r\" \", s).strip()\n\treturn s\n\n\n# TODO: Decrypt this function\ndef read_vocabs(datafile, corpus_name):\n\t\"\"\" Read query/response pairs and return a voc object \"\"\"\n\tst = time.time()\n\tprint(\"Reading lines & normalizing string...\")\n\t# Read the hole file and split into lines\n\twith open(datafile, \"r\", encoding=\"utf-8\") as f:\n\t\tlines = f.read().strip().split(\"\\n\")\n\t# Split every line into pairs and normalize\n\tpairs = [[normalize_string(s) for s in l.split(\"\\t\")] for l in lines]\n\t# Create Vocabulary w.r.t corpus\n\tvoc = Vocabulary(corpus_name)\n\tprint(\"Done! In {}\\n\".format(time.time() - st))\n\treturn voc, pairs\n\n\ndef filter_pair(p):\n\t\"\"\"\n\t\tReturns True if both sentences in a pair 'p'\n\t\tare under the MAX_LENGTH threshold\n\t\"\"\"\n\t# Input sequences need to preserve the last word for EOS token\n\treturn len(p[0].split(' ')) < MAX_LENGTH and len(p[1].split(' ')) < MAX_LENGTH\n\n\ndef filter_pairs(pairs):\n\t\"\"\" Filter multiple pairs using filter pair condition \"\"\"\n\treturn [pair for pair in pairs if filter_pair(pair)]\n\n\ndef _check_keep_sentence(vocab, sentence):\n\treturn not any([word not in vocab.word2index for word in sentence.split(' ')])\n\n\ndef trim_rare_words(vocab, pairs, threshold=MIN_COUNT):\n\tprint(\"Trimming sentences w.r.t rare words... Threshold: {}\".format(threshold))\n\t# Trim words seen under the MIN_COUNT threshold from the vocabulary\n\tvocab.trim(threshold)\n\t# Filter out pairs with trimmed words\n\tkept_pairs = []\n\tfor pair in pairs:\n\t\t# Check input sentence\n\t\tkeep_in_sentence = _check_keep_sentence(vocab, pair[0])\n\t\tif not keep_in_sentence:\n\t\t\tcontinue\n\t\t# Check output sentence\n\t\tkeep_out_sentence = _check_keep_sentence(vocab, pair[1])\n\t\tif not keep_out_sentence:\n\t\t\tcontinue\n\t\t# Only keep sentence pairs that do not contain\n\t\t# trimmed words in their input or output sentence\n\t\tkept_pairs.append(pair)\n\tprint(\"Trimmed sentences pairs {} -> {}, keep {:.4f}% of total\".format(len(pairs), len(kept_pairs),\n\t len(kept_pairs) / len(pairs)))\n\treturn kept_pairs\n\n\ndef load_prepare_data(corpus_name, datafile):\n\tst = time.time()\n\tprint(\"Start preparing training data...\")\n\tvoc, pairs = read_vocabs(datafile, corpus_name)\n\tprint(\"Read {!s} sentence pairs\".format(len(pairs)))\n\tpairs = filter_pairs(pairs)\n\tprint(\"Trimmed/filtered to {!s} sentence pairs\".format(len(pairs)))\n\tprint(\"Creating vocab...\")\n\tfor pair in pairs:\n\t\tvoc.add_sentence(pair[0])\n\t\tvoc.add_sentence(pair[1])\n\tprint(\"New vocab created, counted words: \", voc.number_of_words)\n\tprint(\"Done! In {}\\n\".format(time.time() - st))\n\treturn voc, pairs\n","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"604702158","text":"from Tkinter import *\r\nfrom learnOrPlay import learnOrPlay\r\nimport csv\r\n\r\nclass Level(Frame):\r\n def __init__(self, parent, controller):\r\n Frame.__init__(self, parent)\r\n\r\n # Add the level to the second row of the CSV file\r\n def addCSV1():\r\n myFile = open(\"game.csv\", \"a\")\r\n\r\n with myFile:\r\n writer = csv.writer(myFile)\r\n writer.writerows([[\"1\"]])\r\n\r\n myFile.close()\r\n\r\n def addCSV2():\r\n myFile = open(\"game.csv\", \"a\")\r\n\r\n with myFile:\r\n writer = csv.writer(myFile)\r\n writer.writerows([[\"2\"]])\r\n\r\n myFile.close()\r\n\r\n def addCSV3():\r\n myFile = open(\"game.csv\", \"a\")\r\n\r\n with myFile:\r\n writer = csv.writer(myFile)\r\n writer.writerows([[\"3\"]])\r\n\r\n myFile.close()\r\n\r\n def addCSV4():\r\n myFile = open(\"game.csv\", \"a\")\r\n\r\n with myFile:\r\n writer = csv.writer(myFile)\r\n writer.writerows([[\"4\"]])\r\n\r\n myFile.close()\r\n\r\n def addCSV5():\r\n myFile = open(\"game.csv\", \"a\")\r\n\r\n with myFile:\r\n writer = csv.writer(myFile)\r\n writer.writerows([[\"5\"]])\r\n\r\n myFile.close()\r\n\r\n\r\n # Widgets\r\n pickLabel = Label(self, text=\"Pick level:\")\r\n\r\n button1 = Button(self, text=\"Level 1\", command=lambda:addCSV1())\r\n button2 = Button(self, text=\"Level 2\", command=lambda:addCSV2())\r\n button3 = Button(self, text=\"Level 3\", command=lambda:addCSV3())\r\n button4 = Button(self, text=\"Level 4\", command=lambda:addCSV4())\r\n button5 = Button(self, text=\"Level 5\", command=lambda:addCSV5())\r\n\r\n cardOrGame = Button(self, text=\"Play or Cards\", command=lambda:controller.show_frame(learnOrPlay))\r\n categories = Button(self, text=\"Back to Categories\")\r\n\r\n # Organization\r\n pickLabel.pack(fill=X)\r\n\r\n button1.pack(fill=X)\r\n button2.pack(fill=X)\r\n button3.pack(fill=X)\r\n button4.pack(fill=X)\r\n button5.pack(fill=X)\r\n\r\n cardOrGame.pack(fill=X)\r\n categories.pack(fill=X)\r\n\r\n","sub_path":"interface/Level.py","file_name":"Level.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"485201467","text":"#Michael Silverstein\n#Boston University\n#BE 562 - Computational Biology\n#Naive Bayes Classifier\n\nimport cPickle as pickle\nimport pandas as pd\nimport numpy as np\nimport math\npd.options.mode.chained_assignment = None # default='warn'\n\n\ndef cov_mat_calc(data):\n #Calculates covariance matrix\n #|Input: Data BY CLASS\n #|Output: Dictionary of covariance matrix by class\n cov_matrices = {}\n for label in labels:\n d = data[label]\n #https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Estimation_of_parameters\n cov_matrices[label] = float(1)/len(d)*np.sum(np.array(np.dot(np.array([x-d.mean()]).T,np.array([x-d.mean()])))\n for x in np.array(d))\n return cov_matrices\n\ndef priors_calc(data):\n #Calculates priors based off of frequency in data (counting)\n labels_list = data['Labels'].tolist()\n total = len(labels_list)\n priors = {}\n for i in labels_list:\n priors[i] = priors.get(i,0)+1\n for k,v in priors.items():\n priors[k] = float(v)/total\n return priors\n\ndef class_parameterizer(data):\n #Calculates parameters (mean, cov) for each feature for each class\n #parameters = {'CLASS1' : [mean1 ,cov1],...,'CLASS_N' : [mean_N, cov_N]}\n cov_matrices = cov_mat_calc(data)\n parameters = {}\n for label in labels:\n parameters[label] = [np.array(data[label].mean()),cov_matrices[label]]\n return parameters\n\ndef multi_variate(x,u,cov):\n #Calculate P(Class | X, parameters)\n # https://en.wikipedia.org/wiki/Multivariate_normal_distribution\n #| u = mean, cov = covariance matrix\n #|f_x(x_1,...,x_k) = e^(-1/2 * (x-u).T * inv(cov) * (x-u))\n #| ------------------------------------\n #| sqrt([2*pi]^k*det(cov)))\n cov = np.matrix(cov)\n det_cov = np.linalg.det(cov)\n x_mu = np.matrix(x-u)\n numerator = math.exp(-0.5*x_mu*cov.I*x_mu.T)\n normalization = 1/(math.sqrt(math.pow(2*math.pi,len(x))*det_cov))\n return numerator*normalization\n\ndef naivebayes(data,parameters,priors,fuzzy=True):\n # G(x) = argmax(P(X_i|Class,params)P(X_i))\n predicted_labels = []\n for x in data:\n probs_by_class = {}\n for label in labels:\n probs_by_class[label] = multi_variate(x,parameters[label][0],parameters[label][1])*priors[label]\n if fuzzy:\n norm_probs = [probs_by_class[label]/sum(probs_by_class.values()) for label in labels]\n predicted_labels.append(np.random.choice(labels,p=norm_probs))\n else:\n predicted_labels.append(max(probs_by_class,key=probs_by_class.get))\n return predicted_labels\n\ndef accuracy_calculator(data):\n correct = data['Labels'].tolist()\n predictions = data['Predictions'].tolist()\n total = len(correct)\n count = 0\n for i in range(len(correct)):\n if correct[i] == predictions[i]:\n count += 1\n return float(count)/total\n","sub_path":"Mutliclass_naivebayes.py","file_name":"Mutliclass_naivebayes.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"329924815","text":"import time\n\nfrom pydruid.utils.aggregators import doublemax, doublemin\n\nfrom db.druid.aggregations.query_dependent_aggregation import QueryDependentAggregation\nfrom db.druid.calculations.calculation_merger import CalculationMerger\nfrom db.druid.calculations.simple_calculation import TimeCalculation\nfrom db.druid.query_builder import GroupByQueryBuilder\nfrom db.druid.calculations.unique_calculations import ThetaSketchUniqueCountCalculation\nfrom db.druid.util import build_query_filter_from_aggregations\nfrom web.server.query.visualizations.aqt.aqt_base import AQTBase\n\nMILLISECONDS_IN_DAY = 24 * 60 * 60 * 1000\n\n\ndef first_report_id(prefix):\n return f'{prefix}__first_report'\n\n\ndef last_report_id(prefix):\n return f'{prefix}__last_report'\n\n\ndef days_reporting_id(prefix):\n return f'{prefix}__days_reporting'\n\n\ndef silent_days_id(prefix):\n return f'{prefix}__silent_days'\n\n\ndef build_query_filter(original_calculation):\n '''Build a query filter that will captures all reported events for the given\n calculation.\n '''\n aggregations = {}\n for key, aggregation in original_calculation.aggregations.items():\n agg = aggregation\n # If the aggregation requires information from the query to be computed, extract\n # the filter applied to the base aggregation. Most aggregations of this type\n # have a dependency on *time*, which we do not care about here. We want to\n # capture all events and we can ignore the query dependent portion since we are\n # not trying to accurately calculate the aggregation's value.\n if isinstance(aggregation, QueryDependentAggregation):\n agg = aggregation.base_aggregation\n aggregations[key] = agg\n return build_query_filter_from_aggregations(aggregations)\n\n\ndef build_calculation(field):\n field_id = field.id\n query_filter = build_query_filter(field.calculation.to_druid(field_id))\n\n # Calculate the first and last times a report was submitted.\n first_id = first_report_id(field_id)\n first_report_calculation = TimeCalculation(first_id, doublemin, query_filter)\n\n last_id = last_report_id(field_id)\n last_report_calculation = TimeCalculation(last_id, doublemax, query_filter)\n\n # Calculate the number of unique days that a report was submitted.\n days_reporting_calculation = ThetaSketchUniqueCountCalculation(\n days_reporting_id(field_id),\n '__time',\n count_filter=query_filter,\n is_input_theta_sketch=False,\n )\n\n calculation = CalculationMerger(\n [first_report_calculation, last_report_calculation, days_reporting_calculation]\n )\n\n # Calculate the number of days since the last report.\n # Floor the current epoch time to be the start of the day since all of our data in\n # Druid does not have a \"time\" component. This makes the result a nice round number.\n today_ms = int(time.time() * 1000 / MILLISECONDS_IN_DAY) * MILLISECONDS_IN_DAY\n formula = f'({today_ms} - {last_id}) / {MILLISECONDS_IN_DAY}'\n calculation.add_post_aggregation_from_formula(silent_days_id(field_id), formula)\n return calculation\n\n\nclass DataQualityTable(AQTBase):\n def __init__(self, *args, **kwargs):\n # Disable intermediate date filling because it is not needed for DataQuality\n # score computation.\n super().__init__(fill_intermediate_dates=False, *args, **kwargs)\n\n def build_query(self):\n calculations = [build_calculation(field) for field in self.request.fields]\n return GroupByQueryBuilder(\n datasource=self.datasource.name,\n granularity=self.request.build_granularity(),\n grouping_fields=self.request.build_dimensions(),\n intervals=self.request.build_intervals(),\n calculation=CalculationMerger(calculations),\n dimension_filter=self.request.build_query_filter(),\n )\n\n def build_df(self, raw_df):\n if raw_df.empty:\n return raw_df\n\n dimensions = self.grouping_dimension_ids()\n if dimensions:\n # Use the most granular dimension as the pretty name for each result.\n # NOTE(stephen): This assumes the dimensions are sorted from least to most\n # granular.\n raw_df['name'] = raw_df[dimensions[-1]]\n else:\n # If no dimensions are selected, assume this is a Nation level query.\n raw_df['name'] = 'Nation'\n return raw_df\n\n def build_response(self, df):\n '''Build the query response result from the result dataframe.'''\n\n # NOTE(stephen): Right now, data quality only supports one field. Build the\n # output format as if there is a single field to query.\n field_id = self.request.fields[0].id\n df['firstReport'] = df[first_report_id(field_id)]\n df['lastReport'] = df[last_report_id(field_id)]\n df['numReports'] = df[days_reporting_id(field_id)]\n df['silentDays'] = df[silent_days_id(field_id)]\n\n # Create a list of reporting data (by location) and a list of locations.\n report_df = df[\n ['firstReport', 'lastReport', 'numReports', 'silentDays', 'name']\n ]\n reports = report_df.to_dict('records')\n locations = df[self.grouping_dimension_ids()].to_dict('records')\n\n # Merge the locations into the reports.\n for i, report in enumerate(reports):\n report['locationHierarchy'] = locations[i]\n return reports\n","sub_path":"web/server/query/data_quality/data_quality_table.py","file_name":"data_quality_table.py","file_ext":"py","file_size_in_byte":5453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"555786576","text":"#!/usr/bin/env python\n\nimport RPi.GPIO as GPIO\nimport time, sys\nimport pymongo\n\nFLOW_SENSOR = 23\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(FLOW_SENSOR, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)\n\nclient = pymongo.MongoClient(\"localhost\", 27017)\ndb = client.sensors.flow\n\nglobal count\ncount = 0\n\ndef countPulse(channel):\n global count\n count = count+1\n\nGPIO.add_event_detect(FLOW_SENSOR, GPIO.RISING, callback=countPulse)\n\nwhile True:\n try:\n count = 0\n time.sleep(1)\n pulse = count\n db.insert_one({\"value\": pulse})\n\n except KeyboardInterrupt:\n GPIO.cleanup()\n sys.exit()\n","sub_path":"sensors/flow.py","file_name":"flow.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"562116517","text":"### 881. Boats to Save People\n# Time complexity: O(N) where N = list size\n# Space complexity: O(N) where N = list size (O(1) if not count the input list)\nclass Solution:\n def numRescueBoats(self, people, limit):\n \"\"\"\n :type people: List[int]\n :type limit: int\n :rtype: int\n \"\"\"\n people.sort()\n boat = 0\n i = 0\n j = len(people)-1\n while i<j:\n if people[i]+people[j] <= limit:\n i += 1\n j -= 1\n else:\n j -= 1\n boat += 1\n return boat+1 if i==j else boat\n","sub_path":"881/lc881-solution2.py","file_name":"lc881-solution2.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"95097910","text":"'''\r\nFaça um programa que calcule o valor total investido por um colecionador em sua coleção de CDs e o valor médio gasto em cada um deles. O usuário deverá informar a quantidade de CDs e o valor para em cada um. \r\n'''\r\n\r\n\r\nif __name__ == '__main__':\r\n quantidade_cd = int(input('Informe a quantidade de CD\\'s: ' ))\r\n \r\n contador = 0\r\n somatorio = 0\r\n \r\n if quantidade_cd > 0:\r\n\r\n while contador < quantidade_cd:\r\n\r\n valor = float(input('Informe o valor do %sº CD: ' %(contador + 1)))\r\n\r\n if valor >= 0:\r\n contador += 1\r\n somatorio += valor\r\n else:\r\n print('Valor inválido')\r\n\r\n valor_medio = somatorio / contador\r\n print('O valor médio de todos os CD\\'s é igual a R${:.2f}'.format(valor_medio))\r\n\r\n else:\r\n print('Quantidade de CD\\'s insuficiente')\r\n","sub_path":"Lista de Exercícios/02 - Estrutura de repetição/ex028.py","file_name":"ex028.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"539178907","text":"# Copyright\n# 2019 Department of Dermatology, School of Medicine, Tohoku University\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.\nimport os\n\nfrom profilehooks import profile\n\nfrom pathilico.misc.behavior_tools import *\nfrom pathilico.pygletelm.effect import NO_COMMANDS, NO_SUBSCRIPTIONS\n\n\nSAMPLE_FILE_PATH = os.path.expanduser(\n \"~/DataForML/svs/aiba.svs\"\n)\nLOGGING_CONFIG = dict(\n graphic_manager=\"INFO\",\n effect_executor=\"INFO\",\n backend=\"INFO\"\n)\nWINDOW_SIZE = (16 * 80, 9 * 80)\n\n\ndef get_schedule():\n schedule = (\n ((\"once\", 0.3), Msg.WindowResized, dict(\n width=WINDOW_SIZE[0], height=WINDOW_SIZE[1])),\n ((\"once\", 0.1), Msg.ChangeMode, dict(new_mode=\"file_select\")),\n )\n behavior = ScheduledBehavior.from_schedules(schedule)\n return behavior\n\n\nSCHEDULE = get_schedule()\n\n\ndef init_nothing_model():\n return 0, NO_COMMANDS\n\n\n@wrap_subscriptions_with_message_dispatcher(SCHEDULE)\ndef subscriptions(model):\n return NO_SUBSCRIPTIONS\n\n\ndef app():\n load_dependencies()\n configure_app_logging_settings()\n program(\n init=init_model,\n view=view,\n update=update,\n subscriptions=subscriptions,\n logger_config=LOGGING_CONFIG,\n initial_window_size=WINDOW_SIZE\n )\n\n\nif __name__ == \"__main__\":\n app()","sub_path":"python/tests/behavior_tests/file_select_view.py","file_name":"file_select_view.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"31426264","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport functools\r\nimport torchvision.models as models\r\nfrom model.network.base_function import ADAIN\r\nfrom torch.nn import init\r\nimport utils\r\nimport random\r\n\r\n##################################################################\r\n\r\ndef get_norm_layer(type):\r\n if type=='LN':\r\n return functools.partial(LayerNorm,affine=True)\r\n if type=='IN':\r\n return functools.partial(nn.InstanceNorm2d,affine=True)\r\n if type=='BN':\r\n return functools.partial(nn.BatchNorm2d,momentum=0.1,affine=True)\r\n return None\r\n\r\ndef get_non_linearity(layer_type='relu'):\r\n if layer_type == 'relu':\r\n nl_layer = functools.partial(nn.ReLU)\r\n elif layer_type == 'lrelu':\r\n nl_layer = functools.partial(nn.LeakyReLU,0.1)\r\n elif layer_type == 'selu':\r\n nl_layer = functools.partial(nn.SELU)\r\n else:\r\n raise NotImplementedError('nonlinearity activitation [%s] is not found' % layer_type)\r\n return nl_layer\r\n\r\ndef block_nl_nll_conv(inc,outc,kernel_size=3,stride=1,padding=1,norm_layer='LN',non_linerity_layer='relu'):\r\n norm=get_norm_layer(norm_layer)\r\n nll=get_non_linearity(layer_type=non_linerity_layer)\r\n model=[]\r\n if norm is not None:\r\n model.append(norm(inc))\r\n model+=[nll(),nn.ReflectionPad2d(padding),nn.Conv2d(inc,outc,kernel_size=kernel_size,stride=stride,padding=0)]\r\n return nn.Sequential(*model)\r\n\r\ndef padding_conv(inc,outc,kernel_size=3,stride=1,padding=1):\r\n model=[]\r\n model+=[nn.ReflectionPad2d(padding),nn.Conv2d(inc,outc,kernel_size=kernel_size,stride=stride,padding=0)]\r\n return nn.Sequential(*model)\r\n\r\ndef block_conv_nl_nll(inc,outc,kernel_size=3,stride=1,padding=1,norm_layer='LN',non_linerity_layer='relu'):\r\n norm=get_norm_layer(norm_layer)\r\n nll=get_non_linearity(layer_type=non_linerity_layer)\r\n model=[]\r\n model.append(nn.ReflectionPad2d(padding))\r\n model+=[nn.Conv2d(inc,outc,kernel_size=kernel_size,stride=stride,padding=0)]\r\n if norm is not None:\r\n model.append(norm(outc))\r\n model+=[nll()]\r\n return nn.Sequential(*model)\r\n\r\nclass resblock_conv(nn.Module):\r\n def __init__(self,inc,outc=None,hiddenc=None,norm_layer='LN',non_linerity_layer='relu'):\r\n super(resblock_conv,self).__init__()\r\n hiddenc=inc if hiddenc is None else hiddenc\r\n outc=inc if outc is None else outc\r\n norm=get_norm_layer(norm_layer)\r\n nll=get_non_linearity(layer_type=non_linerity_layer)\r\n model=[]\r\n if norm is not None:\r\n model.append(norm(inc))\r\n model+=[nll(),nn.ReflectionPad2d(1),nn.Conv2d(inc,hiddenc,3,1,padding=0)]\r\n if norm is not None:\r\n model.append(norm(hiddenc))\r\n model+=[nll(),nn.ReflectionPad2d(1),nn.Conv2d(hiddenc,outc,3,1,padding=0)]\r\n self.bp=False\r\n if outc!=inc:\r\n self.bp=True\r\n self.bypass=nn.Conv2d(inc,outc,1,1,0)\r\n self.model=nn.Sequential(*model)\r\n\r\n def forward(self,x):\r\n residual=x\r\n if self.bp:\r\n out=self.model(x)+self.bypass(residual)\r\n else:\r\n out=self.model(x)+residual\r\n return out\r\n\r\nclass resblock_transconv(nn.Module):\r\n def __init__(self,inc,outc,hiddenc=None,norm_layer='LN',non_linerity_layer='relu'):\r\n super(resblock_transconv,self).__init__()\r\n norm=get_norm_layer(norm_layer)\r\n nll=get_non_linearity(layer_type=non_linerity_layer)\r\n hiddenc=inc if hiddenc is None else hiddenc\r\n self.model=[]\r\n if norm is not None:\r\n self.model.append(norm(inc))\r\n self.model+=[nll(),\r\n nn.Conv2d(inc,hiddenc,3,1,1)]\r\n if norm is not None:\r\n self.model.append(norm(hiddenc))\r\n self.model+=[nll(),\r\n nn.ConvTranspose2d(hiddenc,outc,3,2,1,1)]\r\n self.model=nn.Sequential(*self.model)\r\n self.bypass=nn.Sequential(nn.ConvTranspose2d(inc,outc,3,2,1,1))\r\n\r\n def forward(self,x):\r\n residual=x\r\n out=self.model(x)+self.bypass(residual)\r\n return out\r\n\r\nclass resblock_upbilin(nn.Module):\r\n def __init__(self,inc,outc=None,norm_layer='LN',non_linerity_layer='relu'):\r\n super(resblock_upbilin,self).__init__()\r\n norm=get_norm_layer(norm_layer)\r\n nll=get_non_linearity(layer_type=non_linerity_layer)\r\n outc=inc if outc is None else outc\r\n self.model=[]\r\n if norm is not None:\r\n self.model.append(norm(inc))\r\n self.model+=[nll(),\r\n nn.Conv2d(inc,outc,3,1,1)]\r\n if norm is not None:\r\n self.model.append(norm(outc))\r\n self.model+=[nll(),nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)]\r\n self.model=nn.Sequential(*self.model)\r\n self.bypass=nn.Sequential(nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True))\r\n\r\n def forward(self,x):\r\n residual=x\r\n out=self.model(x)+self.bypass(residual)\r\n return out\r\n\r\nclass LayerNorm(nn.Module):\r\n def __init__(self, num_features, eps=1e-5, affine=True):\r\n super(LayerNorm, self).__init__()\r\n self.num_features = num_features\r\n self.affine = affine\r\n self.eps = eps\r\n\r\n if self.affine:\r\n self.gamma = nn.Parameter(torch.Tensor(num_features).uniform_())\r\n self.beta = nn.Parameter(torch.zeros(num_features))\r\n\r\n def forward(self, x):\r\n shape = [-1] + [1] * (x.dim() - 1)\r\n # print(x.size())\r\n if x.size(0) == 1:\r\n # These two lines run much faster in pytorch 0.4 than the two lines listed below.\r\n mean = x.view(-1).mean().view(*shape)\r\n std = x.view(-1).std().view(*shape)\r\n else:\r\n mean = x.view(x.size(0), -1).mean(1).view(*shape)\r\n std = x.view(x.size(0), -1).std(1).view(*shape)\r\n\r\n x = (x - mean) / (std + self.eps)\r\n\r\n if self.affine:\r\n shape = [1, -1] + [1] * (x.dim() - 2)\r\n x = x * self.gamma.view(*shape) + self.beta.view(*shape)\r\n return x\r\n\r\ndef initialize_weights(net,init_type='xavier', gain=0.02):\r\n def init_func(m):\r\n classname = m.__class__.__name__\r\n if classname.find('BatchNorm2d') != -1:\r\n if hasattr(m, 'weight') and m.weight is not None:\r\n init.normal_(m.weight.data, 1.0, gain)\r\n if hasattr(m, 'bias') and m.bias is not None:\r\n init.constant_(m.bias.data, 0.0)\r\n elif hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):\r\n if init_type == 'normal':\r\n init.normal_(m.weight.data, 0.0, gain)\r\n elif init_type == 'xavier':\r\n init.xavier_normal_(m.weight.data, gain=gain)\r\n elif init_type == 'xavier_uniform':\r\n init.xavier_uniform_(m.weight.data, gain=1.0)\r\n elif init_type == 'kaiming':\r\n init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\r\n elif init_type == 'orthogonal':\r\n init.orthogonal_(m.weight.data, gain=gain)\r\n elif init_type == 'none': # uses pytorch's default init method\r\n m.reset_parameters()\r\n else:\r\n raise NotImplementedError('initialization method [%s] is not implemented' % init_type)\r\n if hasattr(m, 'bias') and m.bias is not None:\r\n init.constant_(m.bias.data, 0.0)\r\n for m in net.modules():\r\n init_func(m)\r\n \r\n###########################################################################\r\nclass Layer_down(nn.Module):\r\n def __init__(self, inchannel, outchannel, blocks=1,norm_layer='LN'):\r\n super(Layer_down, self).__init__()\r\n self.flatten = nn.Sequential(\r\n get_norm_layer(norm_layer)(inchannel),\r\n get_non_linearity()(),\r\n nn.MaxPool2d(kernel_size=2, stride=2),\r\n padding_conv(inchannel,outchannel,3,1,1)\r\n )\r\n self.layer_blocks = []\r\n for _ in range(blocks):\r\n self.layer_blocks.append(resblock_conv(outchannel,norm_layer=norm_layer))\r\n self.layer_blocks = nn.Sequential(*self.layer_blocks)\r\n\r\n def forward(self, x):\r\n out = self.flatten(x)\r\n out = self.layer_blocks(out)\r\n return out\r\n\r\nclass Layer_up(nn.Module):\r\n def __init__(self, inchannel,outchannel, blocks=1,bilinear=False,norm_layer='LN', enc_inc=None):\r\n super(Layer_up, self).__init__()\r\n enc_inc=inchannel if enc_inc is None else enc_inc\r\n if bilinear:\r\n self.heighten=nn.Sequential(get_norm_layer(norm_layer)(inchannel),\r\n get_non_linearity()(),\r\n nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True),\r\n padding_conv(inchannel,outchannel,3,1,1),\r\n ) \r\n else:\r\n self.heighten = nn.Sequential(resblock_transconv(inchannel,inchannel,norm_layer=norm_layer),\r\n block_nl_nll_conv(inchannel,outchannel,norm_layer=norm_layer))\r\n self.bypass_sc = block_nl_nll_conv(enc_inc,outchannel,3,1,1,norm_layer=norm_layer)\r\n self.layer_blocks = []\r\n for _ in range(blocks):\r\n self.layer_blocks.append(resblock_conv(outchannel,norm_layer=norm_layer))\r\n self.layer_blocks = nn.Sequential(*self.layer_blocks)\r\n\r\n def forward(self, x, cat):\r\n y = self.heighten(x)\r\n y=y+self.bypass_sc(cat)\r\n y = self.layer_blocks(y)\r\n return y\r\n\r\n#####################################################################################\r\n\r\n\r\nclass Unet_encoder(nn.Module):\r\n def __init__(self, inchannel, ndf=32,blocks=1, depth=5,norm_layer='LN'):\r\n super(Unet_encoder, self).__init__()\r\n self.Inconv=nn.Sequential(padding_conv(inchannel,ndf,7,1,3))\r\n self.layer_blocks = []\r\n for _ in range(blocks):\r\n self.layer_blocks.append(resblock_conv(ndf,norm_layer=norm_layer))\r\n self.layer_blocks = nn.Sequential(*self.layer_blocks)\r\n self.down_layers = []\r\n channel_in=ndf\r\n for _ in range(depth - 1):\r\n self.down_layers.append(Layer_down(channel_in, channel_in*2, blocks,norm_layer=norm_layer))\r\n channel_in=channel_in*2\r\n self.down_layers = nn.ModuleList(self.down_layers)\r\n initialize_weights(self)\r\n\r\n def __call__(self, x):\r\n return self.forward(x)\r\n\r\n def forward(self, x):\r\n tmp = []\r\n out = self.Inconv(x)\r\n out=self.layer_blocks(out)\r\n tmp.append(out)\r\n for layer in self.down_layers[:-1]:\r\n out = layer(out)\r\n tmp.append(out)\r\n out = self.down_layers[-1](out)\r\n return out, tmp\r\n\r\nclass Unet_decoder(nn.Module):\r\n def __init__(self, outchannel,ndf=32, blocks=1, depth=5,bilinear=False,norm_layer='LN'):\r\n super(Unet_decoder, self).__init__()\r\n self.up_layers = []\r\n channel_in=ndf*(2**(depth-1))\r\n for _ in range(depth - 1):\r\n self.up_layers.append(Layer_up(channel_in, channel_in//2, blocks=blocks,\r\n bilinear=bilinear,norm_layer=norm_layer,enc_inc=channel_in//2))\r\n channel_in=channel_in//2\r\n self.up_layers = nn.ModuleList(self.up_layers)\r\n self.outconv = nn.Sequential(block_nl_nll_conv(channel_in,outchannel,3,1,1,norm_layer=norm_layer),\r\n block_nl_nll_conv(outchannel,outchannel,1,1,0,norm_layer=norm_layer),\r\n )\r\n initialize_weights(self)\r\n\r\n def forward(self, x, tmp):\r\n out=x\r\n for idx, layer in enumerate(self.up_layers):\r\n out = layer(out, tmp[-(idx + 1)])\r\n out = self.outconv(out)\r\n return out\r\n\r\nclass Unet(nn.Module):\r\n def __init__(self, inchannel=3, outchannel=3, ndf=64,enc_blocks=1, dec_blocks=3, depth=5,bilinear=False,norm_layer='LN'):\r\n super(Unet, self).__init__()\r\n self.e = Unet_encoder(inchannel=inchannel,ndf=ndf,blocks= enc_blocks,depth= depth,norm_layer=norm_layer)\r\n self.d = Unet_decoder(outchannel=outchannel,ndf=ndf,blocks= dec_blocks,depth= depth,bilinear=bilinear,norm_layer=norm_layer)\r\n\r\n def forward(self, x):\r\n out, temp = self.e(x)\r\n out = self.d(out, temp)\r\n out=torch.tanh(out)\r\n return out\r\n\r\n\r\n######################################################################################\r\nclass Encoder_S(nn.Module):\r\n def __init__(self,inc=3,n_downsample=2,ndf=32,norm_layer='LN'):\r\n super().__init__()\r\n self.Inconv=padding_conv(inc,ndf,7,1,3)\r\n channel_in=ndf\r\n self.model=list()\r\n for _ in range(n_downsample):\r\n self.model+=[block_nl_nll_conv(channel_in,channel_in*2,4,2,1,norm_layer=norm_layer)]\r\n channel_in=channel_in*2\r\n for _ in range(2):\r\n self.model+=[resblock_conv(channel_in,norm_layer=norm_layer)]\r\n self.model=nn.Sequential(*self.model)\r\n self.Outconv=nn.Sequential(block_nl_nll_conv(channel_in,channel_in,1,1,0,norm_layer=norm_layer))\r\n self.outc=channel_in\r\n self.n_downsample=n_downsample\r\n initialize_weights(self)\r\n\r\n def forward(self, x):\r\n y=self.Inconv(x)\r\n # ho=[]\r\n # for layer in self.model:\r\n # y=layer(y)\r\n # ho.append(y)\r\n y=self.model(y)\r\n y=self.Outconv(y)\r\n return y\r\n\r\nclass Encoder_E(nn.Module):\r\n def __init__(self,inc=3,n_downsample=4,outc=8,ndf=64,usekl=True):\r\n super().__init__()\r\n self.usekl=usekl\r\n self.conv1=block_conv_nl_nll(inc,ndf,7,1,3,norm_layer=None)\r\n self.downconv=[]\r\n channel_in=ndf\r\n for _ in range(2):\r\n self.downconv.append(block_conv_nl_nll(channel_in,channel_in*2,4,2,1,norm_layer=None))\r\n channel_in*=2\r\n for _ in range(n_downsample-2):\r\n self.downconv+=[block_conv_nl_nll(channel_in,channel_in,4,2,1,norm_layer=None)]\r\n self.downconv.append(nn.AdaptiveAvgPool2d(1))\r\n self.downconv=nn.Sequential(*self.downconv)\r\n if usekl:\r\n self.mean_fc =nn.Linear(channel_in, outc)\r\n self.var_fc= nn.Linear(channel_in, outc)\r\n else:\r\n self.fc= nn.Linear(channel_in, outc)\r\n initialize_weights(self)\r\n\r\n def forward(self, x):\r\n y = self.conv1(x)\r\n y=self.downconv(y)\r\n y = y.view(x.size(0), -1)\r\n if self.usekl:\r\n mean=self.mean_fc(y)\r\n var=self.var_fc(y)\r\n return mean,var\r\n else:\r\n y=self.fc(y)\r\n return y\r\n\r\nclass Decoder_SE(nn.Module):\r\n def __init__(self,s_inc=128,e_inc=8,outc=3,n_upsample=2,norm_layer='LN'):\r\n super().__init__()\r\n inc=s_inc\r\n self.adin=ADAIN(inc,e_inc)\r\n self.model=[]\r\n self.model+=[padding_conv(inc,inc,1,1,0),resblock_conv(inc,norm_layer=norm_layer)]\r\n channel_in=inc\r\n for _ in range(n_upsample):\r\n self.model+=[resblock_transconv(channel_in,channel_in//2,norm_layer=norm_layer)]\r\n channel_in=channel_in//2\r\n self.model=nn.Sequential(*self.model)\r\n self.outconv = nn.Sequential(\r\n block_nl_nll_conv(channel_in,outc,3,1,1,norm_layer=norm_layer),\r\n )\r\n initialize_weights(self)\r\n\r\n def forward(self, x1,x2):\r\n out = self.adin(x1, x2)\r\n out=self.model(out)\r\n out=self.outconv(out)\r\n out=torch.tanh(out)\r\n return out\r\n\r\n#######################################################################################\r\n\r\n#VGG 19\r\nclass VGG19(torch.nn.Module):\r\n def __init__(self):\r\n super(VGG19, self).__init__()\r\n vgg=models.vgg19()\r\n vgg.load_state_dict(torch.load('./checkpoints/vgg19/vgg19-dcbb9e9d.pth',map_location=torch.device('cpu')))\r\n features = vgg.features\r\n self.relu1_1 = torch.nn.Sequential()\r\n self.relu1_2 = torch.nn.Sequential()\r\n\r\n self.relu2_1 = torch.nn.Sequential()\r\n self.relu2_2 = torch.nn.Sequential()\r\n\r\n self.relu3_1 = torch.nn.Sequential()\r\n self.relu3_2 = torch.nn.Sequential()\r\n self.relu3_3 = torch.nn.Sequential()\r\n self.relu3_4 = torch.nn.Sequential()\r\n\r\n self.relu4_1 = torch.nn.Sequential()\r\n self.relu4_2 = torch.nn.Sequential()\r\n self.relu4_3 = torch.nn.Sequential()\r\n self.relu4_4 = torch.nn.Sequential()\r\n\r\n self.relu5_1 = torch.nn.Sequential()\r\n self.relu5_2 = torch.nn.Sequential()\r\n self.relu5_3 = torch.nn.Sequential()\r\n self.relu5_4 = torch.nn.Sequential()\r\n\r\n for x in range(2):\r\n self.relu1_1.add_module(str(x), features[x])\r\n\r\n for x in range(2, 4):\r\n self.relu1_2.add_module(str(x), features[x])\r\n\r\n for x in range(4, 7):\r\n self.relu2_1.add_module(str(x), features[x])\r\n\r\n for x in range(7, 9):\r\n self.relu2_2.add_module(str(x), features[x])\r\n\r\n for x in range(9, 12):\r\n self.relu3_1.add_module(str(x), features[x])\r\n\r\n for x in range(12, 14):\r\n self.relu3_2.add_module(str(x), features[x])\r\n\r\n for x in range(14, 16):\r\n self.relu3_2.add_module(str(x), features[x])\r\n\r\n for x in range(16, 18):\r\n self.relu3_4.add_module(str(x), features[x])\r\n\r\n for x in range(18, 21):\r\n self.relu4_1.add_module(str(x), features[x])\r\n\r\n for x in range(21, 23):\r\n self.relu4_2.add_module(str(x), features[x])\r\n\r\n for x in range(23, 25):\r\n self.relu4_3.add_module(str(x), features[x])\r\n\r\n for x in range(25, 27):\r\n self.relu4_4.add_module(str(x), features[x])\r\n\r\n for x in range(27, 30):\r\n self.relu5_1.add_module(str(x), features[x])\r\n\r\n for x in range(30, 32):\r\n self.relu5_2.add_module(str(x), features[x])\r\n\r\n for x in range(32, 34):\r\n self.relu5_3.add_module(str(x), features[x])\r\n\r\n for x in range(34, 36):\r\n self.relu5_4.add_module(str(x), features[x])\r\n\r\n # don't need the gradients, just want the features\r\n for param in self.parameters():\r\n param.requires_grad = False\r\n\r\n def forward(self, x):\r\n relu1_1 = self.relu1_1(x)\r\n relu1_2 = self.relu1_2(relu1_1)\r\n\r\n relu2_1 = self.relu2_1(relu1_2)\r\n relu2_2 = self.relu2_2(relu2_1)\r\n\r\n relu3_1 = self.relu3_1(relu2_2)\r\n relu3_2 = self.relu3_2(relu3_1)\r\n relu3_3 = self.relu3_3(relu3_2)\r\n relu3_4 = self.relu3_4(relu3_3)\r\n\r\n relu4_1 = self.relu4_1(relu3_4)\r\n relu4_2 = self.relu4_2(relu4_1)\r\n relu4_3 = self.relu4_3(relu4_2)\r\n relu4_4 = self.relu4_4(relu4_3)\r\n\r\n relu5_1 = self.relu5_1(relu4_4)\r\n relu5_2 = self.relu5_2(relu5_1)\r\n relu5_3 = self.relu5_3(relu5_2)\r\n relu5_4 = self.relu5_4(relu5_3)\r\n\r\n out = {\r\n 'relu1_1': relu1_1,\r\n 'relu1_2': relu1_2,\r\n\r\n 'relu2_1': relu2_1,\r\n 'relu2_2': relu2_2,\r\n\r\n 'relu3_1': relu3_1,\r\n 'relu3_2': relu3_2,\r\n 'relu3_3': relu3_3,\r\n 'relu3_4': relu3_4,\r\n\r\n 'relu4_1': relu4_1,\r\n 'relu4_2': relu4_2,\r\n 'relu4_3': relu4_3,\r\n 'relu4_4': relu4_4,\r\n\r\n 'relu5_1': relu5_1,\r\n 'relu5_2': relu5_2,\r\n 'relu5_3': relu5_3,\r\n 'relu5_4': relu5_4,\r\n }\r\n return out\r\n","sub_path":"model/network/components.py","file_name":"components.py","file_ext":"py","file_size_in_byte":19650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"246359388","text":"from __future__ import print_function\n\nimport os\nimport ctypes\nimport sys\n\nfrom clang.cindex import TypeKind\nfrom ctypeslib.codegen import clangparser, typedesc\nfrom ctypeslib.codegen.codegenerator import Generator\n\n\nclass MyGenerator(Generator):\n def type_name(self, t, generate=True):\n \"\"\"\n Override POINTER_T; full-disclosure I don't know what it is for, just\n that we get RaspberryPi (arm) support without it.\n \"\"\"\n if isinstance(t, typedesc.PointerType):\n return \"ctypes.POINTER(%s)\" % (self.type_name(t.typ, generate))\n else:\n return super(MyGenerator, self).type_name(t, generate)\n\n def Typedef(self, tp):\n \"\"\"\n Allow ctypes to handle a few more special types\n \"\"\"\n sized_types = {\n \"size_t\": \"c_size_t\",\n \"ssize_t\": \"c_size_t\",\n \"wchar_t\": \"c_wchar\",\n }\n name = self.type_name(tp) # tp.name\n if (isinstance(tp.typ, typedesc.FundamentalType) and\n tp.name in sized_types):\n print(u\"%s = ctypes.%s\" % \\\n (name, sized_types[tp.name]), file=self.stream)\n self.names.add(tp.name)\n return\n return super(MyGenerator, self).Typedef(tp)\n\ndef run():\n parser = clangparser.Clang_Parser(('-I/usr/include/clang/5.0/include/',))\n parser.filter_location(\n [\n os.path.abspath('pynfc/nfc.c'),\n os.path.abspath('pynfc/freefare.c'),\n os.path.abspath('pynfc/mifare.c'),\n '/usr/include/freefare.h',\n '/usr/include/nfc/nfc-types.h',\n '/usr/include/nfc/nfc.h',\n ]\n )\n parser.parse(os.path.abspath('pynfc/nfc.c'))\n items = parser.get_result()\n items = [i for i in items if isinstance(i, (typedesc.Function, typedesc.Typedef))]\n with open('pynfc/nfc.py', 'w') as out:\n gen = MyGenerator(\n out,\n searched_dlls=(\n ctypes.CDLL('libfreefare.so'),\n )\n )\n gen.generate_headers(parser)\n gen.generate_code(items)\n","sub_path":"gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"550148807","text":"#!/usr/bin/env python\n#coding:utf-8\n\"\"\"\n Author: --<v1ll4n>\n Purpose: Render The Template\n Created: 2016/12/20\n\"\"\"\n\nimport unittest\nimport types\nimport random\nimport time\nimport warnings\nimport uuid\nimport re\nimport itertools\n\nREG_N = r'(\\{\\[\\{(N)(\\(([a-zA-z_][a-zA-Z_0-9]*)?\\))?({([1-9]\\d*)?,?([1-9]\\d*)?})?\\}\\]\\})'\nREG_NS_NC_S_C = r'(\\{\\[\\{(NS|NC|S|C)(\\(([a-zA-z_][a-zA-Z_0-9]*)?\\))?({([1-9]\\d*)?,?([1-9]\\d*)?})?\\}\\]\\})'\nREG_ENUM_X = r'(\\{\\[\\{(X|ENUM)(\\(([a-zA-z_][a-zA-Z_0-9]*)\\))\\}\\]\\})'\nREG_UUID = r'(\\{\\[\\{(UUID)(\\(([a-zA-z_][a-zA-Z_0-9]*)?\\))?({(hex|raw)})?\\}\\]\\})'\n\nSVTYPE_LIST = ['N', 'NC', 'S', 'C', 'NS', 'ENUM', 'UUID', 'X']\n\nNS = 'NS'\nNC = 'NC'\nN = 'N'\nS = 'S'\nC = 'C'\nENUM = 'ENUM'\nUUID = 'UUID'\nX = 'X'\n\nrandom.seed(time.time())\n\n#----------------------------------------------------------------------\ndef get_random_digit():\n \"\"\"\"\"\"\n base = '0123456789'\n return random.choice(base)\n \n#----------------------------------------------------------------------\ndef get_random_word():\n \"\"\"\"\"\"\n number = range(48, 58)\n small_c = range(97, 123)\n big_c = range(65, 91)\n return chr(random.choice(random.choice([number, small_c, big_c])))\n\n#----------------------------------------------------------------------\ndef get_random_char():\n \"\"\"\"\"\"\n small_c = range(97, 123)\n big_c = range(65, 91)\n return chr(random.choice(random.choice([small_c, big_c]))) \n\n#----------------------------------------------------------------------\ndef get_uuid(type='raw'):\n \"\"\"\"\"\"\n if type == 'raw':\n return str(uuid.uuid1())\n elif type == 'hex':\n return str(uuid.uuid1().hex)\n\n#----------------------------------------------------------------------\ndef findall(template, reg):\n \"\"\"\"\"\"\n return re.findall(reg, template)\n \n\n########################################################################\nclass Scalpel(object):\n \"\"\"\"\"\"\n\n #----------------------------------------------------------------------\n def __init__(self, template, random_every_time=True, **kwargs):\n \"\"\"Constructor\"\"\"\n assert isinstance(template, (str, unicode)), \"Error payload \" + \\\n \"tempate, should be a str or unicode\"\n self._template = template\n self._random_every_time = random_every_time\n self._kwarfs = kwargs\n self._variable_table = {}\n \n self._parse_scalpel_variables()\n \n self._payloads = []\n \n #----------------------------------------------------------------------\n def _parse_scalpel_variables(self):\n \"\"\"\"\"\"\n self._parse_variable_n_s(REG_N)\n self._parse_variable_n_s(REG_NS_NC_S_C)\n self._parse_variable_e_x(REG_ENUM_X)\n \n \n #----------------------------------------------------------------------\n def _parse_variable_n_s(self, reg):\n \"\"\"\"\"\"\n \n results = findall(self._template, reg)\n if results != []:\n for orig, svtype, _, name, __, _min, _max in results:\n if _max == '':\n ret = SVariable(orig, svtype, name, \n params={'length':int(_min)}, \n value=self._kwarfs[name] if self._kwarfs.has_key(name) \\\n else '',\n random_every_time=self._random_every_time)\n else:\n ret = SVariable(orig, svtype, name, \n params={'min':int(_min), 'max':int(_max)}, \n value=self._kwarfs[name] if self._kwarfs.has_key(name) \\\n else '',\n random_every_time=self._random_every_time)\n self._variable_table[ret.name] = ret\n \n #----------------------------------------------------------------------\n def _parse_variable_u(self, reg):\n \"\"\"\"\"\"\n \n results = findall(self._template, reg)\n if results != []:\n for orig, svtype, _, name, __, uuid_param in results:\n ret = SVariable(orig, svtype, name, \n params={'uuid':uuid_param}, \n value=self._kwarfs[name] if self._kwarfs.has_key(name) \\\n else '',\n random_every_time=self._random_every_time)\n self._variable_table[ret.name] = ret\n \n #----------------------------------------------------------------------\n def _parse_variable_e_x(self, reg):\n \"\"\"\"\"\"\n \n results = findall(self._template, reg)\n if results != []:\n for orig, svtype, _, name in results:\n ret = SVariable(orig, svtype, name, \n params={}, \n value=self._kwarfs[name] if self._kwarfs.has_key(name) \\\n else '',\n random_every_time=self._random_every_time)\n self._variable_table[ret.name] = ret\n \n #----------------------------------------------------------------------\n def _render(self):\n \"\"\"\"\"\"\n def remove_none_from_list(ret):\n while True:\n try:\n ret.remove(None)\n except:\n break\n \n enum_variable = map(lambda x: x if x.type == ENUM else None, \n self._variable_table.values())\n ordinary_variable = map(lambda x: x if x.type != ENUM else None,\n self._variable_table.values())\n \n remove_none_from_list(enum_variable)\n remove_none_from_list(ordinary_variable)\n \n\n \n def render_enums(ret):\n result = []\n def render(result, ret, depth, tmp):\n #while True:\n if depth == len(ret):\n return\n else:\n varialbe = ret[depth]\n for i in varialbe.value:\n buff = tmp.replace(varialbe.orig, i)\n if depth + 1 == len(ret):\n result.append(buff)\n else:\n render(result, ret, depth + 1, buff)\n render(result, ret, depth=0, tmp=self._template)\n return result\n\n \n for ret in render_enums(enum_variable):\n for i in ordinary_variable:\n ret = ret.replace(i.orig, str(i.value)) \n yield ret\n \n #----------------------------------------------------------------------\n @property\n def payloads(self):\n \"\"\"\"\"\"\n return self._render()\n \n \n #----------------------------------------------------------------------\n @property\n def variable_table(self):\n \"\"\"\"\"\"\n return self._variable_table\n \n\n\n########################################################################\nclass SVariable(object):\n \"\"\"\"\"\"\n\n #----------------------------------------------------------------------\n def __init__(self, orig, svtype, name='', params={}, value='', random_every_time=True):\n \"\"\"Constructor\"\"\"\n \n assert svtype in SVTYPE_LIST, '[!] Error Template Variable Type' + \\\n 'Should be in [N,NS,NC,S,C,ENUM,UUID,X].'\n assert isinstance(name, (str, unicode)), '[!] Error name shuold be a str' + \\\n 'or unicode.'\n assert isinstance(value, (types.StringType, unicode,\n types.TupleType,\n types.ListType,\n types.GeneratorType)), '[!] Values Type Error!'\n \n self._type = svtype\n self._name = name if name != '' else get_uuid('hex')\n self._orig = orig\n self._param = {}\n\n self._random_every_time = random_every_time\n \n if self._param.has_key('length'):\n self._param['min'] = 8\n self._param['max'] = 9\n else:\n self._param['min'] = params['min'] if params.has_key('min') else 8\n self._param['max'] = params['max'] + 1 if params.has_key('max') else 9\n\n if self._param.has_key('uuid'):\n self._param['uuid'] = self._param['uuid'] if params['uuid'] in \\\n ['raw', 'hex'] else 'raw'\n else:\n self._param['uuid'] = 'raw'\n self._min = self._param['min']\n self._max = self._param['max']\n \n self._uservalue = value\n \n self._value = self._get_value(smin=self._min, smax=self._max, value=self._uservalue)\n \n \n #----------------------------------------------------------------------\n def _get_value(self, smin, smax, value):\n \"\"\"\"\"\"\n _min = smin\n _max = smax\n \n if self._type == N:\n if self._param['min'] == 8 and self._param['max'] == 9:\n value = random.randint(0, 999)\n else:\n value = random.randint(_min, _max)\n elif self._type == NS:\n tmp = ''\n for i in xrange(random.randint(xrange(_min, _max))):\n tmp = tmp + get_random_digit()\n value = tmp\n elif self._type == NC:\n for i in xrange(random.randint(xrange(_min, _max))):\n tmp = tmp + get_random_word()\n value = tmp\n elif self._type in S + C:\n for i in xrange(random.randint(xrange(_min, _max))):\n tmp = tmp + get_random_char() \n value = tmp\n elif self._type == ENUM:\n value = value if isinstance(value, (types.GeneratorType, \n types.ListType,\n types.TupleType)) else []\n if value == []:\n warnings.warn('[!] The enum\\' s value is emtpy(default is [])'+\\\n 'Are you sure that you did this?')\n elif self._type == X:\n value = value if isinstance(value, types.StringTypes) else ''\n elif self._type == UUID:\n value = get_uuid(self._param['uuid'])\n else:\n raise ValueError('[!] Type Error!')\n \n return value\n \n #----------------------------------------------------------------------\n @property \n def name(self):\n \"\"\"\"\"\"\n return self._name\n \n #----------------------------------------------------------------------\n @property \n def value(self):\n \"\"\"\"\"\"\n if self._random_every_time:\n return self._get_value(smin=self._min, smax=self._max, value=self._uservalue)\n else:\n return self._value\n \n #----------------------------------------------------------------------\n @property \n def type(self):\n \"\"\"\"\"\"\n return self._type\n\n #----------------------------------------------------------------------\n @property\n def orig(self):\n \"\"\"\"\"\"\n return self._orig\n \n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"scalpel_old/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":11114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"361886443","text":"from .models import *\nfrom django.shortcuts import render, get_object_or_404,redirect\nfrom django.views.generic import DetailView\nfrom django.views.generic.detail import SingleObjectMixin\nfrom django.http import JsonResponse\nimport json\nimport datetime\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.urls import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import UserForm,CustomerForm\nfrom django.contrib import messages\n# Create your views here.\n\n\ndef home(request):\n if request.user.is_authenticated:\n customer = request.user.customer\n order, created = Order.objects.get_or_create(\n customer=customer, complete=False)\n items = order.orderitem_set.all()\n cartItems = order.get_cart_items\n else:\n items = []\n order = {'get_cart_total': 0, 'get_cart_items': 0}\n cartItems = order['get_cart_items']\n prdoucts = ProductDetail.objects.all()\n messages.warning(request,'Zero Contact Delivery Due to Covid-19 Pandemic')\n context = {\n 'title': 'Home',\n 'products': prdoucts,\n 'cartItems': cartItems,\n }\n return render(request, 'store/home.html', context)\n\n\n\n\n\ndef menu(request):\n if request.user.is_authenticated:\n customer = request.user.customer\n order, created = Order.objects.get_or_create(\n customer=customer, complete=False)\n items = order.orderitem_set.all()\n cartItems = order.get_cart_items\n else:\n items = []\n order = {'get_cart_total': 0, 'get_cart_items': 0}\n cartItems = order['get_cart_items']\n prdoucts = ProductDetail.objects.all()\n \n context = {\n 'title': 'Menu',\n 'products': prdoucts,\n 'cartItems': cartItems,\n }\n return render(request, 'store/menu.html', context)\n\ndef OnOrder(request):\n if request.user.is_authenticated:\n customer = request.user.customer\n order, created = Order.objects.get_or_create(\n customer=customer, complete=False)\n items = order.orderitem_set.all()\n cartItems = order.get_cart_items\n else:\n items = []\n order = {'get_cart_total': 0, 'get_cart_items': 0}\n cartItems = order['get_cart_items']\n context = {\n 'title': 'On Order',\n 'cartItems': cartItems\n }\n return render(request, 'store/on_order.html', context)\n\n\n\nclass ProductDetailView(DetailView,SingleObjectMixin):\n model = ProductDetail\n\n def get_context_data(self, **kwargs):\n if self.request.user.is_authenticated:\n customer = self.request.user.customer\n order, created = Order.objects.get_or_create(\n customer=customer, complete=False)\n items = order.orderitem_set.all()\n cartItems = order.get_cart_items\n else:\n items = []\n order = {'get_cart_total': 0, 'get_cart_items': 0}\n cartItems = order['get_cart_items']\n context = super().get_context_data(**kwargs)\n context['cartItems'] = cartItems\n return context\n\ndef cart(request):\n if request.user.is_authenticated:\n customer = request.user.customer\n order, created = Order.objects.get_or_create(\n customer=customer, complete=False)\n items = order.orderitem_set.all()\n cartItems = order.get_cart_items\n print('Hedello')\n else:\n print('Hello')\n items = []\n order = {'get_cart_total': 0, 'get_cart_items': 0}\n cartItems = order['get_cart_items']\n\n context = {'items': items, 'order': order, 'cartItems': cartItems,'title': 'Cart'}\n return render(request, 'store/cart.html', context)\n\ndef updateItem(request):\n data = json.loads(request.body)\n productId = data['productId']\n action = data['action']\n\n customer = request.user.customer\n product = ProductDetail.objects.get(id=productId)\n order, created = Order.objects.get_or_create(\n customer=customer, complete=False)\n orderItem, created = OrderItem.objects.get_or_create(\n order=order, product=product)\n\n if action == 'add':\n orderItem.quantity = (orderItem.quantity + 1)\n elif action == 'remove':\n orderItem.quantity = (orderItem.quantity - 1)\n orderItem.save()\n\n if orderItem.quantity <= 0:\n orderItem.delete()\n return JsonResponse('item was added', safe=False)\n\ndef checkout(request):\n if request.user.is_authenticated:\n customer = request.user.customer\n order, created = Order.objects.get_or_create(\n customer=customer, complete=False)\n items = order.orderitem_set.all()\n cartItems = order.get_cart_items\n else:\n items = []\n order = {'get_cart_total': 0, 'get_cart_items': 0}\n cartItems = order['get_cart_items']\n\n context = {'items': items, 'order': order, 'cartItems': cartItems}\n\n return render(request, 'store/checkout.html', context)\n\ndef processOrder(request):\n transaction_id = datetime.datetime.now().timestamp()\n data = json.loads(request.body)\n\n if request.user.is_authenticated:\n customer = request.user.customer\n order, created = Order.objects.get_or_create(\n customer=customer, complete=False)\n total = data['form']['total']\n print(total, \" \", order.get_cart_total)\n order.transaction_id = transaction_id\n if float(total) == float(order.get_cart_total):\n order.complete = True\n order.save()\n\n ShippingAddress.objects.create(\n customer=customer,\n order=order,\n appt=data['shipping']['appt'],\n area=data['shipping']['area'],\n landmark=data['shipping']['landmark'],\n city=data['shipping']['city'],\n state=data['shipping']['state'],\n zipcode=data['shipping']['zipcode'],\n )\n else:\n print('User Not logged In')\n\n return JsonResponse('Payment Complete', safe=False)\n\ndef Login(request):\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n user = authenticate(username=username, password=password)\n if user:\n if user.is_active:\n login(request,user)\n messages.success(request, f'Sucessfully LoggedIn !!')\n return redirect('store-home')\n else:\n return HttpResponse(\"Your account was inactive.\")\n else:\n print(\"Someone tried to login and failed.\")\n print(\"They used username: {} and password: {}\".format(username,password))\n return HttpResponse(\"Invalid login details given\")\n else:\n return render(request, 'store/login.html', {})\n\n@login_required\ndef Logout(request):\n logout(request)\n return HttpResponseRedirect(reverse('store-home'))\n\ndef Register(request):\n registered = False\n if request.method == 'POST':\n user_form = UserForm(data=request.POST)\n customer_form = CustomerForm(data=request.POST)\n if user_form.is_valid() and customer_form.is_valid():\n user = user_form.save()\n user.set_password(user.password)\n user.save()\n customer = customer_form.save(commit=False)\n customer.user = user\n customer.name = user.username\n customer.save()\n registered = True\n else:\n print(user_form.errors,customer_form.errors)\n if registered:\n messages.success(request, f'Account created Now you can Log In !!')\n return redirect('login')\n else:\n user_form = UserForm()\n customer_form = CustomerForm()\n return render(request,'store/register.html',\n {'user_form':user_form,\n 'customer_form':customer_form,\n 'registered':registered})","sub_path":"store/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"110218751","text":"import logging\nimport os\nimport settings\n\nlogger = logging.getLogger(__name__)\n\ndef intTo2CarString(integ):\n strng = str(integ)\n if(len(strng)==1):\n strng = \"0\" + strng\n return strng\n\ndef doLoggingHeader(request):\n uagent = ''\n try:\n uagent = request.META['HTTP_USER_AGENT'].replace(';',',')\n except:\n uagent = 'NO USER AGENT'\n\n sessionid = ''\n try:\n sessionid = request.COOKIES['sessionid']\n if(not sessionid):\n sessionid = 'CSRF_'+request.COOKIES['csrftoken']\n\n except:\n sessionid = ''\n\n try:\n logger.debug(\"; OUTP_REQ; \" + request.META['REMOTE_ADDR'] + \"; \" + request.META['REQUEST_METHOD'] + \"; \" + request.path + \"; \" + request.META['QUERY_STRING'] + \"; \" + uagent + \"; \" + \"POST\" + str(request.POST) + \"; \" + str(request.COOKIES) + \"; \" + sessionid)\n except:\n logger.debug(\"; OUTP_REQ; Error when logging request\")\n logger.debug(request)\n\n\ndef get_stored_json_data():\n line = '; ; '\n f = open(settings.BASE_DIR + '/json/lastjson.txt', 'r')\n for line in f:\n pass\n f.close()\n\n stored_data = line.split('; ')[1]\n return stored_data\n\ndef get_stored_time():\n line = '; ; '\n f = open(settings.BASE_DIR + '/json/lastjson.txt', 'r')\n for line in f:\n pass\n f.close()\n\n stored_time = line.split('; ')[0]\n return stored_time","sub_path":"outpost/outp_utils.py","file_name":"outp_utils.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"429696055","text":"import re\n\ndef render_template(filename, **kwargs):\n with open(filename, 'r') as f:\n txt = f.read()\n for key in kwargs:\n pattern = '({{{{\\s*{}\\s*}}}})'.format(key)\n txt = re.sub(pattern, kwargs[key], txt)\n return txt\n \n#print(render_template('Makefile.tpl', text='Rumpel', text2='Rumpelpumpel'))","sub_path":"util/render_template.py","file_name":"render_template.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"148310235","text":"from PyQt5.QtWidgets import QHeaderView, QPushButton,QProgressDialog\nfrom PyQt5.QtCore import Qt\n\ndef showbarprocess(content):\n num = int(100000)\n progress = QProgressDialog()\n progress.setWindowTitle(\"Please waiting\")\n progress.setLabelText(content)\n progress.setCancelButton(None) ##不显示cancel button\n #progress.setCancelButtonText(\"\")\n progress.setMinimumDuration(5)\n progress.setWindowModality(Qt.WindowModal)\n progress.setRange(0, num)\n for i in range(num):\n progress.setValue(i)\n\n else:\n progress.setValue(num)","sub_path":"CMlib/showprocess.py","file_name":"showprocess.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"586633120","text":"# coding=utf-8\nfrom shutil import copyfile\nfrom shutil import move\n\nsample = 'docker-compose.sample.yml'\nconfig = 'docker-compose.yml'\ntmp_config = 'docker-compose.yml.tmp'\n\ncopyfile(sample, config)\n\nprint('Have a few questions for you')\nprint('How do I greet user ? ')\ngreeting_user_input = raw_input()\nprint('What do I transfer for ' + greeting_user_input + ' ?')\npayload_user_input = raw_input()\nprint ('Okay, got it.')\n\nprint('What about port?')\nprint ('Select port on which server will be accessible (current value: 9090)')\nport_user_input = raw_input()\n\nif not greeting_user_input:\n print(\"Given greeting is empty. Falling back to default\")\n greeting = \"Hea Kasutaja\"\nelse:\n greeting = greeting_user_input\n\nif not payload_user_input:\n print(\"Given payload is empty. Falling back to default\")\n payload = \"Kõik on korrus\"\nelse:\n payload = payload_user_input\n\nif not port_user_input:\n print(\"Empty port is not valid port. Using default (9090)\")\n server_port = 9090\nelse:\n try:\n raw_server_port = int(port_user_input)\n if raw_server_port < 1 | raw_server_port > 65535:\n print(\"port should be between 1 and 65535. Using default (9090)\")\n server_port = 9090\n else:\n server_port = raw_server_port\n except ValueError:\n print(\"port should be valid int between 1 and 65535. Using default (9090)\")\n server_port = 9090\n\nreplacements = {'kasutaja': greeting, 'payloadX': payload, '9090:8080': str(server_port) + ':8080'}\n\nwith open(config) as infile, open(tmp_config, 'w') as outfile:\n for line in infile:\n for src, target in replacements.iteritems():\n if src != target:\n line = line.replace(src, target)\n outfile.write(line)\n\nmove(tmp_config, config)\n\nprint(\"Done! Now it's time to run: 'docker-compose up -d'\")\n","sub_path":"secure-compose.py","file_name":"secure-compose.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"133703754","text":"# No shebang line, this module is meant to be imported\n#\n# Copyright 2014 Ambient Entertainment GmbH & Co. KG\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\"\"\"\nJobtypes\n============\n\nUI endpoints allowing seeing and manipulating jobtypes via the web interface\n\"\"\"\n\ntry:\n from httplib import (\n NOT_FOUND, INTERNAL_SERVER_ERROR, SEE_OTHER, BAD_REQUEST)\nexcept ImportError: # pragma: no cover\n from http.client import (\n NOT_FOUND, INTERNAL_SERVER_ERROR, SEE_OTHER, BAD_REQUEST)\n\nfrom flask import render_template, request, redirect, flash, url_for\n\nfrom sqlalchemy import desc, func, sql\n\nfrom pyfarm.models.jobtype import JobType, JobTypeVersion\nfrom pyfarm.models.software import (\n JobTypeSoftwareRequirement, Software, SoftwareVersion)\nfrom pyfarm.master.application import db\n\ndef jobtypes():\n return render_template(\"pyfarm/user_interface/jobtypes.html\",\n jobtypes=JobType.query)\n\ndef jobtype(jobtype_id):\n \"\"\"\n UI endpoint for a single jobtype. Allows showing and updating the jobtype\n \"\"\"\n jobtype = JobType.query.filter_by(id=jobtype_id).first()\n if not jobtype:\n return (render_template(\n \"pyfarm/error.html\", error=\"Jobtype %s not found\" %\n jobtype_id), NOT_FOUND)\n\n if request.method == \"POST\":\n with db.session.no_autoflush:\n jobtype.description = request.form[\"description\"]\n\n new_version = JobTypeVersion(jobtype=jobtype)\n new_version.max_batch = request.form[\"max_batch\"].strip() or\\\n sql.null()\n new_version.batch_contiguous =\\\n (\"batch_contiguous\" in request.form and\n request.form[\"batch_contiguous\"] == \"true\")\n new_version.no_automatic_start_time =\\\n (\"no_automatic_start_time\" in request.form and\n request.form[\"no_automatic_start_time\"] == \"true\")\n new_version.classname = request.form[\"classname\"]\n new_version.code = request.form[\"code\"]\n\n max_version, = db.session.query(func.max(\n JobTypeVersion.version)).filter_by(jobtype=jobtype).first()\n new_version.version = (max_version or 0) + 1\n\n previous_version = JobTypeVersion.query.filter_by(\n jobtype=jobtype).order_by(desc(JobTypeVersion.version)).first()\n if previous_version:\n for requirement in previous_version.software_requirements:\n new_requirement = JobTypeSoftwareRequirement()\n new_requirement.jobtype_version = new_version\n new_requirement.software = requirement.software\n new_requirement.min_version = requirement.min_version\n new_requirement.max_version = requirement.max_version\n db.session.add(new_requirement)\n\n db.session.add(jobtype)\n db.session.add(new_version)\n db.session.commit()\n\n flash(\"Jobtype %s updated to version %s\" %\n (jobtype.name, new_version.version))\n\n return redirect(url_for(\"single_jobtype_ui\", jobtype_id=jobtype.id),\n SEE_OTHER)\n\n else:\n latest_version = JobTypeVersion.query.filter_by(\n jobtype=jobtype).order_by(desc(JobTypeVersion.version)).first()\n if not latest_version:\n return (render_template(\n \"pyfarm/error.html\", error=\"Jobtype %s has no versions\" %\n jobtype_id), INTERNAL_SERVER_ERROR)\n\n\n return render_template(\"pyfarm/user_interface/jobtype.html\",\n jobtype=jobtype, latest_version=latest_version,\n software_items=Software.query)\n\ndef remove_jobtype_software_requirement(jobtype_id, software_id):\n with db.session.no_autoflush:\n jobtype = JobType.query.filter_by(id=jobtype_id).first()\n if not jobtype:\n return (render_template(\n \"pyfarm/error.html\", error=\"Jobtype %s not found\" %\n jobtype_id), NOT_FOUND)\n\n previous_version = JobTypeVersion.query.filter_by(\n jobtype=jobtype).order_by(desc(JobTypeVersion.version)).first()\n if not previous_version:\n return (render_template(\n \"pyfarm/error.html\", error=\"Jobtype %s has no versions\" %\n jobtype_id), INTERNAL_SERVER_ERROR)\n\n new_version = JobTypeVersion(jobtype=jobtype)\n new_version.max_batch = previous_version.max_batch or sql.null()\n new_version.batch_contiguous = previous_version.batch_contiguous\n new_version.no_automatic_start_time =\\\n previous_version.no_automatic_start_time\n new_version.classname = previous_version.classname\n new_version.code = previous_version.code\n new_version.version = previous_version.version + 1\n\n for requirement in previous_version.software_requirements:\n if requirement.software_id != software_id:\n new_requirement = JobTypeSoftwareRequirement()\n new_requirement.jobtype_version = new_version\n new_requirement.software = requirement.software\n new_requirement.min_version = requirement.min_version\n new_requirement.max_version = requirement.max_version\n db.session.add(new_requirement)\n\n db.session.commit()\n\n flash(\"Software requirement has been removed from jobtype %s\" %\n jobtype.name)\n\n return redirect(url_for(\"single_jobtype_ui\", jobtype_id=jobtype.id),\n SEE_OTHER)\n\ndef add_jobtype_software_requirement(jobtype_id):\n with db.session.no_autoflush:\n jobtype = JobType.query.filter_by(id=jobtype_id).first()\n if not jobtype:\n return (render_template(\n \"pyfarm/error.html\", error=\"Jobtype %s not found\" %\n jobtype_id), NOT_FOUND)\n\n previous_version = JobTypeVersion.query.filter_by(\n jobtype=jobtype).order_by(desc(JobTypeVersion.version)).first()\n if not previous_version:\n return (render_template(\n \"pyfarm/error.html\", error=\"Jobtype %s has no versions\" %\n jobtype_id), INTERNAL_SERVER_ERROR)\n\n new_version = JobTypeVersion(jobtype=jobtype)\n new_version.max_batch = previous_version.max_batch or sql.null()\n new_version.batch_contiguous = previous_version.batch_contiguous\n new_version.no_automatic_start_time =\\\n previous_version.no_automatic_start_time\n new_version.classname = previous_version.classname\n new_version.code = previous_version.code\n new_version.version = previous_version.version + 1\n\n for requirement in previous_version.software_requirements:\n retained_requirement = JobTypeSoftwareRequirement()\n retained_requirement.jobtype_version = new_version\n retained_requirement.software = requirement.software\n retained_requirement.min_version = requirement.min_version\n retained_requirement.max_version = requirement.max_version\n db.session.add(retained_requirement)\n\n new_requirement = JobTypeSoftwareRequirement()\n new_requirement.jobtype_version = new_version\n\n new_requirement_software = Software.query.filter_by(\n id=request.form[\"software\"]).first()\n if not new_requirement_software:\n return (render_template(\n \"pyfarm/error.html\", error=\"Software %s not found\" %\n request.form[\"software\"]), NOT_FOUND)\n new_requirement.software = new_requirement_software\n\n if request.form[\"minimum_version\"] != \"\":\n min_version = SoftwareVersion.query.filter_by(\n id=request.form[\"minimum_version\"]).first()\n if not min_version:\n return (render_template(\n \"pyfarm/error.html\", error=\"Software version %s not \"\n \"found\" % request.form[\"minimum_version\"]), NOT_FOUND)\n if min_version.software != new_requirement_software:\n return (render_template(\n \"pyfarm/error.html\", error=\"Software version %s does \"\n \"not belong to software %s\" %\n (min_version.version,\n new_requirement_software.software)), BAD_REQUEST)\n new_requirement.min_version = min_version\n\n if request.form[\"maximum_version\"] != \"\":\n max_version = SoftwareVersion.query.filter_by(\n id=request.form[\"maximum_version\"]).first()\n if not max_version:\n return (render_template(\n \"pyfarm/error.html\", error=\"Software version %s not \"\n \"found\" % request.form[\"maximum_version\"]), NOT_FOUND)\n if max_version.software != new_requirement_software:\n return (render_template(\n \"pyfarm/error.html\", error=\"Software version %s does \"\n \"not belong to software %s\" %\n (max_version.version,\n new_requirement_software.software)), BAD_REQUEST)\n new_requirement.max_version = max_version\n\n db.session.add(new_version)\n db.session.add(new_requirement)\n db.session.commit()\n\n flash(\"Software requirement has been added to jobtype %s\" %\n jobtype.name)\n\n return redirect(url_for(\"single_jobtype_ui\", jobtype_id=jobtype.id),\n SEE_OTHER)\n\ndef remove_jobtype(jobtype_id):\n with db.session.no_autoflush:\n jobtype = JobType.query.filter_by(id=jobtype_id).first()\n if not jobtype:\n return (render_template(\n \"pyfarm/error.html\", error=\"Jobtype %s not found\" %\n jobtype_id), NOT_FOUND)\n\n for version in jobtype.versions:\n if version.jobs.count() > 0:\n return (render_template(\n \"pyfarm/error.html\", error=\"Jobtype %s cannot be deleted \"\n \"because there are still jobs referencing it. Please \"\n \"delete those jobs first.\" % jobtype.name), BAD_REQUEST)\n\n db.session.delete(jobtype)\n db.session.commit()\n\n return redirect(url_for(\"jobtypes_index_ui\"), SEE_OTHER)\n\ndef create_jobtype():\n if request.method == \"GET\":\n return render_template(\"pyfarm/user_interface/jobtype_create.html\",\n jobtypes=JobType.query,\n software_items=Software.query)\n else:\n with db.session.no_autoflush:\n jobtype = JobType()\n jobtype.name = request.form[\"name\"]\n jobtype.description = request.form[\"description\"]\n jobtype_version = JobTypeVersion()\n jobtype_version.jobtype = jobtype\n jobtype_version.version = 1\n jobtype_version.max_batch = request.form[\"max_batch\"].strip() or\\\n sql.null()\n jobtype_version.batch_contiguous =\\\n (\"batch_contiguous\" in request.form and\n request.form[\"batch_contiguous\"] == \"true\")\n jobtype_version.no_automatic_start_time =\\\n (\"no_automatic_start_time\" in request.form and\n request.form[\"no_automatic_start_time\"] == \"true\")\n jobtype_version.classname = request.form[\"classname\"]\n jobtype_version.code = request.form[\"code\"]\n\n requirements = zip(request.form.getlist(\"software\"),\n request.form.getlist(\"min_version\"),\n request.form.getlist(\"min_version\"))\n\n for requirement_tuple in requirements:\n software = Software.query.filter_by(\n id=int(requirement_tuple[0])).first()\n if not software:\n return (render_template(\n \"pyfarm/error.html\", error=\"Software %s not found\" %\n requirement_tuple[0]), NOT_FOUND)\n requirement = JobTypeSoftwareRequirement()\n requirement.software = software\n requirement.jobtype_version = jobtype_version\n\n if requirement_tuple[1] != \"\":\n minimum_version = SoftwareVersion.query.filter_by(\n id=int(requirement_tuple[1])).first()\n if not minimum_version:\n return (render_template(\n \"pyfarm/error.html\", error=\"Software version %s not \"\n \"found\" % requirement_tuple[1]), NOT_FOUND)\n if minimum_version.software != software:\n return (render_template(\n \"pyfarm/error.html\", error=\"Software version %s \"\n \"does not belong to software %s\" %\n (minimum_version.version, software.software)),\n BAD_REQUEST)\n requirement.min_version = minimum_version\n\n if requirement_tuple[2] != \"\":\n maximum_version = SoftwareVersion.query.filter_by(\n id=int(requirement_tuple[2])).first()\n if not maximum_version:\n return (render_template(\n \"pyfarm/error.html\", error=\"Software version %s not \"\n \"found\" % requirement_tuple[2]), NOT_FOUND)\n if maximum_version.software != software:\n return (render_template(\n \"pyfarm/error.html\", error=\"Software version %s \"\n \"does not belong to software %s\" %\n (maximum_version.version, software.software)),\n BAD_REQUEST)\n requirement.max_version = maximum_version\n\n db.session.add(requirement)\n\n db.session.add(jobtype)\n db.session.add(jobtype_version)\n db.session.commit()\n\n flash(\"Jobtype %s created\" % jobtype.name)\n\n return redirect(url_for('jobtypes_index_ui'), SEE_OTHER)\n\ndef update_jobtype_notification_templates(jobtype_id):\n with db.session.no_autoflush:\n jobtype = JobType.query.filter_by(id=jobtype_id).first()\n if not jobtype:\n return (render_template(\n \"pyfarm/error.html\", error=\"Jobtype %s not found\" %\n jobtype_id), NOT_FOUND)\n\n if \"success_subject\" in request.form:\n if request.form[\"success_subject\"].strip() != \"\":\n jobtype.success_subject = request.form[\"success_subject\"]\n else:\n jobtype.success_subject = sql.null()\n if \"success_body\" in request.form:\n if request.form[\"success_body\"].strip() != \"\":\n jobtype.success_body = request.form[\"success_body\"]\n else:\n jobtype.success_body = sql.null()\n if \"failure_subject\" in request.form:\n if request.form[\"failure_subject\"].strip() != \"\":\n jobtype.fail_subject = request.form[\"failure_subject\"]\n else:\n jobtype.fail_subject = sql.null()\n if \"failure_body\" in request.form:\n if request.form[\"failure_body\"].strip() != \"\":\n jobtype.fail_body = request.form[\"failure_body\"]\n else:\n jobtype.fail_body = sql.null()\n\n db.session.add(jobtype)\n db.session.commit()\n\n flash(\"Notification templates for jobtype %s updated\" % jobtype.name)\n\n return redirect(url_for(\"single_jobtype_ui\", jobtype_id=jobtype.id),\n SEE_OTHER)\n","sub_path":"pyfarm/master/user_interface/jobtypes.py","file_name":"jobtypes.py","file_ext":"py","file_size_in_byte":16431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"529822446","text":"'''\nInput: a List of integers\nReturns: a List of integers\n'''\ndef moving_zeroes(arr):\n # iterate over the array\n # if we find a zero, swap with the last non-zero value in the array\n last = len(arr)-1\n cur = 0\n\n while cur < last:\n if arr[cur] == 0:\n while arr[last] == 0 and cur < last:\n last -= 1\n if arr[last] != 0:\n arr[cur], arr[last] = arr[last], arr[cur]\n else:\n break\n cur += 1\n\n return arr\n\n\nif __name__ == '__main__':\n # Use the main function here to test out your implementation\n arr = [0, 3, 1, 0, -2]\n\n print(f\"The resulting of moving_zeroes is: {moving_zeroes(arr)}\")","sub_path":"moving_zeroes/moving_zeroes.py","file_name":"moving_zeroes.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"7425655","text":"# Copyright (c) 2017 OpenStack Foundation.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nimport netaddr\nfrom oslo_log import log\nfrom ryu.ofproto import ether\n\nfrom dragonflow._i18n import _LI\nfrom dragonflow.common import constants as df_common_const\nfrom dragonflow.common import utils as df_utils\nfrom dragonflow.controller import base_snat_app\nfrom dragonflow.controller.common import constants as const\n\nLOG = log.getLogger(__name__)\n\n\nclass TenantSNATApp(base_snat_app.BaseSNATApp):\n \"\"\"Implements tenant based IP allocation strategy for all hosted VMs\n\n Methods provide strategy specific operations\n\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(TenantSNATApp, self).__init__(*args, **kwargs)\n self.tenant_cache = {}\n\n def ovs_port_updated_helper(self):\n ports = self.db_store.get_ports_by_chassis(self.chassis)\n parser = self.parser\n for lport in ports:\n if self.is_data_port(lport):\n tenant_id = lport.get_topic()\n tenant_info = self.tenant_cache[tenant_id]\n ext_host_mac = tenant_info['external_host_mac']\n match = parser.OFPMatch(eth_type=ether.ETH_TYPE_IP,\n reg6=lport.get_unique_key())\n self._install_snat_egress_after_conntrack(match,\n ext_host_mac)\n\n def install_strategy_based_flows(self):\n super(TenantSNATApp, self).install_strategy_based_flows()\n\n def install_lport_based_flows(self, lport):\n # instance specific flows\n tenant_id = lport.get_topic()\n if tenant_id in self.tenant_cache:\n tenant_info = self.tenant_cache[tenant_id]\n ext_host_ip = tenant_info['external_host_ip']\n ext_host_mac = tenant_info['external_host_mac']\n count = tenant_info['count']\n self.tenant_cache[tenant_id] = {\n 'count': (count + 1),\n 'external_host_ip': ext_host_ip,\n 'external_host_mac': ext_host_mac}\n else:\n ext_host_ip, ext_host_mac = \\\n self._extract_local_gateway_info(lport)\n # install ARP responder\n self._install_arp_responder(ext_host_ip, ext_host_mac)\n self.tenant_cache[tenant_id] = {\n 'count': 1,\n 'external_host_ip': ext_host_ip,\n 'external_host_mac': ext_host_mac}\n\n self._install_snat_ingress_after_conntrack(\n lport.get_unique_key(),\n lport.get_mac(),\n ext_host_mac)\n\n parser = self.parser\n match = parser.OFPMatch(\n eth_type=ether.ETH_TYPE_IP,\n reg6=lport.get_unique_key())\n self._install_snat_egress_conntrack(match, ext_host_ip)\n\n match = parser.OFPMatch(\n eth_type=ether.ETH_TYPE_IP,\n reg6=lport.get_unique_key())\n self._install_snat_egress_after_conntrack(match, ext_host_mac)\n\n def remove_strategy_based_flows(self):\n super(TenantSNATApp, self).remove_strategy_based_flows()\n\n def remove_lport_based_flows(self, lport):\n # remove arp responder on last tenant instance\n tenant_id = lport.get_topic()\n tenant_info = self.tenant_cache[tenant_id]\n count = tenant_info['count']\n count -= 1\n if count == 0:\n self._remove_arp_responder(\n tenant_info['external_host_ip'],\n tenant_info['external_host_mac'])\n\n self.tenant_cache.pop(tenant_id, None)\n else:\n self.tenant_cache[tenant_id] = {\n 'count': count,\n 'external_host_ip': tenant_info['external_host_ip'],\n 'external_host_mac': tenant_info['external_host_mac']}\n\n parser = self.parser\n ofproto = self.ofproto\n\n match = parser.OFPMatch(\n eth_type=ether.ETH_TYPE_IP,\n ct_mark=int(lport.get_unique_key()))\n self.mod_flow(\n command=ofproto.OFPFC_DELETE_STRICT,\n table_id=const.INGRESS_NAT2_TABLE,\n priority=const.PRIORITY_LOW,\n match=match)\n\n match = parser.OFPMatch(\n eth_type=ether.ETH_TYPE_IP,\n reg6=lport.get_unique_key())\n self.mod_flow(\n command=ofproto.OFPFC_DELETE_STRICT,\n table_id=const.EGRESS_NAT_TABLE,\n priority=const.PRIORITY_LOW,\n match=match)\n\n match = parser.OFPMatch(\n eth_type=ether.ETH_TYPE_IP,\n reg6=lport.get_unique_key())\n self.mod_flow(\n command=ofproto.OFPFC_DELETE_STRICT,\n table_id=const.EGRESS_NAT2_TABLE,\n priority=const.PRIORITY_LOW,\n match=match)\n\n def _find_local_tenant_port(self, port,\n owner_list_name,\n exclude_self=False):\n LOG.debug(\"Search port with owner in list: '%s'\", owner_list_name)\n tenant_ports = self.nb_api.get_all_logical_ports(port.get_topic())\n for lport in tenant_ports:\n if exclude_self is True and lport.get_id() == port.get_id():\n continue\n if (lport.get_chassis() == port.get_chassis() and\n df_utils.is_port_owner_of_type(\n lport.get_device_owner(),\n owner_list_name)):\n LOG.debug(\"Found reference port\")\n return lport\n\n return None\n\n def _extract_local_gateway_info(self, port):\n gw_port = self._find_local_tenant_port(port,\n df_common_const.LGW_DEVICE_OWNER)\n\n external_host_ip = None\n external_host_mac = None\n if gw_port is not None:\n ips = [ip['ip_address'] for ip in gw_port.get('fixed_ips', [])]\n for tmp_ip in ips:\n if netaddr.IPAddress(tmp_ip).version == 4:\n external_host_ip = tmp_ip\n external_host_mac = gw_port.get('mac_address')\n LOG.info(_LI(\"Extracted %(ip)s, %(mac)s\"),\n {'ip': external_host_ip,\n 'mac': external_host_mac})\n break\n\n return external_host_ip, external_host_mac\n","sub_path":"dragonflow/controller/tenant_snat_app.py","file_name":"tenant_snat_app.py","file_ext":"py","file_size_in_byte":6923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"490760007","text":"from collective.transmogrifier.interfaces import ISection\nfrom collective.transmogrifier.interfaces import ISectionBlueprint\nfrom collective.transmogrifier.utils import defaultMatcher\nfrom ftw.mail.mail import IMail\nfrom mimetypes import guess_type\nfrom opengever.bundle.sections.bundlesource import BUNDLE_KEY\nfrom opengever.bundle.sections.bundlesource import BUNDLE_PATH_KEY\nfrom opengever.document.document import IDocumentSchema\nfrom opengever.document.subscribers import set_digitally_available\nfrom opengever.document.subscribers import sync_title_and_filename_handler\nfrom opengever.mail.mail import initalize_title\nfrom opengever.mail.mail import initialize_metadata\nfrom opengever.mail.mail import NO_SUBJECT_TITLE_FALLBACK\nfrom zope.annotation.interfaces import IAnnotations\nfrom zope.interface import classProvides\nfrom zope.interface import implements\nimport logging\nimport ntpath\nimport os.path\nimport posixpath\n\n\nlogger = logging.getLogger('opengever.setup.sections.fileloader')\n\n\nINVALID_FILE_EXTENSIONS = ('.msg', '.exe', '.dll')\n\n\nclass FileLoaderSection(object):\n \"\"\"Stores file data directly in already constructed content items.\"\"\"\n\n classProvides(ISectionBlueprint)\n implements(ISection)\n\n def __init__(self, transmogrifier, name, options, previous):\n self.previous = previous\n self.context = transmogrifier.context\n\n # TODO: Might want to also use defaultMatcher for this key to make it\n # configurable instead of hard coding it here.\n self.key = 'filepath'\n self.pathkey = defaultMatcher(options, 'path-key', name, 'path')\n\n self.bundle = IAnnotations(transmogrifier)[BUNDLE_KEY]\n self.bundle_path = IAnnotations(transmogrifier)[BUNDLE_PATH_KEY]\n\n self.bundle.errors['files_not_found'] = []\n self.bundle.errors['files_io_errors'] = []\n self.bundle.errors['files_unresolvable_path'] = []\n self.bundle.errors['files_invalid_types'] = []\n self.bundle.errors['unmapped_unc_mounts'] = set()\n\n def is_mail(self, item):\n return item['_type'] == 'ftw.mail.mail'\n\n def _is_absolute_path(self, path):\n if posixpath.isabs(path):\n return True\n\n if ntpath.isabs(path):\n return True\n\n return False\n\n def _is_unc_path(self, filepath):\n return filepath.startswith('\\\\\\\\')\n\n def _translate_unc_path(self, filepath):\n ingestion_settings = self.bundle.ingestion_settings\n unc_mount_mapping = ingestion_settings.get('unc_mounts', {})\n mount, rest = ntpath.splitunc(filepath)\n\n if mount not in unc_mount_mapping:\n logger.warning('UNC mount %s is not mapped!' % mount)\n self.bundle.errors['unmapped_unc_mounts'].add((mount, ))\n return None\n\n # posix_mountpoint is the location where the fileshare has been\n # mounted on the POSIX system (Linux / OS X)\n posix_mountpoint = unc_mount_mapping[mount]\n relative_path = rest.replace('\\\\', '/').lstrip('/')\n abs_filepath = os.path.join(posix_mountpoint, relative_path)\n return abs_filepath\n\n def build_absolute_filepath(self, filepath):\n if not self._is_absolute_path(filepath):\n filepath = os.path.join(self.bundle_path, filepath)\n\n if self._is_unc_path(filepath):\n filepath = self._translate_unc_path(filepath)\n\n return filepath\n\n def __iter__(self):\n for item in self.previous:\n guid = item['guid']\n\n if self.is_mail(item):\n file_field = IMail['message']\n else:\n file_field = IDocumentSchema['file']\n\n keys = item.keys()\n pathkey = self.pathkey(*keys)[0]\n\n if self.key in item:\n _filepath = item[self.key]\n if _filepath is None:\n yield item\n continue\n\n if pathkey not in item:\n logger.warning(\"Missing path key for file %s\" % _filepath)\n yield item\n continue\n path = item[pathkey]\n\n abs_filepath = self.build_absolute_filepath(_filepath)\n if abs_filepath is None:\n logger.warning('Unresolvable filepath: %s' % _filepath)\n error = (guid, _filepath, path)\n self.bundle.errors['files_unresolvable_path'].append(error)\n yield item\n continue\n\n filename = os.path.basename(abs_filepath)\n if isinstance(filename, str):\n filename = filename.decode('utf8')\n\n # TODO: Check for this in OGGBundle validation\n if any(abs_filepath.lower().endswith(ext) for ext in INVALID_FILE_EXTENSIONS): # noqa\n logger.warning(\n \"Skipping file with invalid type: %s\" % abs_filepath)\n error = (guid, abs_filepath, path)\n self.bundle.errors['files_invalid_types'].append(error)\n yield item\n continue\n\n # TODO: Check for this in OGGBundle validation\n if not os.path.exists(abs_filepath):\n logger.warning(\"File not found: %s\" % abs_filepath)\n error = (guid, abs_filepath, path)\n self.bundle.errors['files_not_found'].append(error)\n yield item\n continue\n\n mimetype, _encoding = guess_type(abs_filepath, strict=False)\n if mimetype is None:\n logger.warning(\n \"Unknown mimetype for file %s\" % abs_filepath)\n mimetype = 'application/octet-stream'\n\n obj = item.get('_object')\n if obj is None:\n logger.warning(\n \"Cannot set file. Document %s doesn't exist.\" % path)\n yield item\n continue\n\n try:\n with open(abs_filepath, 'rb') as f:\n namedblobfile = file_field._type(\n data=f.read(),\n contentType=mimetype,\n filename=filename)\n setattr(obj, file_field.getName(), namedblobfile)\n except EnvironmentError as e:\n # TODO: Check for this in OGGBundle validation\n logger.warning(\"Can't open file %s. %s.\" % (\n abs_filepath, str(e)))\n error = (guid, abs_filepath, str(e), path)\n self.bundle.errors['files_io_errors'].append(error)\n yield item\n continue\n\n # Fire these event handlers manually because they got fired\n # too early before (when the file contents weren't loaded yet)\n if self.is_mail(item):\n initialize_metadata(obj, None)\n\n if obj.title == NO_SUBJECT_TITLE_FALLBACK:\n # Reset the [No Subject] placeholder\n obj.title = None\n initalize_title(obj, None)\n else:\n sync_title_and_filename_handler(obj, None)\n set_digitally_available(obj, None)\n\n yield item\n","sub_path":"opengever/bundle/sections/fileloader.py","file_name":"fileloader.py","file_ext":"py","file_size_in_byte":7426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"76601775","text":"# bitcoin address clipboard swapper\n\n# bitcoin address validation:\n# they are 26-35 alphanumeric characters\n# they begin with '1' or '3' or 'bc1'\n# the do not contain uppercase 'O', number '0', lowercase 'l' and uppercase 'I'\n\nimport clipboard\nimport time\n\ndef get_clipboard():\n # store clipboard value\n data = str(clipboard.paste())\n \n # validate bitcoin address\n if 26 < len(data) < 35:\n if (data[0] == '1' or '3' or 'bc1'): \n for i in str(data):\n if (i == ('O' or '0' or 'I' or 'l')):\n break;\n else:\n # swap address\n swap_address(str(data))\n \n#set clipoboard data\ndef swap_address(data):\n clipboard.copy(\"my_bitcoin_address\")\n\n\nwhile True:\n get_clipboard()\n time.sleep(2)\n","sub_path":"btc-address(clipboard)-swapper/btc-address(clipboard)-swapper.py","file_name":"btc-address(clipboard)-swapper.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"652940665","text":"#!/usr/bin/env python3\n\nimport io\nimport os\nimport pathlib\nimport sys\nfrom zipfile import ZipFile\n\nimport requests\n\nDEFAULT_URL = 'https://questionsacm.isograd.com/codecontest/sample_input_output/sample-lJdOuPUVRty107MkPy5Em4OWCFIWHYf6rV_gf6jAgU4.zip'\n\n# Make paths relative to the folder containing the script so that it can be called from anywhere\nsrc_dir = pathlib.Path(os.path.dirname(os.path.abspath(__file__)))\ndata_dir = pathlib.Path(src_dir / '../data/')\nzip_filepath = data_dir / 'data.zip'\nurl = sys.argv[1] if len(sys.argv) >= 2 else DEFAULT_URL\n\n# Get zip from url\nprint('Downloading zip file from {}'.format(url))\nresponse = requests.get(url)\nif not response:\n exit('Invalid response, got status code {}'.format(response.status_code))\nzip_file = ZipFile(io.BytesIO(requests.get(url).content))\n\n# Delete existing txt files from data folder\nprint('Deleting .txt and .out files from data folder')\ntxt_files = os.listdir(data_dir)\nfor file in txt_files:\n if file.endswith('.txt') or file.endswith('.out'):\n os.remove(data_dir / file)\n\n# Extract .txt files to data folder\nprint('Extracting individual text files to data folder')\nfor file_name in zip_file.namelist():\n if file_name.endswith('.txt'):\n base_name = pathlib.PurePath(file_name).name\n print('Extracting file from archive as {}'.format(base_name))\n with open(data_dir / base_name, 'wb') as f_out:\n f_out.write(zip_file.read(file_name))\n else:\n print('Ignoring non txt file {}'.format(file_name))\n","sub_path":"src/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"125268628","text":"from datetime import datetime\r\nimport shutil\r\nimport os\r\n\r\nlocal_path = \"f:\\\\sqlbackup\"\r\n\r\nunc_path = \"//pdc/backup/sqlbackup\"\r\n\r\n\r\ndef copy_dir(dir, add):\r\n unc_add = \"/\" + add[1:]\r\n for f in os.listdir(dir):\r\n if f.endswith in (\".diff\", \".trn\", \".weekly\", \".nightly\"):\r\n full_path = os.path.join(dir, f)\r\n if os.path.isfile(full_path):\r\n time_now = datetime.now()\r\n text_str = time_now.strftime('%d-%m-%Y %H:%M:%S') + \\\r\n \" Copying \" + f + \" ---> \" + unc_path + unc_add + \"\\n\"\r\n with open(\"copy_sql_bckp.log\", 'a') as file:\r\n file.write(text_str)\r\n shutil.copy2(full_path, unc_path + unc_add)\r\n\r\n\r\nif __name__ == '__main__':\r\n for i in (\"\\\\b1\", \"\\\\b2\", \"\\\\trade\", \"\\\\unf\"):\r\n copy_dir(local_path + i, i)\r\n","sub_path":"copy_to_pdc.py","file_name":"copy_to_pdc.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"324298416","text":"\n#Reducer.py\nimport sys\nimport operator\nfrom collections import OrderedDict\n\nmov_dat = {}\n\ndat = []\n#Partitoner\nfor line in sys.stdin:\n\tline = line.strip()\n\tsplit = line.split('::')\n\tif len(split)==3:\n\t\tprint(\"%s\\t%s\\t%s\"%(split[0],split[1],split[2]))\n\telse:\n\t\tprint(\"%s\\t%s\\t%s\\t%s\"%(split[0],split[1],split[2],split[3]))\n","sub_path":"Hadoop - MapReduce/mapper_rating.py","file_name":"mapper_rating.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"463944828","text":"# -*- coding: utf-8 -*-\n\"\"\"Implementation of the ``somatic_variant_annotation`` step\n\nThe ``somatic_variant_annotation`` step takes as the input the results of the\n``somatic_variant_calling`` step (bgzip-ed and indexed VCF files) and performs annotation of the\nsomatic variants. The result are annotated versions of the somatic variant VCF files (again\nbgzip-ed and indexed VCF files).\n\n==========\nStep Input\n==========\n\nThe somatic variant annotation step uses Snakemake sub workflows for using the result of the\n``somatic_variant_calling`` step.\n\nThe main assumption is that each VCF file contains the two matched normal and tumor samples.\n\n==========\nStep Input\n==========\n\nThe variant annotation step uses Snakemake sub workflows for using the result of the\n``variant_calling`` step.\n\n===========\nStep Output\n===========\n\nTODO\n\n====================\nGlobal Configuration\n====================\n\nTODO\n\n=====================\nDefault Configuration\n=====================\n\nThe default configuration is as follows.\n\n.. include:: DEFAULT_CONFIG_variant_annotation.rst\n\n=======\nReports\n=======\n\nCurrently, no reports are generated.\n\"\"\"\n\nfrom collections import OrderedDict\nimport os\nimport sys\n\nfrom biomedsheets.shortcuts import CancerCaseSheet, CancerCaseSheetOptions, is_not_background\nfrom snakemake.io import expand\n\nfrom snappy_pipeline.utils import dictify, listify\nfrom snappy_pipeline.workflows.abstract import BaseStep, BaseStepPart, LinkOutStepPart\nfrom snappy_pipeline.workflows.ngs_mapping import NgsMappingWorkflow\nfrom snappy_pipeline.workflows.somatic_variant_calling import (\n SOMATIC_VARIANT_CALLERS_JOINT,\n SOMATIC_VARIANT_CALLERS_MATCHED,\n SomaticVariantCallingWorkflow,\n)\n\n__author__ = \"Manuel Holtgrewe <manuel.holtgrewe@bihealth.de>\"\n\n#: Extensions of files to create as main payload\nEXT_VALUES = (\".vcf.gz\", \".vcf.gz.tbi\", \".vcf.gz.md5\", \".vcf.gz.tbi.md5\")\n\n#: Names of the files to create for the extension\nEXT_NAMES = (\"vcf\", \"tbi\", \"vcf_md5\", \"tbi_md5\")\n\n#: Default configuration for the somatic_variant_calling step\nDEFAULT_CONFIG = r\"\"\"\n# Default configuration variant_annotation\nstep_config:\n somatic_variant_annotation:\n drmaa_snippet: '' # value to pass in as additional DRMAA arguments\n window_length: 50000000 # split input into windows of this size, each triggers a job\n num_jobs: 100 # number of windows to process in parallel\n use_drmaa: true # use DRMAA for parallel processing\n restart_times: 5 # number of times to re-launch jobs in case of failure\n max_jobs_per_second: 10 # throttling of job creation\n max_status_checks_per_second: 10 # throttling of status checks\n ignore_chroms: # patterns of chromosome names to ignore\n - NC_007605 # herpes virus\n - hs37d5 # GRCh37 decoy\n - chrEBV # Eppstein-Barr Virus\n - 'GL*' # problematic unplaced loci\n - '*_decoy' # decoy contig\n - 'HLA-*' # HLA genes\n use_advanced_ped_filters: false # whether or not to use the advanced pedigree filters flag\n path_somatic_variant_calling: ../somatic_variant_calling # REQUIRED\n path_jannovar_ser: REQUIRED # REQUIRED\n flag_off_target: False # REQUIRED\n tools_ngs_mapping: [] # default to those configured for ngs_mapping\n tools_somatic_variant_calling: [] # default to those configured for somatic_variant_calling\n dbnsfp: # configuration for default genome release, needs change if differing\n col_contig: 1\n col_pos: 2\n columns: []\n annotation_tracks_bed: []\n annotation_tracks_tsv: []\n annotation_tracks_vcf: []\n\"\"\"\n\n\nclass JannovarAnnotateSomaticVcfStepPart(BaseStepPart):\n \"\"\"Annotate VCF file from somatic calling using \"Jannovar annotate-vcf\"\n\n .. note:\n\n The ``tumor_library`` wildcard can actually be the name of a donor!\n \"\"\"\n\n name = \"jannovar\"\n\n def __init__(self, parent):\n super().__init__(parent)\n # Build shortcut from cancer bio sample name to matched cancre sample\n self.tumor_ngs_library_to_sample_pair = OrderedDict()\n for sheet in self.parent.shortcut_sheets:\n self.tumor_ngs_library_to_sample_pair.update(\n sheet.all_sample_pairs_by_tumor_dna_ngs_library\n )\n # Build mapping from donor name to donor.\n self.donors = OrderedDict()\n for sheet in self.parent.shortcut_sheets:\n for donor in sheet.donors:\n self.donors[donor.name] = donor\n\n @dictify\n def get_input_files(self, action):\n \"\"\"Return path to pedigree input file\"\"\"\n assert action == \"annotate_somatic_vcf\"\n tpl = (\n \"output/{mapper}.{var_caller}.{tumor_library}/out/\"\n \"{mapper}.{var_caller}.{tumor_library}\"\n )\n KEY_EXT = {\"vcf\": \".vcf.gz\", \"tbi\": \".vcf.gz.tbi\"}\n variant_calling = self.parent.sub_workflows[\"somatic_variant_calling\"]\n for key, ext in KEY_EXT.items():\n yield key, variant_calling(tpl + ext)\n\n @dictify\n def get_output_files(self, action):\n \"\"\"Return output files for the filtration\"\"\"\n assert action == \"annotate_somatic_vcf\"\n prefix = (\n \"work/{mapper}.{var_caller}.jannovar_annotate_somatic_vcf.{tumor_library}/out/\"\n \"{mapper}.{var_caller}.jannovar_annotate_somatic_vcf.{tumor_library}\"\n )\n KEY_EXT = {\"vcf\": \".vcf.gz\", \"tbi\": \".vcf.gz.tbi\"}\n for key, ext in KEY_EXT.items():\n yield key, prefix + ext\n yield key + \"_md5\", prefix + ext + \".md5\"\n\n @dictify\n def _get_log_file(self, action):\n \"\"\"Return mapping of log files.\"\"\"\n assert action == \"annotate_somatic_vcf\"\n prefix = (\n \"work/{mapper}.{var_caller}.jannovar_annotate_somatic_vcf.{tumor_library}/log/\"\n \"{mapper}.{var_caller}.jannovar_annotate_somatic_vcf.{tumor_library}\"\n )\n\n key_ext = (\n (\"log\", \".log\"),\n (\"conda_info\", \".conda_info.txt\"),\n (\"conda_list\", \".conda_list.txt\"),\n )\n for key, ext in key_ext:\n yield key, prefix + ext\n\n def get_params(self, action):\n \"\"\"Return arguments to pass down.\"\"\"\n\n def params_function(wildcards):\n if wildcards.tumor_library not in self.donors:\n return {\n \"tumor_library\": wildcards.tumor_library,\n \"normal_library\": self.get_normal_lib_name(wildcards),\n }\n else:\n return {}\n\n return params_function\n\n def get_normal_lib_name(self, wildcards):\n \"\"\"Return name of normal (non-cancer) library\"\"\"\n pair = self.tumor_ngs_library_to_sample_pair[wildcards.tumor_library]\n return pair.normal_sample.dna_ngs_library.name\n\n @classmethod\n def update_cluster_config(cls, cluster_config):\n \"\"\"Update cluster configuration with resource requirements\"\"\"\n cluster_config[\"somatic_variant_annotation_jannovar_annotate_somatic_vcf\"] = {\n \"mem\": 8 * 1024 * 2,\n \"time\": \"100:00\",\n \"ntasks\": 2,\n }\n\n\nclass SomaticVariantAnnotationWorkflow(BaseStep):\n \"\"\"Perform germline variant annotation\"\"\"\n\n name = \"somatic_variant_annotation\"\n sheet_shortcut_class = CancerCaseSheet\n sheet_shortcut_kwargs = {\n \"options\": CancerCaseSheetOptions(allow_missing_normal=True, allow_missing_tumor=True)\n }\n\n @classmethod\n def default_config_yaml(cls):\n \"\"\"Return default config YAML, to be overwritten by project-specific one.\"\"\"\n return DEFAULT_CONFIG\n\n def __init__(\n self, workflow, config, cluster_config, config_lookup_paths, config_paths, workdir\n ):\n super().__init__(\n workflow,\n config,\n cluster_config,\n config_lookup_paths,\n config_paths,\n workdir,\n (SomaticVariantCallingWorkflow, NgsMappingWorkflow),\n )\n # Register sub step classes so the sub steps are available\n self.register_sub_step_classes((JannovarAnnotateSomaticVcfStepPart, LinkOutStepPart))\n # Register sub workflows\n self.register_sub_workflow(\n \"somatic_variant_calling\", self.config[\"path_somatic_variant_calling\"]\n )\n # Copy over \"tools\" setting from somatic_variant_calling/ngs_mapping if not set here\n if not self.config[\"tools_ngs_mapping\"]:\n self.config[\"tools_ngs_mapping\"] = self.w_config[\"step_config\"][\"ngs_mapping\"][\"tools\"][\n \"dna\"\n ]\n if not self.config[\"tools_somatic_variant_calling\"]:\n self.config[\"tools_somatic_variant_calling\"] = self.w_config[\"step_config\"][\n \"somatic_variant_calling\"\n ][\"tools\"]\n\n @listify\n def get_result_files(self):\n \"\"\"Return list of result files for the NGS mapping workflow\n\n We will process all primary DNA libraries and perform joint calling within pedigrees\n \"\"\"\n callers = set(self.config[\"tools_somatic_variant_calling\"])\n name_pattern = \"{mapper}.{caller}.jannovar_annotate_somatic_vcf.{tumor_library.name}\"\n yield from self._yield_result_files_matched(\n os.path.join(\"output\", name_pattern, \"out\", name_pattern + \"{ext}\"),\n mapper=self.config[\"tools_ngs_mapping\"],\n caller=callers & set(SOMATIC_VARIANT_CALLERS_MATCHED),\n ext=EXT_VALUES,\n )\n yield from self._yield_result_files_matched(\n os.path.join(\"output\", name_pattern, \"log\", name_pattern + \"{ext}\"),\n mapper=self.config[\"tools_ngs_mapping\"],\n caller=callers & set(SOMATIC_VARIANT_CALLERS_MATCHED),\n ext=(\n \".log\",\n \".log.md5\",\n \".conda_info.txt\",\n \".conda_info.txt.md5\",\n \".conda_list.txt\",\n \".conda_list.txt.md5\",\n ),\n )\n # joint calling\n name_pattern = \"{mapper}.{caller}.jannovar_annotate_somatic_vcf.{donor.name}\"\n yield from self._yield_result_files_joint(\n os.path.join(\"output\", name_pattern, \"out\", name_pattern + \"{ext}\"),\n mapper=self.w_config[\"step_config\"][\"ngs_mapping\"][\"tools\"][\"dna\"],\n caller=callers & set(SOMATIC_VARIANT_CALLERS_JOINT),\n ext=EXT_VALUES,\n )\n\n def _yield_result_files_matched(self, tpl, **kwargs):\n \"\"\"Build output paths from path template and extension list.\n\n This function returns the results from the matched somatic variant callers such as\n Mutect.\n \"\"\"\n for sheet in filter(is_not_background, self.shortcut_sheets):\n for sample_pair in sheet.all_sample_pairs:\n if (\n not sample_pair.tumor_sample.dna_ngs_library\n or not sample_pair.normal_sample.dna_ngs_library\n ):\n msg = (\n \"INFO: sample pair for cancer bio sample {} has is missing primary\"\n \"normal or primary cancer NGS library\"\n )\n print(msg.format(sample_pair.tumor_sample.name), file=sys.stderr)\n continue\n yield from expand(\n tpl, tumor_library=[sample_pair.tumor_sample.dna_ngs_library], **kwargs\n )\n\n def _yield_result_files_joint(self, tpl, **kwargs):\n \"\"\"Build output paths from path template and extension list.\n\n This function returns the results from the joint somatic variant callers such as\n \"Bcftools joint\".\n \"\"\"\n for sheet in filter(is_not_background, self.shortcut_sheets):\n for donor in sheet.donors:\n yield from expand(tpl, donor=[donor], **kwargs)\n\n def check_config(self):\n \"\"\"Check that the path to the NGS mapping is present\"\"\"\n self.ensure_w_config(\n (\"step_config\", \"somatic_variant_annotation\", \"path_somatic_variant_calling\"),\n (\"Path to variant calling not configured but required for somatic variant annotation\"),\n )\n self.ensure_w_config(\n (\"step_config\", \"somatic_variant_annotation\", \"path_jannovar_ser\"),\n (\"Path to serialized Jannovar database\"),\n )\n","sub_path":"snappy_pipeline/workflows/somatic_variant_annotation/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":12334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"390244347","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\nfrom nwae.utils.Log import Log\nfrom inspect import currentframe, getframeinfo\nfrom keras.models import Input, Model\nfrom keras.layers import Dense\nfrom nwae.lang.preprocessing.TxtPreprocessor import TxtPreprocessor\nfrom nwae.utils.dataencoder.OneHotEncoder import OneHotEncoder\n\n\n#\n# Model to encode words to more compact vectors instead of the inefficient sparse one-hot encoding\n# Каждое слово кодируется в более компактный n-мерный вектор с вещественными числами,\n# а не в двоичном разреженном формате с только 1 и 0 как one-hot\n#\n# Суть решения\n# В принципе решение ниже очень просто, мы представим слово в вектор с аттрибутами.\n# Эти аттрибуты является самыми словами, и озаначается что мы должен быть только находить\n# связи между словами и создавать какую-то меру.\n#\n# Принцип алгоритма\n# В первом слое нейронной сети, входные данные (одно слово) кодируется как one-hot\n# В втором слое, кодирование выходных в n-мерном пространстве, который является вектор слова\n# В третом как обычно кодирование в softmax (вероятность)\n#\nclass WordEmbedding:\n\n def __init__(\n self,\n identifier_string,\n lang,\n training_text_list,\n # If None, will not do spelling correction\n dir_path_model = None,\n # If None, will not replace any word with unknown symbol W_UNK\n model_features_list = None,\n dirpath_synonymlist = None,\n postfix_synonymlist = None,\n dir_wordlist = None,\n postfix_wordlist = None,\n dir_wordlist_app = None,\n postfix_wordlist_app = None,\n stopwords_list = None,\n ):\n self.identifier_string = identifier_string\n self.lang = lang\n self.training_text_list = training_text_list\n\n self.txt_pp = TxtPreprocessor(\n identifier_string = self.identifier_string,\n # If None, will not do spelling correction\n dir_path_model = dir_path_model,\n # If None, will not replace any word with unknown symbol W_UNK\n model_features_list = model_features_list,\n lang = self.lang,\n dirpath_synonymlist = dirpath_synonymlist,\n postfix_synonymlist = postfix_synonymlist,\n dir_wordlist = dir_wordlist,\n postfix_wordlist = postfix_wordlist,\n dir_wordlist_app = dir_wordlist_app,\n postfix_wordlist_app = postfix_wordlist_app,\n stopwords_list = stopwords_list,\n )\n\n self.index_word_dict = None\n self.word_index_dict = None\n return\n\n def preprocess_text(\n self\n ):\n self.sentences_cleaned = [\n self.txt_pp.process_text(inputtext=s, return_as_string=False)\n for s in self.training_text_list\n ]\n Log.debug(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Processed sentences: ' + str(self.sentences_cleaned)\n )\n return self.sentences_cleaned\n\n #\n # Концепция заключается в том что \"связь\" между словом и \"атрибутами\" (сами является теми же словами)\n # измерится как расстояние слов\n #\n def form_word_tuples(\n self,\n window,\n sentences_array,\n ):\n assert window >= 2, 'Window ' + str(window) + ' must be >= 2.'\n\n # Creating a placeholder for the scanning of the word list\n word_lists = []\n all_text = []\n\n for sent in sentences_array:\n # Appending to the all text list\n all_text += sent\n\n # Creating a context dictionary\n for i, word in enumerate(sent):\n for w in range(window):\n # Getting the context that is ahead by *window* words\n if i + 1 + w < len(sent):\n word_lists.append([word] + [sent[(i + 1 + w)]])\n # Getting the context that is behind by *window* words\n if i - w - 1 >= 0:\n word_lists.append([word] + [sent[(i - w - 1)]])\n return word_lists, all_text\n\n #\n # Алгоритм обяснен выше\n #\n def encode(\n self,\n # E.g. {'china': 1, 'russia': 2, ..}\n word_list,\n # E.g. [('china', 'dimsum'), ('russia', 'xleb'), ..]\n word_tuples_list,\n ):\n oh_enc = OneHotEncoder()\n self.words_onehot = oh_enc.encode(\n feature_list = word_list\n )\n self.word_index_dict = oh_enc.get_feature_index_dict()\n self.index_word_dict = {v:k for k,v in self.word_index_dict.items()}\n Log.debug(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Unique word dictionary, length ' + str(len(self.word_index_dict))\n + ': ' + str(self.word_index_dict)\n )\n\n X = []\n Y = []\n for t in word_tuples_list:\n root_word = t[0]\n root_word_index = self.word_index_dict[root_word]\n close_word = t[1]\n close_word_index = self.word_index_dict[close_word]\n X.append(self.words_onehot[root_word_index])\n Y.append(self.words_onehot[close_word_index])\n\n Log.debug(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': X: ' + str(X) + '\\nY: ' + str(Y)\n )\n\n return np.array(X), np.array(Y)\n\n def train(\n self,\n X,\n Y\n ):\n # Defining the size of the embedding\n embed_size = 2\n\n # Defining the neural network\n inp = Input(shape=(X.shape[1],))\n Log.debug('Input shape: ' + str(X.shape))\n # Middle layer is the embedding vector we seek to extract\n # \"linear\" because this will serve as the word definition, to be input to other neural networks\n x = Dense(units=embed_size, activation='linear')(inp)\n # Standard softmax final layer\n x = Dense(units=Y.shape[1], activation='softmax')(x)\n model = Model(inputs=inp, outputs=x)\n Log.debug('Output shape: ' + str(Y.shape))\n model.compile(loss='categorical_crossentropy', optimizer='adam')\n model.summary()\n\n # Optimizing the network weights\n model.fit(\n x=X,\n y=Y,\n batch_size=256,\n epochs=100\n )\n\n # Obtaining the weights from the neural network.\n # These are the so called word embeddings\n\n # The input layer (embedding weights)\n weights = model.get_weights()[0]\n Log.important(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Weights extracted as embedding layer: ' + str(weights)\n )\n print(len(weights))\n\n # Creating a dictionary to store the embeddings in. The key is a unique word and\n # the value is the numeric vector\n embedding_dict = {}\n for word in self.word_index_dict.keys():\n embedding_dict.update({\n word: weights[self.word_index_dict.get(word)]\n })\n return embedding_dict\n\n\nif __name__ == '__main__':\n Log.LOGLEVEL = Log.LOG_LEVEL_DEBUG_1\n data_and_clean_version = [\n (\n 'Аккаунт популярного южнокорейского чат-бота был заблокирован в Facebook после жалоб на ненавистнические '\n 'высказывания в адрес сексуальных меньшинств.',\n # \"Чистая\" форма\n 'Аккаунт популярный южнокорея чат-бот быть заблокировать в Facebook после жалоба на ненависть '\n 'высказывание в адрес сексуальный меньшинство.'\n ),\n (\n 'Как передаёт газета, в одном из диалогов с пользователями бот по имени Lee Ludа назвала лесбиянок '\n '«жуткими» и призналась, что ненавидит их.',\n # \"Чистая\" форма\n 'Как передать газета, в один из диалог с пользователь бот по имя Lee Ludа назвать лесбиянка '\n '«жуткий» и признать, что ненавидеть они.'\n ),\n (\n 'По словам издания, это уже не первый случай, когда искусственный интеллект сталкивается с обвинениями '\n 'в нетерпимости и дискриминации.',\n # \"Чистая\" форма\n 'По слово издание, это уже не первый случай, когда искусственный интеллект сталкиваться с обвинение '\n 'в нетерпимость и дискриминация.'\n ),\n (\n 'Чат-бот Lee Ludа, разработанный сеульским стартапом Scatter Lab и использовавший личность 20-летней '\n 'студентки университета, был удалён из Facebook messenger на этой неделе',\n # \"Чистая\" форма\n 'Чат-бот Lee Ludа, разработать сеул стартап Scatter Lab и использовать личность 20-лет '\n 'студентка университет, быть удалить из Facebook messenger на это неделя'\n ),\n (\n 'Luda поразила пользователей глубиной и естественным тоном своих ответов, которые она заимствовала '\n 'из 10 млрд реальных разговоров между молодыми парами в самом популярном южнокорейском мессенджере KakaoTalk',\n # \"Чистая\" форма\n 'Luda поразить пользователь глубиний и естественный тон свой ответ, который она заимствовать '\n 'из 10 млрд реальный разговор между молодой пара в самый популярный южнокорея мессенджер KakaoTalk'\n ),\n (\n 'восхищение знанием интернет-сленга переросло в возмущение после того, как Luda начала использовать '\n 'оскорбительные и откровенно сексуальные термины',\n # \"Чистая\" форма\n 'восхищение знание интернет-сленг перерасти в возмущение после тот, как Luda начать использовать '\n 'оскорбительный и откровенный сексуальный термин'\n ),\n ]\n\n from nwae.lang.preprocessing.BasicPreprocessor import BasicPreprocessor\n stopwords = [\n 'как', 'на', 'в', 'и', 'с', 'по', 'не', 'когда', 'который',\n 'из', 'что', 'это', 'тот',\n 'он', 'она', 'оно', 'они', 'свой',\n 'быть', 'уже', 'после', 'между',\n 'один',\n ] + [p for p in BasicPreprocessor.DEFAULT_PUNCTUATIONS]\n stopwords = [s.lower() for s in stopwords]\n print('Using stopwords: ' + str(stopwords))\n\n we = WordEmbedding(\n identifier_string = 'test.word.embedding',\n lang = 'ru',\n training_text_list = [s[1] for s in data_and_clean_version],\n stopwords_list = stopwords,\n )\n sentences = we.preprocess_text()\n special_symbols = [BasicPreprocessor.W_UNK, BasicPreprocessor.W_NUM]\n cleaned_sentences = []\n for sent in sentences:\n cleaned_sentences.append(\n [w for w in sent if w not in special_symbols]\n )\n [print(s) for s in cleaned_sentences]\n\n word_tuples_list, all_text = we.form_word_tuples(\n window = 2,\n sentences_array = cleaned_sentences,\n )\n print('Word tuples list: ' + str(word_tuples_list))\n print('All text: ' + str(all_text))\n\n X, Y = we.encode(\n word_list = all_text,\n word_tuples_list = word_tuples_list\n )\n index_word_dict = we.index_word_dict\n v = np.array(list(range(len(X[0]))))\n\n # Check the one-hot encoding\n for i, word_oh in enumerate(X):\n root_word_index = np.sum(v*word_oh)\n close_word_index = np.sum(v*Y[i])\n root_word = index_word_dict[root_word_index]\n close_word = index_word_dict[close_word_index]\n pair = [root_word, close_word]\n assert pair in word_tuples_list\n\n embedding_dict = we.train(X=X, Y=Y)\n print(embedding_dict)\n\n import matplotlib.pyplot as plt\n plt.figure(figsize=(10, 10))\n for word in list(we.word_index_dict.keys()):\n coord = embedding_dict.get(word)\n plt.scatter(coord[0], coord[1])\n plt.annotate(word, (coord[0], coord[1]))\n plt.show()\n exit(0)\n","sub_path":"build/lib/nwae/lang/model/WordEmbedding.py","file_name":"WordEmbedding.py","file_ext":"py","file_size_in_byte":14061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"215770304","text":"\n\n#calss header\nclass _HUSTLE():\n\tdef __init__(self,): \n\t\tself.name = \"HUSTLE\"\n\t\tself.definitions = [u'to make someone move quickly by pushing or pulling them along: ', u'to try to persuade someone, especially to buy something, often illegally: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_hustle.py","file_name":"_hustle.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"154160874","text":"import sys\nfrom fontTools.otlLib.builder import buildStatTable\nfrom fontTools.ttLib import TTFont\nfrom make_designspace import (wghts, ESHPs, EGRDs)\n\npath = sys.argv[1]\nfont = TTFont(path)\n\nwght_axis = dict(\n tag=\"wght\",\n name=\"Weight\",\n values=[dict(value=v, name=n) for v, _, n in wghts if n is not None]\n)\n\nshape_axis = dict(\n tag=\"ESHP\",\n name=\"Element Shape\",\n values=[dict(value=v, name=n) for v, _, n in ESHPs if n is not None]\n)\n\ngrid_axis = dict(\n tag=\"EGRD\",\n name=\"Element Grid\",\n values=[dict(value=v, name=n) for v, _, n in EGRDs if n is not None]\n)\n\nbuildStatTable(font, [wght_axis, shape_axis, grid_axis], elidedFallbackName=2)\n\nfont.save(path)\nprint(\"Added STAT table to %s\" % path)\n","sub_path":"production/add_stat_table.py","file_name":"add_stat_table.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"345639409","text":"#!/usr/bin/python3\n\nimport datetime\nimport time\nimport os\n\n#\n# This class maintains a file for logging data. It will rotate the file based on the number\n# of minutes specified in timeBoundary. For examle, timeBoundary = 5, will rotate the file\n# every 5 minutes.\n#\n# Class variables for creation of the log object:\n# path = directory path where to store the log files.\n#\n# name = prefix of the log file name.\n#\n# suffix = suffix of the log file name (type of file). For example \"csv\" for a comma\n# separated file.\n#\n# timeBoundary = the number of minutes before the file gets rotated. Valid values are 0-59\n# A value of zero means to never rotate.\n#\n# Log files get created with the name in the format of:\n# <name> _ <YYYYMMDD> _ <hhmmss> . <prefix>\n#\n# The first log file timestamp will get labeled with the time of the first write entry.\n# Subsequent log file timestamps will get labeled with the time stamp boundary.\n\n# Example - assuming a 5 minute log boundary where the first log entry gets written at 09:12:34am\n# on January 23, 2018\n#\n# First log file name will have a timestamp - 20180123_091234\n# Second log file name will have a timestamp - 20180123_091500\n# Third log file name will have a timestamp - 20180123_092099\n#\n\nclass vteLog:\n\n def __init__(self, path, name, suffix, timeBoundary):\n self.path = path\n self.name = name\n self.suffix = suffix\n self.timeBoundary = timeBoundary\n self.firstWrite = False\n self.firstMinutes = int(datetime.datetime.now().minute)\n self.firstSeconds = int(datetime.datetime.now().second)\n self.lastRotate = self.firstMinutes\n self.currentFile = \"\"\n self.baseFile = self.path + name + '.' + suffix\n\n #\n # TODO: Check to make sure the path name has a \"/\" at the end.\n # If it doesn't add the slash.\n #\n\n def getFilename(self, minString, secString):\n #\n # Expect that minString and secString are string values for minutes and seconds of\n # log file.\n #\n logTimeStamp = datetime.datetime.now().strftime('%Y%m%d_%H')\n logFilename = self.name + \"_\" + logTimeStamp + minString + secString + \".\" + self.suffix\n return logFilename\n\n def rotate(self):\n minString = self.boundaryMinutesLabel()\n secString = '00'\n self.currentFile = self.getFilename(minString, secString)\n self.lastRotate = int(minString)\n\n def setFirst(self):\n minString = datetime.datetime.now().strftime('%M')\n secString = datetime.datetime.now().strftime('%S')\n self.firstWrite = True\n self.currentFile = self.getFilename(minString, secString)\n self.lastRotate = int(minString)\n\n def writeLog(self, message):\n\n if (self.firstWrite == False):\n self.setFirst()\n else:\n if self.readyToRotate():\n self.rotate() \n if os.path.exists(self.baseFile):\n os.remove(self.baseFile)\n\n logfile = self.path + self.currentFile\n\n #\n # Make the directory if it does not exist\n #\n if not os.path.exists(self.path):\n os.makedirs(self.path)\n \n self.open_file = open(logfile,'a',1) # non blocking\n self.open_file.write(message)\n self.open_file.close()\n \n self.open_file = open(self.baseFile,'a',1) # non blocking\n self.open_file.write(message)\n self.open_file.close()\n\n def boundaryCheck(self):\n \n currentMinutes = int(datetime.datetime.now().minute)\n\n # Checks if we are at a multiple of time boundary minutes\n\n if (not(currentMinutes % self.timeBoundary)):\n return True\n else:\n return False\n\n def boundaryMinutesLabel(self):\n currentMinutes = int(datetime.datetime.now().minute)\n minOffset = currentMinutes % self.timeBoundary\n minLabel = currentMinutes - minOffset\n\n if (minLabel < 10):\n return ('0' + str(minLabel))\n else:\n return (str(minLabel))\n \n def readyToRotate(self):\n\n #\n # Never rotate if timeBoundary == 0\n #\n if (self.timeBoundary == 0):\n return False\n\n currentMinutes = int(datetime.datetime.now().minute)\n\n # Checks if we are at a multiple of time boundary minutes and if our current minutes don't\n # equal our last rotation\n\n if (not(currentMinutes % self.timeBoundary) and currentMinutes != self.lastRotate):\n return True\n else:\n return False\n\n#\n# Test of package\n#\n\ndef main():\n print (\"Log Tester\")\n mylog = vteLog('/home/camera/vte/data/test/', 'test', 'csv', 5)\n i = 1\n while True:\n mylog.writeLog(\"Hello World \" + str(i) + '\\n')\n print (\"Current File : \", mylog.currentFile)\n i = i+1\n time.sleep(10)\n \nif __name__ == \"__main__\":\n main()\n\n \n","sub_path":"scripts/vtelog.py","file_name":"vtelog.py","file_ext":"py","file_size_in_byte":5137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"507882024","text":"#!/usr/bin/env python3\n\nimport rospy\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge\nfrom sound_play.libsoundplay import SoundClient\nimport numpy as np\n\n\nclass ObstacleDetector:\n\n sound_messages = {\n 'obstacle_center': \"obstacle center\",\n 'obstacle_left': \"obstacle left\",\n 'obstacle_right': \"obstacle right\",\n }\n\n def __init__(self) -> None:\n self.camera_suscriber = rospy.Subscriber(\n '/camera/depth/image_raw', Image, self._image_process)\n self.occupancy_state_publisher = rospy.Publisher(\n '/occupancy_state', String, queue_size=1)\n\n self.bridge = CvBridge()\n self._obstacle_pos: str = \"free\"\n self.soundhandle = SoundClient()\n\n @property\n def obstacle_pos(self) -> str:\n return self._obstacle_pos\n\n @obstacle_pos.setter\n def obstacle_pos(self, value: str) -> None:\n if value != \"free\" and value != self._obstacle_pos:\n self.soundhandle.say(self.sound_messages[value],\n voice='voice_kal_diphone')\n\n self._obstacle_pos = value\n\n def _image_process(self, image: Image) -> None:\n # Image dimension is 480 (fila), 640 (columnas)\n # With self.bridge we convert the depth image to a matrix.\n distance = 2\n self.current_image = np.asarray(\n self.bridge.imgmsg_to_cv2(image, '32FC1'))\n self.current_image_left = self.current_image[:, :210]\n self.current_image_center = self.current_image[:, 211:420]\n self.current_image_right = self.current_image[:, 421:640]\n\n if np.mean(np.mean(self.current_image_center)) < distance:\n # we take the mean of the mean\n # because the mean of a matrix is a vector\n # and the mean of a vector is a number.\n self.obstacle_pos = \"obstacle_center\"\n\n elif np.mean(np.mean(self.current_image_left)) < distance:\n self.obstacle_pos = \"obstacle_left\"\n\n elif np.mean(np.mean(self.current_image_right)) < distance:\n self.obstacle_pos = \"obstacle_right\"\n\n elif (np.mean(np.mean(self.current_image_left)) >= distance and\n np.mean(np.mean(self.current_image_center)) >= distance and\n np.mean(np.mean(self.current_image_center)) >= distance\n ):\n self.obstacle_pos = \"free\"\n\n def publish_occupancy(self) -> None:\n while not rospy.is_shutdown():\n rospy.loginfo(self.obstacle_pos)\n self.occupancy_state_publisher.publish(self.obstacle_pos)\n rospy.Rate(5).sleep()\n\n\nif __name__ == '__main__':\n rospy.init_node('obstacle_detector', anonymous=True)\n\n obstacle_detector = ObstacleDetector()\n obstacle_detector.publish_occupancy()\n rospy.spin()\n","sub_path":"action_and_perception/scripts/obstacle_detector.py","file_name":"obstacle_detector.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"628640684","text":"import json\n\nfrom compredict.client import api\nfrom compredict.resources import resources\n\n\nclass Forecast:\n\n def __init__(self, api_config=None):\n\n self.__result = None\n self.__client = api.get_instance(token=api_config[\"COMPREDICT_AI_CORE_KEY\"],\n callback_url=api_config[\"COMPREDICT_AI_CORE_CALLBACK_URL\"],\n url=api_config[\"COMPREDICT_AI_CORE_BASE_URL\"])\n self.__client.fail_on_error(option=api_config[\"COMPREDICT_AI_CORE_FAIL_ON_ERROR\"])\n\n def __algorithm(self, data, callback=None): # ,api_config=None):\n\n algorithm = self.__client.get_algorithm(\"base-damage-forecaster\")\n results = algorithm.run(data, evaluate=False, encrypt=False, callback_param=callback)\n\n if results is False:\n print(results.last_error)\n\n if isinstance(results, resources.Task):\n print(results.job_id)\n\n return results\n\n def forecast_checker(self, forecast=None):\n\n subscript = \"damages.%s.damage\" % (str(int(forecast[\"data\"][\"damages_types\"])))\n damages = list(forecast[\"data\"][subscript])\n km = list(forecast[\"data\"][\"mileages\"])\n callback_param = dict(damage_id=forecast[\"data\"][\"idX\"], damage_type_id=int(forecast[\"data\"][\"damages_types\"])\n , update_date_at=json.dumps(forecast[\"data\"][\"updated_at\"], indent=4, sort_keys=True,\n default=str))\n\n forecasting = {\n 'data': {\n 'damage': damages,\n 'distance': km\n }\n\n }\n\n result = self.__algorithm(forecasting, callback_param)\n\n mydata = {\"reference_id\": result.job_id,\n \"status\": \"Pending\",\n \"success\": False,\n \"callback_param\": callback_param}\n\n self.__result = mydata\n\n def results(self, ):\n return self.__result\n","sub_path":"forecast.py","file_name":"forecast.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"378505659","text":"import mxnet as mx\n\n\ndef get_conv(name, data, kout, kernel, stride, pad, with_relu=True):\n data = mx.symbol.Convolution(name=name+'_conv', data=data, num_filter=kout, kernel=kernel, stride=stride, pad=pad, no_bias=True)\n data = mx.symbol.BatchNorm(name=name + '_bn', data=data, fix_gamma=False, momentum=0.99, eps=2e-5)\n if with_relu:\n data=mx.symbol.Activation(name=name + '_relu', data=data, act_type='relu')\n return data\n\ndef get_deep(name, data, kin, kout, with_relu=False):\n data = get_conv(name=name+'_conv1', data=data, kout=kout/4, kernel=(1, 1), stride=(1, 1), pad=(0, 0))\n data = get_conv(name=name+'_conv2', data=data, kout=kout/4, kernel=(3, 3), stride=(1, 1) if kin==kout or kout==4*kin else (2, 2), pad=(1, 1))\n data = get_conv(name=name+'_conv3', data=data, kout=kout , kernel=(1, 1), stride=(1, 1), pad=(0, 0), with_relu=with_relu)\n return data\n\ndef get_line(name, data, kin, kout):\n if kin!=kout:\n data = get_conv(name=name+'_line', data=data, kout=kout, kernel=(1, 1), stride=(1, 1) if kout==4*kin else (2, 2), pad=(0, 0), with_relu=False)\n return data\ndef get_fusion(name, data1, data2, kin, kout, last_relu=True):\n line1= get_line(name+'l1', data1, kin, kout)\n line2= get_line(name+'l2', data2, kin, kout)\n deep1= get_deep(name+'d1', data1, kin, kout)\n deep2= get_deep(name+'d2', data2, kin, kout)\n\n fuse = line1+line2\n fuse = 0.5*fuse\n data1 = fuse+deep1\n data2 = fuse+deep2\n if last_relu:\n data1 = mx.symbol.Activation(name=name+'_relu1', data=data1, act_type='relu')\n data2 = mx.symbol.Activation(name=name+'_relu2', data=data2, act_type='relu')\n else:\n data1=data1*1; data2=data2*1 #for visualization\n return data1,data2\n\ndef get_group(name,data1,data2,num_block,kin,kout,last_relu=True):\n for idx in range(num_block):\n data1,data2 = get_fusion(name+'_b%d'%(idx+1), data1, data2, kin, kout, last_relu if idx==num_block-1 else True)\n kin=kout\n return data1,data2\n\n\ndef get_symbol(num_classes=1000, net_depth=29):\n # setup model parameters\n model_cfgs = {\n 26: (2,2,3,1),\n 29: (2,2,4,1),\n 44: (2, 2, 8, 2),\n 50: (3, 4, 6, 3),\n 101: (3, 4, 23, 3),\n 152: (3, 8, 36, 3)\n }\n blocks_num = model_cfgs[net_depth]\n \n # start network definition\n data = mx.symbol.Variable(name='data')\n # stage conv1_x\n data = get_conv(name='g0_conv1', data=data, kout=64, kernel=(7, 7), stride=(2, 2), pad=(3, 3))\n data = mx.symbol.Pooling(name='g0_pool1', data=data, kernel=(3, 3), stride=(2, 2), pad=(0, 0), pool_type='max')\n # stage conv2_x, conv3_x, conv4_x, conv5_x\n data1, data2=get_group('g1', data , data , num_block=blocks_num[0], kin=64, kout=64*4)\n data1, data2=get_group('g2', data1, data2, num_block=blocks_num[1], kin=256, kout=128*4)\n data1, data2=get_group('g3', data1, data2, num_block=blocks_num[2], kin=512, kout=256*4)\n data1, data2=get_group('g4', data1, data2, num_block=blocks_num[3], kin=1024, kout=512*4,last_relu=False)\n fusion=data1+data2\n fusion=mx.symbol.Activation(name='last_relu', data=fusion, act_type='relu')\n avg = mx.symbol.Pooling(name='global_pool', data=fusion, kernel=(7, 7), stride=(1, 1), pool_type='avg')\n flatten = mx.sym.Flatten(name=\"flatten\", data=avg)\n fc = mx.symbol.FullyConnected(name='fc_score', data=flatten, num_hidden=num_classes)\n softmax = mx.symbol.SoftmaxOutput(name='softmax', data=fc)\n \n return softmax","sub_path":"network/imagenet/symbol_cross.py","file_name":"symbol_cross.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"393357315","text":"import math\nimport numpy as np\nimport cv2\n\nwidth = 640*2\nheight = 480*2\n\nreferencePoints = [np.float32(\n [[width/4, height/4],\n [2*width/4, height/4], \n [2*width/4, 2*height/4], \n [width/4, 2*height/4]]\n),\nnp.float32([[2.5*width/4, 2.5*height/4],\n [3*width/4, 2.5*height/4], \n [3*width/4, 3*height/4], \n [2.5*width/4, 3*height/4]]\n ),\n\nnp.float32([[3.5*width/4, 3.5*height/4],\n [4*width/4, 3.5*height/4], \n [4*width/4, 4*height/4], \n [3.5*width/4, 4*height/4]]\n )]\n\ncurrentPoint = (-1, -1)\ncalibrating = True\nfullScreen = False\nready = False\n# TODO: mudar o nome do arquivo da imagem\ninputImage1 = [cv2.imread(\"naruto.jpg\"), cv2.imread(\"naruto.jpg\"), cv2.imread('peppa.jpg')]\nrows1, cols1 = [i.shape[0] for i in inputImage1], [i.shape[1] for i in inputImage1]\npts1 = [np.float32(\n [[0,0],\n [cols,0],\n [cols, rows],\n [0, rows]]\n) for cols, rows in zip(cols1, rows1)]\n\nimage = np.zeros((height, width, 3), dtype=np.uint8)\n\ndef pointColor(n):\n if n==0:\n return (0, 0, 255)\n elif n==1:\n return (0, 255, 255)\n elif n==2:\n return (255, 255, 0)\n else:\n return (0, 255, 0)\n\ndef mouse(event, x, y, flags, param):\n global currentPoint\n\n if event == cv2.EVENT_LBUTTONDOWN:\n cp = 0\n for i in range(len(referencePoints)):\n for point in referencePoints[i]:\n dist = math.sqrt((x-point[0])*(x-point[0])+(y-point[1])*(y-point[1]))\n if dist < 10:\n print(\"mouse event ponto {},{} indice {}\".format(x,y,i))\n currentPoint = (cp%4,i)\n print(currentPoint[1])\n break\n else:\n cp += 1\n\n if event == cv2.EVENT_LBUTTONUP:\n currentPoint = (-1,-1)\n \n if currentPoint[0] != -1:\n referencePoints[currentPoint[1]][currentPoint[0]] = [x, y]\ncv2.namedWindow(\"test\", cv2.WINDOW_NORMAL)\ncv2.setMouseCallback(\"test\", mouse)\ncap = [cv2.VideoCapture('batman.mp4'),cv2.VideoCapture('morty.mp4'),cv2.VideoCapture('mandelbrot.mp4')]\n\nwhile True:\n image[:] = (0, 0, 0)\n if calibrating:\n color = 0\n for i in range(len(referencePoints)):\n for point in referencePoints[i]:\n cv2.circle(image, (int(point[0]), int(point[1])),5, pointColor(color%4), -1)\n color += 1\n for i in range(len(referencePoints)):\n \n if not ready:\n M = cv2.getPerspectiveTransform(pts1[i], referencePoints[i])\n cv2.warpPerspective(inputImage1[i], M, (width, height), image, borderMode=cv2.BORDER_TRANSPARENT)\n else:\n frame = cap[i].read()[1]\n rows1, cols1 = frame.shape[0], frame.shape[1]\n pts1 = np.float32(\n [[0,0],\n [cols1,0],\n [cols1, rows1],\n [0, rows1]])\n \n M = cv2.getPerspectiveTransform(pts1, referencePoints[i])\n cv2.warpPerspective(frame, M, (width, height), image, borderMode=cv2.BORDER_TRANSPARENT)\n cv2.imshow(\"test\", image)\n key = cv2.waitKey(1) & 0xFF\n if key == ord(\"r\"):\n ready = True\n if key == ord(\"c\"):\n calibrating = not calibrating\n \n if key == ord(\"f\"):\n if not fullScreen:\n cv2.setWindowProperty(\"test\", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)\n else:\n cv2.setWindowProperty(\"test\", cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_NORMAL)\n fullScreen = not fullScreen\n \n if key == ord(\"q\"):\n break\n\ncv2.destroyAllWindows()","sub_path":"Afonso/0x08-geometric_transformations/projeto2- afonso/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":3573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"91158020","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 10 12:40:38 2018\r\n\r\n@author: wes\r\n\"\"\"\r\n\r\n# RES: https://stackoverflow.com/questions/25962114/how-to-read-a-6-gb-csv-file-with-pandas\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport datetime\r\nimport os\r\nimport sys\r\nimport cProfile\r\nimport line_profiler\r\n\r\n@profile\r\ndef process_bin(path,binSize,sampleName,sample_outdir):\r\n \r\n #bin_means=[]\r\n BIN_MEANS=pd.DataFrame(columns=['POSITION','MEANDEPTH']) #DF TO HOLD BIN DATA\r\n DO_NOT_RETURN_BIN_MEANS=False # \r\n CovOver0=0\r\n Cov0=0\r\n BIN_POS_TRACKER=[0,binSize] # keeps track of chromosome postion\r\n chunk_tracker=0 # keeps track of chunk number\r\n SIZE_LIMIT=1000000000\r\n \r\n for chunk in pd.read_csv(path, sep='\\t', chunksize=binSize):\r\n chunk_tracker+=1\r\n #cur_bin_mean=chunk.ix[:,2].mean() # get 3rd col, calculate mean\r\n cur_bin_mean=chunk.iloc[:,2].mean() # get 3rd col, calculate mean\r\n #bin_means.append(cur_bin_mean) # CHANGE TO ADD CHR,POS,cur_bin_mean\r\n bin_pos_string=str(BIN_POS_TRACKER).split('[')[1].split(']')[0].replace(', ',':')\r\n BIN_MEANS.loc[len(BIN_MEANS)]=[bin_pos_string,cur_bin_mean] # APPEND A ROW OF DATA\r\n if cur_bin_mean==0:\r\n Cov0+=1\r\n else: CovOver0+=1\r\n BIN_POS_TRACKER=[BIN_POS_TRACKER[0]+binSize,BIN_POS_TRACKER[1]+binSize]\r\n #CHECK SIZE OF BIN_MEANS, IF SIZE LIMIT IS EXCEEDED THEN PACKAGE INTO FILE AND RESET SIZE TRACKER\r\n if sys.getsizeof(BIN_MEANS) > SIZE_LIMIT:\r\n #BIN_MEANS['CHROM']='chr' + path.split('chr')[1].split('_')[0] \r\n #BIN_MEANS['CHROM']='chr' + path.split('chr')[1].split('.')[0] \r\n BIN_MEANS['CHROM']='chr' + sampleName\r\n #sampleName = path.split('/')[-1].split('_')[1]\r\n BIN_MEANS.to_csv(sample_outdir + '/'+sampleName+'_'+str(chunk_tracker)+'_'+str(binSize)+'.csv', sep=',')\r\n \r\n \r\n print ('N bins: ',len(BIN_MEANS))\r\n print ('mean cov: ',np.mean(BIN_MEANS))\r\n print('Cov0 bins: ',Cov0, 'Cov >0 bins: ',CovOver0)\r\n print('size of BIN_MEANS: ',sys.getsizeof(BIN_MEANS))\r\n \r\n if DO_NOT_RETURN_BIN_MEANS: return (DO_NOT_RETURN_BIN_MEANS, CovOver0, Cov0)\r\n else: return (BIN_MEANS, CovOver0, Cov0)\r\n \r\ndef process_file(path,binSizes,sample_outdir):\r\n \r\n CovOverZero_fractions = []\r\n NBINS = []\r\n \r\n for BIN in binSizes:\r\n sampleName = path.split('/')[-1].split('.')[0] # THERE IS SOMETIMES A BUG HERE WHERE THE sampleName IS DERIVED FROM THE path\r\n bin_data = process_bin(path,BIN,sampleName,sample_outdir)\r\n Nbins=bin_data[1]+bin_data[2]\r\n CovOverZero_fractions.append(bin_data[1]/Nbins)\r\n NBINS.append(Nbins)\r\n #APPEND CHROM TO DF\r\n if type(bin_data[0]) != bool:\r\n OUTDATA=bin_data[0]\r\n #print('chr' + path.split('chr')[1].split('_')[0])\r\n #OUTDATA['CHROM']='chr' + path.split('chr')[1].split('_')[0]\r\n OUTDATA['CHROM']='chr' + path.split('chr')[1].split('.')[0]\r\n print(OUTDATA.head())\r\n #SAVE DF TO FILE\r\n OUTDATA.to_csv(sample_outdir + '/'+sampleName+'_'+str(BIN)+'.csv', sep=',') \r\n \r\n print('Fraction of nonZero bins: ',CovOverZero_fractions)\r\n print('Number of bins in chrom/file: ',NBINS)\r\n #SAVE SUMMARY OUTPUT\r\n \r\ndef process_chromosomes(sample_paths_file,binSizes,sample_outdir):\r\n\r\n with open(sample_paths_file, 'r') as r:\r\n sample_paths=[line.strip() for line in r]\r\n \r\n if not os.path.exists(sample_outdir):\r\n os.makedirs(sample_outdir)\r\n \r\n for path in sample_paths:\r\n print(datetime.datetime.now())\r\n print(path)\r\n process_file(path,binSizes,sample_outdir)\r\n \r\n\r\nif __name__ == '__main__':\r\n print(datetime.datetime.now())\r\n # READ INPATHS FROM FILE\r\n# with open('/home/rmhawwo/Scratch/batch1_wgs_workflow/coverage_infile_paths.txt', 'r') as r:\r\n# sample_paths=[line.strip() for line in r]\r\n\r\n# sample_outdir='/home/rmhawwo/Scratch/batch1_wgs_workflow/LCM_coverage_binData/coverage_HC_LCM1'\r\n# binSizes=[10000]\r\n# process_chromosomes(sample_paths,binSizes,sample_outdir)\r\n #cProfile.run(\"process_chromosomes(sys.argv[1],[int(sys.argv[2])],sys.argv[3])\")\r\n process_chromosomes(sys.argv[1],[int(sys.argv[2])],sys.argv[3])\r\n\r\n","sub_path":"pandas_process_large_file_in_chunks_TESTING.py","file_name":"pandas_process_large_file_in_chunks_TESTING.py","file_ext":"py","file_size_in_byte":4415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"617820060","text":"import os\nimport json\nimport torch\nfrom collections import defaultdict\nfrom torch.utils.data import Dataset\nimport numpy as np\n\n# Loads a PhotoBook segment data set object from file\nclass SegmentDataset(Dataset):\n def __init__(self, data_dir, segment_file, vectors_file, split='train'):\n\n self.data_dir = data_dir\n self.split = split\n self.segment_file = self.split + '_' + segment_file\n\n # Load a PhotoBook dialogue segment data set\n with open(os.path.join(self.data_dir, self.segment_file), 'r') as file:\n self.temp_dialogue_segments = json.load(file)\n\n self.dialogue_segments = []\n for d in self.temp_dialogue_segments:\n\n if d['segment'] == []:\n d['segment'] = [0] #pad empty segment\n d['length'] = 1\n\n\n self.dialogue_segments.append(d)\n\n # Load pre-defined image features\n with open(os.path.join(data_dir, vectors_file), 'r') as file:\n self.image_features = json.load(file)\n\n # Returns the length of the data set\n def __len__(self):\n return len(self.dialogue_segments)\n\n # Returns a PhotoBook Segment object at the given index\n def __getitem__(self, index):\n return self.dialogue_segments[index]\n\n @staticmethod\n def get_collate_fn(device):\n\n def collate_fn(data):\n\n #print('collate',data)\n max_src_length = max(d['length'] for d in data)\n max_target_images = max(len(d['targets']) for d in data)\n max_num_images = max([len(d['image_set']) for d in data])\n\n #print(max_src_length, max_target_images, max_num_images)\n\n batch = defaultdict(list)\n\n for sample in data:\n for key in data[0].keys():\n\n if key == 'segment':\n padded = sample['segment'] \\\n + [0] * (max_src_length-sample['length'])\n #print('seg', padded)\n\n elif key == 'image_set':\n\n padded = [int(img) for img in sample['image_set']]\n\n padded = padded \\\n + [0] * (max_num_images-len(sample['image_set']))\n #print('img', padded)\n\n elif key == 'targets':\n\n #print(sample['targets'])\n padded = np.zeros(max_num_images)\n padded[sample['targets']] = 1\n\n #print('tar', padded)\n\n else:\n #length of segment in number of words\n padded = sample[key]\n\n batch[key].append(padded)\n\n for key in batch.keys():\n #print(key, batch[key])\n batch[key] = torch.Tensor(batch[key]).long().to(device)\n\n return batch\n\n return collate_fn\n","sub_path":"photobook_dataset/discriminator/SegmentDataset.py","file_name":"SegmentDataset.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"118551099","text":"import json\nimport os\nfrom tkinter.tix import MAX\n\nfrom django.contrib import messages\nfrom django.core.files.storage import FileSystemStorage\n\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom CanAutomationSystem.settings import BASE_DIR\nfrom chef.models import Chef\nfrom client.models import Item, Orders, Customer\nfrom prog.models import Admin, Orderdetails\n\ndef login(request):\n return render(request, 'adminlogin.html')\n\ndef forget(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n return render(request, 'forgot.html')\n\ndef fp(request):\n unm=request.POST['unm']\n data = Admin.objects.filter(name=unm)\n if not data:\n messages.info(request,'inavalid username')\n return HttpResponseRedirect('/prog/forget')\n messages.info(request, ' login with adminid : '+unm+' and password : '+data[0].value)\n return HttpResponseRedirect('/prog/forget')\n\n@csrf_exempt\ndef validation(request):\n username1 = request.POST['unm']\n password1 = request.POST['pwd']\n data = Admin.objects.filter(name=username1)\n if not data:\n return HttpResponse('0')\n elif data[0].value == password1:\n request.session['adminnm'] = username1\n return HttpResponse('1')\n else:\n return HttpResponse('2')\ndef additem(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n data=Chef.objects.all()\n m=0\n a=Item.objects.all()\n for i in a:\n if int(i.itemno)>m:\n m=int(i.itemno)\n return render(request, 'additem.html',{'querydata':data,'inos':str(m+1)})\n\n\ndef addchef(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n return render(request, 'addchef.html')\n\n\ndef viewitem(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n data=Item.objects.order_by('category')\n # data = Item.objects.all()\n return render(request, 'viewitem.html', {'querydata': data})\n\n\ndef viewchef(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n data = Chef.objects.all()\n return render(request, 'viewchef.html', {'querydata': data})\n\n@csrf_exempt\ndef additemwork(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n itemno1 = request.POST['itemno']\n itemname1 = request.POST['itemname']\n category1 = request.POST['category']\n image1 = request.FILES['image']\n price1 = request.POST['price']\n fs=FileSystemStorage(location=os.path.join(BASE_DIR,'static/../client/static/'))\n filename=fs.save(image1.name,image1)\n v = Item(itemno=itemno1,itemname=itemname1,category=category1,image='/static/'+image1.name,price=price1)\n v.save()\n return HttpResponseRedirect('/prog/additem')\n\n@csrf_exempt\ndef addchefwork(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n chefid1 = request.POST['chefid']\n chefname1 = request.POST['chefname']\n category1 = request.POST['category']\n if chefid1=='':\n return HttpResponse('0')\n if chefname1 == '':\n return HttpResponse('1')\n if category1=='':\n return HttpResponse('3')\n v = Chef(chefid=chefid1, chefname=chefname1, category=category1)\n v.save()\n messages.info(request, 'Chef added successfully')\n # dict.staus=\"\";\n return HttpResponse('2')\n\n\n\ndef vieworder(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n data = Orderdetails.objects.all()\n return render(request, 'vieworder.html', {'querydata': data})\n\ndef viewdetail(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n oid1=request.GET['oid']\n data = Orders.objects.filter(orderid=oid1)\n item=Item.objects.all()\n return render(request, 'viewdetail.html', {'qdata':item,'querydata': data})\n@csrf_exempt\ndef deletechef(request):\n cid=request.GET.get('chefid')\n a=Chef.objects.filter(chefid=cid)\n a.delete()\n data = Chef.objects.all()\n return render(request, 'viewchef.html', {'querydata': data})\n\ndef deleteitem(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n iid=request.GET.get('itemno')\n a=Item.objects.filter(itemno=iid)\n a.delete()\n data = Item.objects.all()\n return render(request, 'viewitem.html', {'querydata': data})\n\ndef updateitem(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n iid = request.GET.get('itemno')\n a = Item.objects.filter(itemno=iid)\n data = Chef.objects.all()\n return render(request, 'updateitem.html', {'qdata': a,'querydata':data})\n@csrf_exempt\ndef updateitemwork(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n itemno1 = request.POST['itemno']\n itemname1 = request.POST['itemname']\n category1 = request.POST['category']\n img1 = request.POST['img']\n price1 = request.POST['price']\n d=Item.objects.filter(itemno=itemno1)\n if not d[0].image==img1:\n image1 = request.FILES['image']\n fs = FileSystemStorage(location=os.path.join(BASE_DIR, 'static/../client/static/'))\n filename = fs.save(image1.name, image1)\n Item.objects.filter(itemno=itemno1).update(itemno=itemno1, itemname=itemname1, category=category1,\n image='/static/' + image1.name, price=price1)\n else:\n Item.objects.filter(itemno=itemno1).update(itemno=itemno1, itemname=itemname1, category=category1, image=img1, price=price1)\n\n return HttpResponseRedirect('/prog/viewitem')\ndef updatechef(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n cid = request.GET.get('chefid')\n a = Chef.objects.filter(chefid=cid)\n return render(request,'updatechef.html',{'qdata':a})\n@csrf_exempt\ndef updatechefwork(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n chefid1=request.POST['chefid']\n chefname1=request.POST['chefname']\n category1=request.POST['category']\n if chefid1=='':\n return HttpResponse('0')\n if chefname1 == '':\n return HttpResponse('1')\n if category1=='':\n return HttpResponse('3')\n Chef.objects.filter(chefid=chefid1).update(chefname=chefname1,category=category1)\n return HttpResponse('2')\n\n\ndef adminwork(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n return render(request,'adminwork.html')\n\ndef logout(request):\n if 'adminnm' in request.session:\n del request.session['adminnm']\n return HttpResponseRedirect('/prog')\n\n@csrf_exempt\ndef uniqueino(request):\n dt=Item.objects.values_list('itemno',flat=True)\n\n return HttpResponse(json.dumps({'data': list(dt)}), content_type=\"application/json\")\n\n@csrf_exempt\ndef uniquecid(request):\n dt=Chef.objects.values_list('chefid',flat=True)\n return HttpResponse(json.dumps({'data': list(dt)}), content_type=\"application/json\")\n\n\ndef viewcustomer(request):\n if not 'adminnm' in request.session:\n return HttpResponseRedirect('/prog')\n data = Customer.objects.all()\n return render(request, 'viewcustomer.html', {'querydata': data})\n\n\n@csrf_exempt\ndef searchresult(request):\n itemnos = [];\n itemimages = [];\n itemprice = [];\n itemcategory = [];\n itemname = [];\n searchresultlist = []\n dpval = request.POST['dpval']\n stext = request.POST['stext']\n\n if(dpval == \"itemno\"):\n data = Item.objects.filter(itemno__icontains=stext).values();\n for datalist in data:\n itemnos.append(datalist[\"itemno\"])\n itemname.append(datalist[\"itemname\"])\n itemcategory.append(datalist[\"category\"])\n itemprice.append(datalist[\"price\"])\n itemimages.append(datalist[\"image\"])\n elif(dpval == \"category\") :\n data = Item.objects.filter(category__icontains=stext).values();\n for datalist in data:\n itemnos.append(datalist[\"itemno\"])\n itemname.append(datalist[\"itemname\"])\n itemcategory.append(datalist[\"category\"])\n itemprice.append(datalist[\"price\"])\n itemimages.append(datalist[\"image\"])\n else:\n data = Item.objects.filter(itemname__icontains=stext).values();\n for datalist in data:\n itemnos.append(datalist[\"itemno\"])\n itemname.append(datalist[\"itemname\"])\n itemcategory.append(datalist[\"category\"])\n itemprice.append(datalist[\"price\"])\n itemimages.append(datalist[\"image\"])\n\n return HttpResponse(json.dumps({'itemno': itemnos, 'itemname': itemname, 'itemcategory': itemcategory, 'itemprice': itemprice,'itemimage': itemimages}), content_type=\"application/json\")\n\n","sub_path":"prog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"117741366","text":"from __app__.project import db\n\nclass UserModel(db.Model):\n __tablename__ = 'PristineUser'\n id = db.Column(\n 'Id',\n db.Integer,\n primary_key=True\n )\n username = db.Column(\n 'Username',\n db.String(32),\n unique=True,\n nullable=False\n )\n salt = db.Column(\n 'Salt',\n db.String(32),\n unique=False,\n nullable=False\n )\n hash = db.Column(\n 'Hash',\n db.String(128),\n unique=False,\n nullable=False\n )\n token = db.Column(\n 'Token',\n db.String(32),\n unique=False,\n nullable=True\n )\n register_date = db.Column(\n 'RegistrationDateUtc',\n db.DateTime,\n nullable=True\n )\n login_date = db.Column(\n 'LoginDateUtc',\n db.DateTime,\n nullable=True\n )\n login_expiry = db.Column(\n 'ExpiryDateUtc',\n db.DateTime,\n nullable=True\n )\n\n def __repr__(self):\n return '<User {}>'.format(self.username)\n","sub_path":"project/models/UserModel.py","file_name":"UserModel.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"65978231","text":"from sqlite3 import dbapi2 as sqlite\nimport re\nimport math\n\n\ndef getwords(doc):\n\tsplitter = re.compile('\\\\W*')\n\t# Split the words by non-alpha characters\n\twords = [s.lower() for s in splitter.split(doc)\n\t\t\t\tif len(s)>2 and len (s)<20]\n\n\t# Return the unique set of words only\n\treturn dict([(w,1) for w in words])\n\nclass classifier:\n\tdef __init__ (self,getfeatures,filename =None):\n\t\t#Counts of feature/category combinations\n\t\tself.fc= {}\n\t\t#Counts of documents in each category\n\t\tself.cc ={}\n\t\tself.getfeatures = getfeatures\n\t\t# Here getfeatures would be the getwords function\n\n\tdef setdb(self,dbfile):\n\t\tself.con = sqlite.connect(dbfile)\n\t\tself.con.execute('create table if not exists fc(feature,category,count)')\n\t\tself.con.execute('create table if not exists cc(category,count)')\n\n\n\t#Increase the count of a feature/category pair\n\tdef incf(self,f,cat):\n\t\t#self.fc.setdefault(f,{})\n\t\t#self.fc[f].setdefault(cat,0)\n\t\t#self.fc[f][cat]+=1\n\t\tcount = self.fcount(f,cat)\n\t\tif count == 0:\n\t\t\tself.con.execute(\"insert into fc values ('%s','%s',1)\" % (f,cat))\n\t\telse:\n\t\t\tself.con.execute(\"update fc set count= %d where feature='%s' and category='%s' \"% (count+1,f,cat))\n\n\t#Increase the count of a category\n\tdef incc(self,cat):\n\t\t#self.cc.setdefault(cat,0)\n\t\t#self.cc[cat]+=1\n\t\tcount = self.catcount(cat)\n\t\tif count == 0:\n\t\t\tself.con.execute(\"insert into cc values('%s',1)\" %(cat))\n\t\telse:\n\t\t\tself.con.execute(\"update cc set count=%d where category='%s'\"% (count+1,cat))\n\n\n\n\t# The number of times a feature has appeared in a category\n\tdef fcount(self,f,cat):\n\t\t#if f in self.fc and cat in self.fc[f]:\n\t\t#\treturn float(self.fc[f][cat])\n\t\t#return 0.0\n\t\tres = self.con.execute('select count from fc where feature=\"%s\" and category=\"%s\"'%(f,cat)).fetchone()\n\n\t\tif res==None: return 0\n\t\telse: return float(res[0])\n\n\t# The number of items in a category\n\tdef catcount(self,cat):\n\t\t#if cat in self.cc:\n\t\t#\treturn float(self.cc[cat])\n\t\t#return 0\n\t\tres = self.con.execute('select count from cc where category=\"%s\"' %(cat)).fetchone()\n\t\tif res ==None : return 0\n\t\telse : return float(res[0])\n\n\t# The total number of items\n\tdef totalcount(self):\n\t\t#return sum(self.cc.values())\n\t\tres = self.con.execute('select sum(count) from cc').fetchone();\n\t\tif res == None: return 0\n\t\treturn res[0]\n\n\t# The list of all categories\n\tdef categories(self):\n\t\t#return self.cc.keys()\n\t\tcur = self.con.execute('select category from cc')\n\t\treturn [d[0] for d in cur]\n\n\n\tdef train(self,item,cat):\n\t\tfeatures= self.getfeatures(item)\n\t\t#Increment the count for every feature with this category \n\t\tfor f in features:\n\t\t\tself.incf(f,cat)\n\n\t\t#Increment the count for this category\n\t\tself.incc(cat)\n\t\tself.con.commit()\n\n\t# The probability of getting a word from a given category\n\tdef fprob(self,f,cat):\n\t\tif self.catcount(cat) == 0: return 0\n\n\t\treturn self.fcount(f,cat)/self.catcount(cat)\n\n\t# The \"weighted\" probablilty\n\tdef weightedprob(self,f,cat,prf,weight=1.0,ap=0.5):\n\t\t# Calculate current probability \n\t\tbasicprob = prf(f,cat)\n\n\t\t#Count the number of times the feature has appeared in all categories\n\t\ttotals = sum([self.fcount(f,c) for c in self.categories()])\n\n\t\t#Count the weighted average \n\t\tbp = ((weight*ap)+(totals*basicprob))/(weight+totals)\n\t\treturn bp\n\nclass naivebayes(classifier):\n\n\tdef __init__ (self,getfeatures):\n\t\tclassifier.__init__(self,getfeatures)\n\t\tself.thresholds={}\n\n\tdef setthreshold(self,cat,t):\n\t\tself.thresholds[cat]=t\n\n\tdef getthreshold(self,cat):\n\t\tif cat not in self.thresholds: return 1.0\n\t\treturn self.thresholds[cat]\n\n\t# Calculate Pr(Document| Category)\n\tdef docprob(self,item,cat):\n\t\tfeatures = self.getfeatures(item)\n\n\t\t#Multiply the probabilities of all the features together\n\t\tp=1\n\t\tfor f in features: p*=self.weightedprob(f,cat,self.fprob)\n\t\treturn p\n\n\t# In order to classify documents, you really need Pr(Category|Document)\n\t# Pr(Category|Document) = Pr(Document|Category)*Pr(Category)/Pr(Document)\n\t# Pr(Document) can be ignored since it will scale all the results by the same factor\n\n\tdef prob(self,item,cat):\n\t\tcatprob = self.catcount(cat)/self.totalcount()\n\t\tdocprob = self.docprob(item,cat)\n\t\treturn docprob*catprob\n\n\t# For a new item to be classified into a particular category, its probability must be a specified amount \n\t# larger than the probability for any other category. (Threshold)\n\n\tdef classify(self,item,default=None):\n\t\tprobs={}\n\t\t#Find the category with the highest probability\n\n\t\tmax = 0.0\n\t\tfor cat in self.categories():\n\t\t\tprobs[cat]= self.prob(item,cat)\n\t\t\tif probs[cat]>max:\n\t\t\t\tmax=probs[cat]\n\t\t\t\tbest=cat\n\n\t\t# Make sure the probability exceeds threshold*nextbest\n\t\tfor cat in probs:\n\t\t\tif cat==best: continue\n\t\t\tif probs[cat]*self.getthreshold(best)>probs[best]: return default\n\t\treturn best\n\nclass fisherclassifier(classifier):\n\n\tdef cprob(self,f,cat):\n\t\t#The frequency of this feature in this category\n\t\tclf = self.fprob(f,cat)\n\t\tif clf == 0: return 0\n\n\t\t#The frequency of this feature in all the categories\n\t\tfreqsum = sum([self.fprob(f,c) for c in self.categories()])\n\n\t\t#The probability is the frequency in this category divided by the overall frequency\n\t\tp=clf/(freqsum)\n\n\t\treturn p\n\n\tdef fisherprob(self,item,cat):\n\n\t\t#Multipy all the probabilities together using weighted probabilites like last time\n\t\tp=1 \n\t\tfeatures = self.getfeatures(item)\n\t\tfor f in features:\n\t\t\tp*=(self.weightedprob(f,cat,self.cprob)) \n\n\t\t#Take the natural log and multiply by -2\n\n\t\tfscore = -2*math.log(p)\n\n\t\t#Use the inverse chi2 function to get a probability\n\t\treturn self.invchi2(fscore,len(features)*2)\n\n\tdef invchi2(self,chi,df):\n\t\tm=chi / 2.0\n\t\tsum = term = math.exp(-m)\n\t\tfor i in range(1, df//2):\n\t\t\tterm *= m/i\n\t\t\tsum += term\n\t\treturn min(sum,1.0)\n\n\tdef __init__(self,getfeatures):\n\t classifier.__init__(self,getfeatures)\n\t self.minimums={}\n\n\tdef setminimum(self,cat,min):\n\t self.minimums[cat]=min\n \n\tdef getminimum(self,cat):\n\t if cat not in self.minimums: return 0\n\t return self.minimums[cat]\n\n\tdef classify(self,item,default=None):\n\t # Loop through looking for the best result\n\t best=default\n\t max=0.0\n\t for c in self.categories():\n\n\t \tp = self.fisherprob(item,c)\n\n\t \t#Make sure it exceeds its minimum\n\t \tif p>self.getminimum(c) and p>max:\n\t \t\tbest = c\n\t \t\tmax = p\n\t return best\n\n\ndef sampletrain(cl):\n\tcl.train('Nobody owns the water.','good')\n\tcl.train('the quick rabbit jumps fences','good')\n\tcl.train('buy pharmaceuticals now','bad')\n\tcl.train('make quick money at the online casino','bad')\n\tcl.train('the quick brown fox jumps','good')\n\n\n## to add network support \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Classifier/classy.py","file_name":"classy.py","file_ext":"py","file_size_in_byte":6561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"343693951","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def hasCycle(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n if not head or not head.next:\n return False\n p1 = head\n p2 = p1.next\n\n while p2 != None and p2 != p1:\n p1 = p1.next\n p2 = p2.next\n if p2:\n p2 = p2.next\n else:\n break\n\n if p2 != None:\n return True\n else:\n return False\n\nif __name__ == '__main__':\n one = ListNode(0)\n two = ListNode(1)\n thr = ListNode(2)\n head = one\n one.next = two\n #two.next = thr\n #thr.next = None\n\n print(Solution().hasCycle(head))\n","sub_path":"leetcode/python/141_LinkedListCycle.py","file_name":"141_LinkedListCycle.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"46561397","text":"import os\nimport sys\nimport json\n\nresources = os.path.abspath(\n os.path.join(os.path.dirname(__file__), '..', 'resources'))\n\n\ndef test_can_load_companies_json():\n filepath = os.path.join(resources, 'companies.json')\n with open(filepath, 'rb') as fh:\n data = json.load(fh)\n assert len(data) > 0\n\n\ndef test_can_load_people_json():\n filepath = os.path.join(resources, 'people.json')\n with open(filepath, 'rb') as fh:\n data = json.load(fh)\n assert len(data) > 0\n","sub_path":"tests/test_resources.py","file_name":"test_resources.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"465056679","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport scrapy\nfrom scrapy import signals\nfrom scrapy.exporters import CsvItemExporter\nimport csv\n\nclass MetroscubicosPipeline(object):\n def __init__(self):\n self.files = {}\n \n @classmethod\n def from_crawler(cls, crawler):\n \tpipeline = cls()\n \tcrawler.signals.connect(pipeline.spider_opened,signals.spider_opened)\n \tcrawler.signals.connect(pipeline.spider_closed,signals.spider_closed)\n \treturn pipeline\n\n def spider_opened(self,spider):\n \tfile = open('%s_items.csv' % spider.name, 'w+b')\n \tself.files[spider] = file\n \tself.exporter = CsvItemExporter(file)\n \tself.exporter.fields_to_export = [\t'idPropiedad',\n \t\t\t\t\t\t\t\t\t\t'titulo',\n \t\t\t\t\t\t\t\t\t\t'precio',\n \t\t\t\t\t\t\t\t\t\t'm2',\n \t\t\t\t\t\t\t\t\t\t'recamaras',\n \t\t\t\t\t\t\t\t\t\t'banio',\n \t\t\t\t\t\t\t\t\t\t'telefono',\n \t\t\t\t\t\t\t\t\t\t'ubicacion',\n \t\t\t\t\t\t\t\t\t\t'maps',\n \t\t\t\t\t\t\t\t\t\t'descripcion',\n \t\t\t\t\t\t\t\t\t\t'caracteristicas_adicionales',\n \t\t\t\t\t\t\t\t\t\t'comodidad',\n \t\t\t\t\t\t\t\t\t\t'mas',\n \t\t\t\t\t\t\t\t\t\t'imagenes',\n \t\t\t\t\t\t\t\t\t\t'vendedor',\n \t\t\t\t\t\t\t\t\t\t'ubicacion',\n \t\t\t\t\t\t\t\t\t\t'publicacion',\n \t\t\t\t\t\t\t\t\t\t'constructora',\n \t\t\t\t\t\t\t\t\t\t'entrega',\n \t\t\t\t\t\t\t\t\t\t'imagen',\n \t\t\t\t\t\t\t\t\t\t'url_pagina',\n \t\t\t\t\t\t\t\t\t\t'sitio'\n ]\n \tself.exporter.start_exporting()\n\n def spider_closed(self,spider):\n \tself.exporter.finish_exporting()\n \tfile = self.file.pop(spider)\n \tfile.close()\n\n def process_item(self, item, spider):\n # build your row to export, then export the row\n self.exporter.export_item(item)\n return item","sub_path":"metroscubicos/metroscubicos/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"53070146","text":"from process import *\nfrom collections import Counter\nfrom indra.preassembler.custom_preassembly import agent_name_stmt_type_matches\n\n\ndef norm_name(name):\n return '_'.join(sorted(list(set(name.lower().split()))))\n\n\ndef make_fake_wm(stmts):\n for stmt in stmts:\n for agent in stmt.agent_list():\n agent.db_refs['WM'] = [(norm_name(agent.name), 1.0)]\n\n\ndef filter_name_frequency(stmts, k=2):\n norm_names = []\n for stmt in stmts:\n for agent in stmt.agent_list():\n norm_names.append(norm_name(agent.name))\n cnt = Counter(norm_names)\n names = {n for n, c in cnt.most_common() if c >= k}\n\n new_stmts = []\n for stmt in stmts:\n found = True\n for agent in stmt.agent_list():\n if norm_name(agent.name) not in names:\n found = False\n break\n if found:\n new_stmts.append(stmt)\n return new_stmts\n\n\nif __name__ == '__main__':\n stmts = load_eidos()\n make_fake_wm(stmts)\n stmts = filter_name_frequency(stmts, k=2)\n assembled_stmts = ac.run_preassembly(stmts,\n matches_fun=agent_name_stmt_type_matches)\n corpus_name = 'dart-20200127-ontfree-2'\n corpus = Corpus(corpus_name, assembled_stmts, raw_statements=stmts)\n corpus.s3_put(corpus_name)\n","sub_path":"wm_dart/process_ontfree.py","file_name":"process_ontfree.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"233416504","text":"# Create a method that decrypts texts/reversed_zen_lines.txt\ndef decrypt(file_name):\n f = open(file_name)\n temp = f.read()\n line_count = temp.count('\\n')\n f.close()\n f = open(file_name)\n decrypted = ''\n\n for i in range(1, line_count + 1):\n line = f.readline().rstrip()\n reversed_line = line[::-1]\n decrypted += reversed_line + '\\n'\n\n return decrypted\n\n\n# print(decrypt('texts/reversed_zen_lines.txt'))\n","sub_path":"week-04/day-1/01_io/crypto_2revlines.py","file_name":"crypto_2revlines.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"123856639","text":"\"\"\"\nThis is the local module for the road segmentation\nwith the purpose to encapsulate all self-written functions and classes in a \nseparate local module in order to make our Coding more readable and elegant. \n\nSummer 2017\n\"\"\"\n\nimport os\nimport skimage\nimport PIL\nimport numpy as np\nimport skimage.io\nimport collections\nimport random\n\nfrom skimage.transform import rescale\nfrom sklearn import model_selection\nfrom scipy import ndimage\nfrom PIL import Image\nfrom PIL import ImageDraw\n\n\n#---------------------------------\ndef checker():\n \"\"\"\n checks if the library is loaded successfully\n :return: printed message\n \"\"\"\n print('module succesfully loaded')\n\n#------------------------------------\n\n\n######################################################################\n#\n# PREPROCESSING\n#\n######################################################################\n\n\n#---------------------------------\n\ndef read_split_save_many(satellite, label, images_path ,store_path, size_crop = 64, thresholdgreen = 0,\n threshold = .3, amount_inputs = 1, progress = True, augment = False, usetiffs = False):\n \"\"\"\n Function that splits amount_inputs images and labels, slides them into patches\n and stores those patches that do contain more than threshold % of positive labels\n also, it is able to augment the data with the factor 6 using rotation and flipping of\n the selected images - this is controled by the boolean augment = False\n also, the DEFORESTES is implemented: a thresholdgreen that only selects those images\n that have an mean in the 2nd layer of the matrix, the green layer, above thresholdgreen\n\n Example: for 1 input set\n size_crop = 640, augment = True -> 8 augmented and not cropped images\n size_crop = 128 (=640/5), augment = False -> 25 cropped but not augmented patches\n\n Parameters:\n ---------\n :param satellite: the prefix of each satellite image in the images_path, depends on getMapsFunction.\n :param label: the prefix of each label image in the images_path, depends on getMapsFunction.\n :param images_path: path of the raw images as returned by getMapsFunction.\n :param store_path: desired path for the preprocessed data.\n :param size_crop: size of the cropped patches. Set to 640 if no cropping is desired. Should be a valid divisor of\n the original dimensions.\n :param thresholdgreen: percentage of pixels on the satellite image that have to differ from forest pattern.\n Still experimental\n :param threshold: minimum percentage of road pixels for each image to be passed. Option to sort out non-road input data.\n :param amount_inputs: amount of image sets that are passed to the function. Will be automated soon.\n :param progress: boolean that allows to inform the user on the progress of the function.\n :param augment: boolean for dataset augmentation. If set to TRUE, amound of data is increased by factor 8 via image\n flipping and mirroring\n :return: stores preprocessed images in a new folder.\n \"\"\"\n\n\n # loop over amount_inputs images in the input folder\n progress_counter = 0\n # counter for storage of the images\n # counter-intuitively (haha) we start with 0 (Python standard)\n counter = 0\n\n for l in range(amount_inputs):\n # inform user about progress\n if progress:\n if l/amount_inputs > progress_counter:\n print(str(100*l/amount_inputs) + '% of images processed')\n progress_counter = progress_counter + 0.1\n # read images\n if usetiffs:\n sat = PIL.Image.open((images_path + satellite + str(l) + '.tiff'))\n lab = PIL.Image.open((images_path + label + str(l) + '.tiff'))\n else:\n sat = PIL.Image.open((images_path + satellite + str(l) + '.png'))\n lab = PIL.Image.open((images_path + label + str(l) + '.png'))\n height = size_crop\n width = size_crop\n imgwidth, imgheight = sat.size\n\n # double loop to run over grid\n for i in range(0,imgheight,height):\n for j in range(0,imgwidth,width):\n # box for the current cut\n box = (j, i, j+width, i+height)\n crop_sat = sat.crop(box)\n crop_lab = lab.crop(box)\n greenlayersat = np.array(crop_sat)[:,:,1]\n # only store those images with more than threshold% positive pixels\n crop_lab_array = np.array(crop_lab)\n thresholder = lambda x: 0 if x == 0 else 1\n # vectorization makes computation faster\n vfunc = np.vectorize(thresholder)\n crop_lab_array_thresh = vfunc(crop_lab_array)\n # threshold for road pixels and forestness\n if crop_lab_array_thresh.mean() >= threshold and greenlayersat.mean() >= thresholdgreen:\n # option for dataset augmentation\n if augment:\n # transform to array\n crop_sat_array = np.array(crop_sat)\n\n # loop for rotation, re-transformation in image and storage\n for r in range(0,4):\n\n ## Augmentation\n # original, without mirroring, just rotation\n rot_sat = np.rot90(crop_sat_array, k = r)\n rot_lab = np.rot90(crop_lab_array_thresh, k = r)\n\n # mirrored, rotated images\n # flipped vertically here (axis = 0, axis = 1 for horizontal)\n flip_sat = np.flip(rot_sat, axis=0)\n flip_lab = np.flip(rot_lab, axis=0)\n\n ## Storage\n # non mirrored\n Image.fromarray(np.uint8(rot_sat)).save((store_path + 'sat' + str(counter) + '.png'),'PNG')\n # factor 255 for thresholded label\n Image.fromarray(np.uint8(rot_lab*255)).save((store_path + 'lab' + str(counter) + '.png'),'PNG')\n counter += 1\n\n # vertically flipped (mirrored)\n Image.fromarray(np.uint8(flip_sat)).save((store_path + 'sat' + str(counter) + '.png'), 'PNG')\n Image.fromarray(np.uint8(flip_lab * 255)).save((store_path + 'lab' + str(counter) + '.png'), 'PNG')\n counter +=1\n else:\n crop_sat.save((store_path + 'sat' + str(counter) + '.png'),'PNG')\n # important to resize as the array is normalized to [0,1]\n crop_lab = Image.fromarray(np.uint8(crop_lab_array_thresh * 255))\n crop_lab.save((store_path + 'lab' + str(counter) + '.png'),'PNG')\n counter += 1\n\n\n# ---------------------------------\n\ndef split_train_test(path_all, path_splits, ratio_train, dimension = 640, seed = 123, progress = True):\n\n \"\"\"\n Splits preprocessed data in test and train data sample. Also, names the reuslting data with coherent numbering.\n Input is folder with all preprocessed data and the output are two subfolders train_data, test_data.\n\n :param path_all: path of all input images.\n :param path_splits: parent folder for the resulting data folders (usually same as path_all).\n :param ratio_train: ratio of train data relative to test data.\n :param dimension: dimensionality of the images.\n :param seed: random seed for splitting.\n :param progress: inform user about progress or not.\n :return: creates train and test data folder in desired path.\n \"\"\"\n\n print('start with splitting')\n # get amount of files in path_all\n amount_files = int(len(os.listdir(path_all)) *0.5)\n\n all_lab_list = []\n all_sat_list = []\n\n progress_counter = 0\n for i in range(amount_files):\n\n # inform user about progress\n if progress:\n if i / amount_files > progress_counter:\n print(str(100 * i / amount_files) + '% of images read in')\n progress_counter = progress_counter + 0.1\n\n # read in labels and satellites\n instance_lab = skimage.io.imread(fname=(path_all + 'lab' + str(i) + '.png'), as_grey=True)\n instance_sat = skimage.io.imread(fname=(path_all + 'sat' + str(i) + '.png'), as_grey=False)\n\n # append them to the lists\n all_lab_list.append(instance_lab)\n all_sat_list.append(instance_sat)\n\n # necessary list formating\n all_lab_list = np.stack(all_lab_list)\n all_sat_list = np.stack(all_sat_list)\n\n # satellites are 3-dimensional, labels not\n all_lab_list = all_lab_list.reshape(-1, dimension, dimension)\n all_sat_list = all_sat_list.reshape(-1, dimension, dimension, 3)\n\n # use sklearns inbuild function\n train_sat_list, test_sat_list, train_lab_list, test_lab_list = model_selection.train_test_split(all_sat_list, all_lab_list, train_size=ratio_train, random_state=seed)\n\n ## store train data\n # create folder\n train_path = (path_splits + 'train_data/')\n os.makedirs(train_path)\n\n progress_counter = 0\n for j in range(int(amount_files*ratio_train)):\n # transfrom label values from 0-1 to 0-255\n lab = Image.fromarray(np.uint8(train_lab_list[j,:,:]))\n sat = Image.fromarray(train_sat_list[j,:,:,:])\n lab.save((train_path + 'train_lab' + str(j) + '.png'))\n sat.save((train_path + 'train_sat' + str(j) + '.png'))\n\n # inform user about progress\n if progress:\n if j / (amount_files*ratio_train) > progress_counter:\n print( str(round(100 * j / (amount_files * (ratio_train)),0)) + '% of train data stored')\n progress_counter = progress_counter + 0.1\n\n ## store test data\n # create folder\n test_path = (path_splits + 'test_data/')\n os.makedirs(test_path)\n\n progress_counter = 0\n for j in range(int(amount_files * (1-ratio_train))):\n # transfrom label values from 0-1 to 0-255\n lab = Image.fromarray(np.uint8(test_lab_list[j, :, :]))\n sat = Image.fromarray(test_sat_list[j, :, :, :])\n lab.save((test_path + 'test_lab' + str(j) + '.png'))\n sat.save((test_path + 'test_sat' + str(j) + '.png'))\n\n # inform user about progress\n if progress:\n if j / (amount_files * (1-ratio_train)) > progress_counter:\n print( str(round(100 * j / (amount_files * (1-ratio_train)), 0)) + '% of test data stored')\n progress_counter = progress_counter + 0.1\n\n# --------------------------------\n\n######################################################################\n#\n# TRAINING\n#\n######################################################################\n\n\ndef gaussit(input_list, sigma=(2, 2, 0)):\n \"\"\"\n Function that takes list of numpy arrays (each element = one satellite image, e.g. output from read_input_maps) and\n returns list of numpy arrays that contain a gaussian version of the images. Noise can be controlled via the sigma()\n argument. in RGB images 3 inputs (2,2,0) for each layer are allowed. Also one integer is ok.\n\n :param input_list: list of numpy arrays\n :param sigma: value for the gaussian filtering of the the data. Standard deviation of the bell curve.\n :return: list of numpy arrays that were filtered with the gauss filter.\n \"\"\"\n output_list = []\n for image in input_list:\n output_list.append(ndimage.gaussian_filter(input=image, sigma=sigma))\n output_list = np.asarray(output_list)\n output_list = np.ndarray.astype(output_list, 'float32')\n return output_list\n\n# ---------------------------------\n\n\n# Generic Function that reads Input Map data from given folder path and amount of maps, crops and resizes\n# them and stores the data in a numpy.ndarray object\ndef read_input_maps(path, image_name, suffix, amount_maps = 10, crop_pixels = 20, output_shape = [128, 128, 3],\n progress_step = 0):\n \"\"\"\n Function that reads amount of satellite images, crops and resizes them and stores them in a numpy.ndarray which is\n readable for Keras.\n\n :param path:\n :param image_name:\n :param suffix:\n :param amount_maps:\n :param crop_pixels:\n :param output_shape:\n :param progress_step:\n :return:\n\n :param path: path of the satellite maps.\n :param image_name: prefix of each map in the path.\n :param suffix: suffix of each map in the path.\n :param amount_maps: amount of map that should be read in. Has to match the argument from read_label_masks.\n :param crop_pixels: cropping option. Not used currently.\n :param output_shape: output dimensions of the data. We used 512x512 as dimension for our model.\n :param progress_step: controls after how many loaded images the user wants to be informed.\n :return: numpy.ndarray of label masks.\n \"\"\"\n\n\n map_list = []\n for i in range(amount_maps):\n map = skimage.io.imread(fname = (path + image_name + str(i) + suffix), as_grey = False)\n # print(map.shape)\n map = crop_and_resize_maps(input=map, crop_pixels = crop_pixels, output_shape = output_shape)\n if progress_step != 0:\n if i % progress_step == 0:\n print(\"Read Input Map: \", i)\n map_list.append(map)\n\n map_list = np.vstack(map_list)\n map_list = map_list.reshape(-1, output_shape[0], output_shape[1], output_shape[2])\n # Jann Trial to get uint8 satellites\n # map_list = np.ndarray.astype(map_list, 'uint8')\n\n return map_list\n\n\n# ---------------------------------\n\n\n\ndef read_label_masks(path, mask_name, suffix, amount_masks=10, crop_pixels=20, output_shape=[128, 128],\n progress_step = 0, separation = False):\n\n \"\"\"\n Function that reads amount of masks, crops and resizes them and stores them in a numpy.ndarray which is readable for\n Keras.\n\n :param path: path of the label masks.\n :param mask_name: prefix of each mask in the path.\n :param suffix: suffix of each mask in the path.\n :param amount_masks: amount of masks that should be read in. Has to match the argument from read_input_maps.\n :param crop_pixels: cropping option. Not used currently.\n :param output_shape: output dimensions of the data. We used 512x512 as dimension for our model.\n :param progress_step: controls after how many loaded images the user wants to be informed.\n :param separation: not used, to be deleted soon.\n :return: numpy.ndarray of label masks.\n \"\"\"\n # standard creation of a list of masks depth = 1\n if separation == False:\n mask_list = []\n for i in range(amount_masks):\n mask = skimage.io.imread(fname=(path + mask_name + str(i) + suffix), as_grey=False)\n # use crop_and_resize_MASKS here!!!\n mask = crop_and_resize_masks(input=mask, crop_pixels=crop_pixels, output_shape=output_shape)\n if progress_step != 0:\n if i % progress_step == 0:\n print(\"Read Label Mask: \", i)\n mask_list.append(mask)\n\n mask_list = np.vstack(mask_list)\n mask_list = mask_list.reshape(-1, output_shape[0], output_shape[1])\n\n # lambda function sets all given values = 1 if it is original 0 (=black) and 0 if not (= white / gray)\n # threshold can be adjusted later for inclusion of gray-road-areas\n thresholder = lambda x: 1 if x == 0 else 0\n # vectorization makes computing more efficient\n vfunc = np.vectorize(thresholder)\n mask_list = vfunc(mask_list)\n\n # change data type to float64 as required by tflearn\n mask_list = np.ndarray.astype(mask_list, 'float32')\n\n return mask_list\n\n # creation of list of label masks with depth = 2 for the \"special tflearn case\"\n elif separation == True:\n\n mask_list_1 = []\n\n for i in range(amount_masks):\n mask = skimage.io.imread(fname=(path + mask_name + str(i) + suffix), as_grey=False)\n # use crop_and_resize_MASKS here!!!\n mask = crop_and_resize_masks(input=mask, crop_pixels=crop_pixels, output_shape=output_shape)\n if progress_step != 0:\n if i % progress_step == 0:\n print(\"Read Label Mask: \", i, \" in stacking mode\")\n mask_list_1.append(mask)\n\n mask_list_1 = np.vstack(mask_list_1)\n mask_list_1 = mask_list_1.reshape(-1, output_shape[0], output_shape[1], 1)\n\n # lambda function sets all given values = 1 if it is original 0 (=black) and 0 if not (= white / gray)\n # threshold can be adjusted later for inclusion of gray-road-areas\n thresholder = lambda x: 1 if x == 0 else 0\n # vectorization makes computing more efficient\n vfunc = np.vectorize(thresholder)\n mask_list_1 = vfunc(mask_list_1)\n\n # function that assigns opposite entries in each cell (0 => 1, 1 => 0) for label mask with depth 2\n reverser = lambda x: 1 if x == 0 else 0\n reverse_func = np.vectorize(reverser)\n mask_list_2 = reverse_func(mask_list_1)\n\n # stacked along depth\n stackedMask = np.concatenate((mask_list_1, mask_list_2), axis=3)\n # change data type to float64 as required by tflearn\n stackedMask = np.ndarray.astype(stackedMask, 'float32')\n\n return stackedMask\n\n# ---------------------------------\n\ndef sampler(path_orig, path_sampled, amountsamples):\n \"\"\"\n Function that randomly samples amount X of images from folder of data. Takes as Input: folder path with\n (already preprocessed) satellite and road imagery and returns: new folder with X randomly sampled image pairs\n in subsequent order (0,....,X)\n :param path_orig: original path\n :param path_sampled: new path for sampled images\n :param amountsamples: integer value for desired amount of sampled image sets\n :return:\n \"\"\"\n # seed\n random.seed(3337)\n # get amount of image pairs in orig path\n amountFiles = int(len([f for f in os.listdir(path_orig) if os.path.isfile(os.path.join(path_orig, f))]) * 0.5)\n # randomly sample indices from range of all files\n indices = random.sample(range(amountFiles), amountsamples)\n\n # set counter for sequential storage\n counter = 0\n # loop over index list, load and save imagery\n for i in indices:\n sat = Image.open((path_orig + 'crop_sat' + str(i) + '.png'))\n lab = Image.open((path_orig + 'crop_lab' + str(i) + '.png'))\n\n sat.save((path_sampled + 'train_sat' + str(counter) + '.png'))\n lab.save((path_sampled + 'train_lab' + str(counter) + '.png'))\n\n counter += 1#\n print('Done! I sampled ' + str(counter), 'Image Couples')\n\n# ---------------------------------\n\n\n######################################################################\n#\n# EVALUATION\n#\n######################################################################\n\n\n\n# --------------------------------\n\ndef threshold_predictions(prediction, threshold = 0.5):\n \"\"\"\n Function that threshold predictions in [0,1] to hard values in {0,1}.\n Input: prediction as numpy.ndarray, threshold in [0,1]\n Output: <class 'numpy.ndarray'>, dimension (variable): (128, 128), format: int64 , values max, min: 1 0\n\n :param prediction: prediction as numpy array\n :param threshold: a certain threshold after which the pixel is classified as road\n :return: the thresholded prediction as a numpy.ndarray\n \"\"\"\n\n thresholder = lambda x: 1 if x >= (1-threshold) else 0\n # vectorization makes computing more efficient\n vfunc = np.vectorize(thresholder)\n\n thresh_pred = vfunc(prediction)\n return thresh_pred\n\n# --------------------------------\n\n# CLASS RESULTS\n#\n# Class that calculates many measures for a given hard-thresholded prediction as outputed by threshold_prediction()\n# and a ndarray with the correct labels also given as a numpy.ndarray with format int64 and values in {0,1}.\n# This can be solved more intelligently but the class serves our need in this format\n#\n# Input: prediction and true ndarray\n# Output: object with many attributes including the most important measures, the resultmatrix and the confustion-matrix\n# as a python dictionary\n#\n# IMPORTANT HOW-TO:\n# 1) res1 = result(prediction=p_d_orig, truevalue=y_d_orig) înstantiate thhe\n# 2) res1.calculate_measures() CALL THIS FUNCTION at the beginning, fills class with values\n# 3) res1.printmeasures()\n# 4) use attributes such as res1.acc\n#\n#\n# IMPORTANT: Currently labels are labelled as: road=0, non-road=1 (the 'other way round')\n# TODO: should be adjusted someday and then everything has to be updated to road=1, non-road=1\n# this affects also MAINLY the computation of the TP/FP/TN/FN values\n\nclass result:\n\n def __init__(self, prediction, truevalue):\n # we read in a numpy ndarray and need to flatten it to some sort of a list (not exactly)\n self.Yhat = prediction.flatten('C')\n self.Y = truevalue.flatten('C')\n self.confusionlist = []\n self.countdict = dict\n self.resultmatrix = np.empty(shape=prediction.shape)\n self.tpr = 0\n self.prec = 0\n self.acc = 0\n self.f1 = 0\n self.fpr = 0\n self.neg = 0\n self.pos = 0\n self.summary = str\n\n def calculate_measures(self):\n\n #### based on confusion list\n # initialize empty list for storage of TP/FP/FN/TN\n confusion_list = []\n # loop over both flattened arrays using zip\n # TODO: currently switched labels: road=0, non-road=1. Thus switched confusion matrix\n\n self.neg = (self.Y == 1).sum()\n self.pos = (self.Y == 0).sum()\n\n\n for i, j in zip(self.Yhat, self.Y):\n if i == 0 and j == 0:\n confusion_list.append('TP')\n elif i == 1 and j == 1:\n confusion_list.append('TN')\n elif i == 1 and j == 0:\n confusion_list.append('FN')\n elif i == 0 and j == 1:\n confusion_list.append('FP')\n self.confusionlist = confusion_list\n\n ## calculate draw matrix\n # get the TP/FN/FP/TN Matrix in shape of the input image\n self.resultmatrix = np.asarray(self.confusionlist).reshape(self.resultmatrix.shape)\n\n\n ## calculate Measures\n # get counts dictionary\n self.countdict = collections.Counter(self.confusionlist)\n\n # TPR = RECALL\n # control for 0 division\n if (self.countdict['TP'] + self.countdict['TN']) > 0:\n self.tpr = self.countdict['TP'] / (self.countdict['TP'] + self.countdict['FN'])\n\n # PRECISION\n # control for 0 division\n if (self.countdict['TP'] + self.countdict['FP']) > 0:\n self.prec = self.countdict['TP'] / (self.countdict['TP'] + self.countdict['FP'])\n\n # F1 = harmonic mean precision and recall\n # control for 0 division\n if (self.prec + self.tpr) > 0:\n self.f1 = 2 * (self.prec * self.tpr) / (self.prec + self.tpr)\n\n # ACCURACY\n self.acc = (self.countdict['TP'] + self.countdict['TN']) / len(confusion_list)\n\n # FALSE POSITIVE RATE FOR ROC CURVES\n # control for 0 division\n if (self.countdict['TP'] + self.countdict['FP']) > 0:\n self.fpr = 1- self.countdict['TN'] / (self.countdict['TN'] + self.countdict['FP'])\n\n # SUMMARY\n self.summary = ('Recall: ', round(self.tpr,2), 'Precision: ', round(self.prec,2), 'Accuracy: ', round(self.acc, 2),\n 'F1: ', round(self.f1, 2), 'Specificity: ', round(self.fpr, 2), 'Posratio:', round(self.pos / (self.neg + self.pos)),2)\n\n def printmeasures(self):\n print('Recall: ', round(self.tpr,2), 'Precision: ', round(self.prec,2), 'Accuracy: ', round(self.acc, 2), 'F1: ',\n round(self.f1, 2),'Specificity: ', round(self.fpr, 2), 'Positive ratio:', round(self.pos / (self.neg + self.pos)) )\n\n\n# --------------------------------\n\ndef visualize_prediction(resultmatrix, x_image):\n \"\"\"\n Function that draws TP/FN/FP from prediction on input satellite imagery for visualization of the prediction\n Volodymir & Mnih - Style. Input: result_matrix containing the Confusion matrix values for each pixel which is the\n Output from class result.resultmatrix and satellite image array alread transformed to numpy.ndarray.\n How to: (1) Image.open(path), then 2) np.asarray())\n Outputs a x_image which is a numpy.ndarray with RGB values: matrix with depth 3 containing of uint8 values in\n {0, ..., 255}. Can be easily plotted via Image.fromarray(x_image, mode ='RGB').show() which is used in the test.py.\n\n IMPORTANT: Currently labels are labelled as: road=0, non-road=1 (the 'other way round')\n TODO: should be adjusted someday and then everything has to be updated to road=1, non-road=1. This affects also\n MAINLY the computation of the TP/FP/TN/FN values\n\n :param resultmatrix: output of class result\n :param x_image: the original satellite image as a numpy.ndarray\n :return: vizualization of the pixelwise predictions as a numpy.ndarray\n \"\"\"\n\n # flag image as writeable\n x_image.flags.writeable = True\n\n for i in range(resultmatrix.shape[0]):\n for j in range(resultmatrix.shape[0]):\n measure = resultmatrix[i, j]\n # check for all 4 cases and draw coloured point accordingly\n if measure == 'TP':\n # green\n x_image[i, j, 0] = 255\n x_image[i, j, 1] = 215\n x_image[i, j, 2] = 0\n elif measure == 'FN':\n # blue\n x_image[i, j, 0] = 0\n x_image[i, j, 1] = 0\n x_image[i, j, 2] = 255\n # red\n elif measure == 'FP':\n x_image[i, j, 0] = 255\n x_image[i, j, 1] = 0\n x_image[i, j, 2] = 0\n\n return x_image\n\n\n\n# ---------------------------------\n# VISUALIZATION FUNCTIONS WITH PILLOW aka PIL.Image\n#TODO: maybe merge to one function in case of massive boredom\n\n\ndef print_two_images(image1, image2, background = (255, 200, 255), textcolor = (100, 100, 100), header = 'header', title1 = 'image 1',\n title2 = 'image 2', storagepath = 'None', plotit = True):\n \"\"\"\n Prints two already read in PIL.Image-objects next to each other in one plot and adapts to the size of the images\n (assuming quadratic and equal-sized images). Use rgb values such from\n https://www.w3schools.com/colors/colors_picker.asp to set text and background color. The User can choose to print\n and/ or store the resulting concatenated image (default: only plot, no storage). The storage format is .png RGB and\n can only be adapted in this source code, no user interaction. The user can annotate with text with the given\n defaults. Requires PIL with Image and ImageDraw.\n\n This is implemented in a version for 2, 3, 4 images and in a quadrativ version. Can be merged in one elegant\n function one day.\n\n This is the version with 2 images.\n\n :param image1: path to image 1\n :param image2: path to image 2\n :param background: RGB background color\n :param textcolor: RGB textcolor\n :param header: string given by user.\n :param title1: string given by user.\n :param title2: string given by user.\n :param storagepath: path for the storage of the images. If non is given, nothing is stored\n :param plotit: plot them or not, boolean.\n :return: combined graphic of the input images.\n \"\"\"\n # store height, needed for later creation of the plot.\n # quadratic images assumed\n height = image1.size[0]\n\n # initialize new image. We paste the two real images in this one\n new_concat = Image.new(mode='RGB', size=(2 * height + 30, 40 + height), color= background)\n # give paste the upper left corner as input\n # paste(image, (x, y)), where (0,0) is in the upper left corner\n new_concat.paste(image1, (10, 30))\n new_concat.paste(image2, (20 + height, 30))\n\n # draw text in the image\n draw_all = ImageDraw.Draw(new_concat)\n draw_all.text(xy=(10, 0), text=header, fill = textcolor)\n draw_all.text(xy=(10, 20), text=title1, fill = textcolor)\n draw_all.text(xy=(20 + height, 20), text=title2, fill = textcolor)\n\n # plot the image if required. Ubuntu will use imagemagick for this by default\n if plotit:\n new_concat.show()\n\n # option to store the image and not only plot it\n if storagepath != 'None':\n new_concat.save(storagepath, 'PNG')\n\n\n\ndef print_three_images(image1, image2, image3, background = (255, 200, 255), textcolor = (100, 100, 100),\n header = 'header', title1 = 'image 1', title2 = 'image 2', title3 = 'image 3',\n storagepath = 'None', plotit = True):\n \"\"\"\n Prints three already read in PIL.Image-objects next to each other in one plot and adapts to the size of the images\n (assuming quadratic and equal-sized images). Use rgb values such from\n https://www.w3schools.com/colors/colors_picker.asp to set text and background color. The User can choose to print\n and/ or store the resulting concatenated image (default: only plot, no storage). The storage format is .png RGB and\n can only be adapted in this source code, no user interaction. The user can annotate with text with the given\n defaults. Requires PIL with Image and ImageDraw.\n\n This is implemented in a version for 2, 3, 4 images and in a quadrativ version. Can be merged in one elegant\n function one day.\n\n This is the version with 3 images.\n\n :param image1: path to image 1\n :param image2: path to image 2#\n :param image3: path to image 3\n :param background: RGB background color\n :param textcolor: RGB textcolor\n :param header: string given by user.\n :param title1: string given by user.\n :param title2: string given by user.\n :param storagepath: path for the storage of the images. If non is given, nothing is stored\n :param plotit: plot them or not, boolean.\n :return: combined graphic of the input images.\n \"\"\"\n # store height, needed for later creation of the plot.\n # quadratic images assumed\n height = image1.size[0]\n # print(height)\n\n # initialize new image. We paste the three real images in this one\n new_concat = Image.new(mode='RGB', size=(3 * height + 10 + 3*10, 40 + height), color= background)\n # give paste the upper left corner as input\n # paste(image, (x, y)), where (0,0) is in the upper left corner\n new_concat.paste(image1, (10, 30))\n new_concat.paste(image2, (20 + height, 30))\n new_concat.paste(image3, (30 + 2*height, 30))\n\n\n # draw text in the image\n draw_all = ImageDraw.Draw(new_concat)\n draw_all.text(xy=(10, 0), text=header, fill = textcolor)\n draw_all.text(xy=(10, 20), text=title1, fill = textcolor)\n draw_all.text(xy=(20 + height, 20), text=title2, fill = textcolor)\n draw_all.text(xy=(30 + 2*height, 20), text=title3, fill = textcolor)\n\n\n # plot the image if required. Ubuntu will use imagemagick for this by default\n if plotit:\n new_concat.show()\n\n # option to store the image and not only plot it\n if storagepath != 'None':\n new_concat.save(storagepath, 'PNG')\n\n\ndef print_four_images(image1, image2, image3, image4, background=(255, 200, 255), textcolor=(100, 100, 100),\n header='header', title1='image 1', title2='image 2', title3='image 3', title4='image4',\n subtitle = 'subtitle', storagepath='None', plotit=True):\n \"\"\"\n Prints four already read in PIL.Image-objects next to each other in one plot and adapts to the size of the images\n (assuming quadratic and equal-sized images). Use rgb values such from\n https://www.w3schools.com/colors/colors_picker.asp to set text and background color. The User can choose to print\n and/ or store the resulting concatenated image (default: only plot, no storage). The storage format is .png RGB and\n can only be adapted in this source code, no user interaction. The user can annotate with text with the given\n defaults. Requires PIL with Image and ImageDraw.\n\n This is implemented in a version for 2, 3, 4 images and in a quadrativ version. Can be merged in one elegant\n function one day.\n\n This is the version with 3 images.\n\n :param image1: path to image 1\n :param image2: path to image 2\n :param image3: path to image 3\n :param image4: path to image 4\n :param background: RGB background color\n :param textcolor: RGB textcolor\n :param header: string given by user.\n :param title1: string given by user.\n :param title2: string given by user.\n :param storagepath: path for the storage of the images. If non is given, nothing is stored\n :param plotit: plot them or not, boolean.\n :return: combined graphic of the input images.\n \"\"\"\n\n # store height, needed for later creation of the plot.\n # quadratic images assumed\n height = image1.size[0]\n # print(height)\n\n # initialize new image. We paste the three real images in this one\n new_concat = Image.new(mode='RGB', size=(4 * height + 10 + 4 * 10, 60 + height), color=background)\n # give paste the upper left corner as input\n # paste(image, (x, y)), where (0,0) is in the upper left corner\n new_concat.paste(image1, (10, 30))\n new_concat.paste(image2, (20 + height, 30))\n new_concat.paste(image3, (30 + 2 * height, 30))\n new_concat.paste(image4, (40 + 3 * height, 30))\n\n # draw text in the image\n draw_all = ImageDraw.Draw(new_concat)\n draw_all.text(xy=(10, 0), text=header, fill=textcolor)\n draw_all.text(xy=(10, 20), text=title1, fill=textcolor)\n draw_all.text(xy=(20 + height, 20), text=title2, fill=textcolor)\n draw_all.text(xy=(30 + 2 * height, 20), text=title3, fill=textcolor)\n draw_all.text(xy=(40 + 3 * height, 20), text=title4, fill=textcolor)\n draw_all.text(xy=(10, 40 + height), text=subtitle, fill=textcolor)\n\n\n # plot the image if required. Ubuntu will use imagemagick for this by default\n if plotit:\n new_concat.show()\n\n # option to store the image and not only plot it\n if storagepath != 'None':\n new_concat.save(storagepath, 'PNG')\n\ndef print_four_images_quadratic(image1, image2, image3, image4, background=(255, 200, 255), textcolor=(100, 100, 100),\n header='header', title1='image 1', title2='image 2', title3='image 3', title4='image4',\n subtitle='subtitle', storagepath='None', plotit=True):\n \"\"\"\n Prints four already read in PIL.Image-objects in a quadratic way in one plot and adapts to the size of the images\n (assuming quadratic and equal-sized images). Use rgb values such from\n https://www.w3schools.com/colors/colors_picker.asp to set text and background color. The User can choose to print\n and/ or store the resulting concatenated image (default: only plot, no storage). The storage format is .png RGB and\n can only be adapted in this source code, no user interaction. The user can annotate with text with the given\n defaults. Requires PIL with Image and ImageDraw.\n\n This is implemented in a version for 2, 3, 4 images and in a quadrativ version. Can be merged in one elegant\n function one day.\n\n This is the version with 3 images.\n\n :param image1: path to image 1\n :param image2: path to image 2\n :param image3: path to image 3\n :param image4: path to image 4\n :param background: RGB background color\n :param textcolor: RGB textcolor\n :param header: string given by user.\n :param title1: string given by user.\n :param title2: string given by user.\n :param storagepath: path for the storage of the images. If non is given, nothing is stored\n :param plotit: plot them or not, boolean.\n :return: combined graphic of the input images.\n \"\"\"\n # store height, needed for later creation of the plot.\n # quadratic images assumed\n height = image1.size[0]\n # print(height)\n\n # initialize new image. We paste the three real images in this one\n new_concat = Image.new(mode='RGB', size=(2 * height + 30, 90 + 2* height), color=background)\n # give paste the upper left corner as input\n # paste(image, (x, y)), where (0,0) is in the upper left corner\n new_concat.paste(image1, (10, 30))\n new_concat.paste(image2, (20 + height, 30))\n new_concat.paste(image3, (10, 60 + height))\n new_concat.paste(image4, (20 + height, 60 + height))\n\n # draw text in the image\n draw_all = ImageDraw.Draw(new_concat)\n draw_all.text(xy=(10, 0), text=header, fill=textcolor)\n draw_all.text(xy=(10, 20), text=title1, fill=textcolor)\n draw_all.text(xy=(20 + height, 20), text=title2, fill=textcolor)\n draw_all.text(xy=(10, 50 + height), text=title3, fill=textcolor)\n draw_all.text(xy=(20 + height, 50 + height), text=title4, fill=textcolor)\n draw_all.text(xy=(10, 70 + 2*height), text=subtitle, fill=textcolor)\n\n # plot the image if required. Ubuntu will use imagemagick for this by default\n if plotit:\n new_concat.show()\n\n # option to store the image and not only plot it\n if storagepath != 'None':\n new_concat.save(storagepath, 'PNG')\n\n\n\n######################################################################\n#\n# HELPER FUNCTIONS that are currently not in use\n#\n######################################################################\n\n\n# Function that crops and resizes a list of input maps (satellites) given in np.ndarray format\n\ndef crop_and_resize_maps(input, crop_pixels = 20, output_shape = [128, 128, 3]):\n # crop the input map over all three dimensions\n temp_input = input[crop_pixels:input.shape[0]-crop_pixels, crop_pixels:input.shape[1]-crop_pixels, : ]\n # resize the input map\n temp_input = skimage.transform.resize(image = temp_input, output_shape = output_shape)\n return temp_input\n\n# Function that crops and resizes a list of label-masks (roads) given in np.ndarray format\n# differs from the map cropper because of the dimensions\n# TODO: include both versions in one generic function later\n\n# ---------------------------------\n\ndef crop_and_resize_masks(input, crop_pixels = 20, output_shape = [128, 128]):\n # crop the input map over all three dimensions\n temp_input = input[crop_pixels:input.shape[0]-crop_pixels, crop_pixels:input.shape[1]-crop_pixels]\n # resize the input map\n temp_input = skimage.transform.resize(image = temp_input, output_shape = output_shape)\n return temp_input\n\n\n# DEMO SCRIPT FOR POSTPROCESSING OF ONE PREDICTION\n\"\"\"\nimport custommodule\nimport numpy as np\nfrom PIL import Image\n\ny = np.load(file = '/home/jgucci/PycharmProjects/consulting_master/foo_data/y31.npy')\ny = np.ndarray.astype(y, 'int64')\np = np.load(file = '/home/jgucci/PycharmProjects/consulting_master/foo_data/p31.npy')\n\np_thresh = custommodule.threshold_predictions(p, threshold=0.8)\n\nres1 = custommodule.result(prediction=p_thresh, truevalue=y)\nres1.calculate_measures()\nprint(res1.summary)\n\nsat = Image.open('/home/jgucci/PycharmProjects/consulting_master/foo_data/crop_sat31.png')\nsatarray = np.asarray(sat)\n\nvis1 = custommodule.visualize_prediction(resultmatrix=res1.resultmatrix, x_image=satarray)\n\n# re-pic the arrays\nvis1_repic = Image.fromarray(vis1)\nvis1_repic.show()\n\ny_repic = np.ndarray.astype(y*255, dtype='uint8')\ny_repic = Image.fromarray(y_repic, mode='L')\n\np_thresh_repic = np.ndarray.astype(p_thresh*255, dtype='uint8')\np_thresh_repic = Image.fromarray(p_thresh_repic, mode ='L')\n\n# print three images in one pillow image\ncustommodule.print_three_images(header=str(res1.summary),image1=y_repic, image2=p_thresh_repic, image3=vis1_repic, title1='true',\n title2='predicted', title3='coloured satellite', plotit=True)\n\"\"\"\n\n","sub_path":"custommodule.py","file_name":"custommodule.py","file_ext":"py","file_size_in_byte":39907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"69264773","text":"from random import shuffle\nwith open(\"sowpods.txt\", \"r\") as text:\n words = text.read().splitlines()\n while True:\n search = input(\"Enter your string: \")\n print(\"Searching ...\")\n matches = []\n for word in words:\n if search.lower() in word:\n matches.append(word)\n if matches:\n print(\"Found {} results: \".format(len(matches)))\n shuffle(matches)\n if len(matches) > 20:\n matches = matches[:20]\n print(\"Printing the first twenty results: \")\n for m in matches:\n print(m)\n else:\n print(\"No matches found for that string.\")\n","sub_path":"search_en.py","file_name":"search_en.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"55845912","text":"#!/usr/bin/python3\n\"\"\"\nstarts a Flask web application\n\"\"\"\nimport re\nfrom flask import Flask\nfrom flask import render_template\nfrom models import storage\n\n\napp = Flask(__name__)\n\n\n@app.route('/hbnb_filters/', strict_slashes=False)\ndef only_states():\n \"\"\"Displays an HTML page with a list of all States.\n States are sorted by name.\n and cities sorted by name.\n Amenities sorted by name..\n \"\"\"\n all_states = storage.all('State')\n all_amenity = storage.all('Amenity')\n return render_template('10-hbnb_filters.html', states=all_states,\n amenities=all_amenity)\n\n@app.teardown_appcontext\ndef teardown(exc):\n \"\"\"Remove the current SQLAlchemy session.\n \"\"\"\n storage.close()\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"web_flask/10-hbnb_filters.py","file_name":"10-hbnb_filters.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"32164342","text":"from flask import jsonify,url_for, redirect, request\nfrom flask_restful import Resource, Api, reqparse, abort\nfrom bson.objectid import ObjectId\nfrom settings import db\n#parser = reqparse.RequestParser()\n#parser.add_argument('task')\n#args = parser.parse_args()\n\nclass training(Resource):\n\tdef get(self,skip=0,limit=0, id_training=None):\n\t\tdata = []\n\t\ttotal = db.training.count()\n\t\t# print id_training\n\t\tif id_training:\t\t\t\n\t\t\tdata = db.training.find_one({'_id':ObjectId(id_training)})\n\t\t\tif not data:\n\t\t\t\tabort(404, message=\"Data with Id {} not found!\".format(id_training))\n\t\t\tdata[\"_id\"] = str(data[\"_id\"])\n\t\telse:\t\t\t\n\t\t\tcursor = db.training.find().skip(skip).limit(limit)\n\t\t\tfor rk in cursor:\n\t\t\t\trk['_id'] = str(rk['_id'])\n\t\t\t\tdata.append(rk)\t\t\t\n\t\treturn {\"_items\":data,\"_total\":total}\n\tdef post(self):\n\t\tdata = request.get_json()\n\t\t# print data\n\t\tif not data:\n\t\t\tabort(404, message=\"No data provided\")\n\t\telse:\n\t\t\tif db.training.find_one(data):\n\t\t\t\tabort(404, message=\"Review already exist\")\n\t\t\telse:\n\t\t\t\tdb.training.insert_one(data)\n\t\t\t\tdata[\"_id\"] = str(data[\"_id\"])\n\t\t\t\treturn {\"_items\":data, \"response\":\"1 row inserted\"}\n\n\tdef put(self,id_training):\n\t\tdata = request.get_json()\n\t\tdb.training.update({'_id': ObjectId(id_training)}, {'$set': data})\n\t\treturn {\"_items\":None, \"response\":\"{} updated\".format(id_training)}\n\n\tdef delete(self,id_training):\n\t\tdb.training.remove({'_id': ObjectId(id_training)})\n\t\treturn {\"_items\":None, \"response\":\"1 row deleted\"}\n\n","sub_path":"web_interface/api/training/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"472918685","text":"\nSTART_SYMBOL = \"@@START@@\"\nEND_SYMBOL = \"@@END@@\"\n\n\ndef valid_next_characters(function_calls, arg_numbers, last_token, valid_numbers, valid_variables,\n valid_types):\n valid_variables.add('?')\n valid_variables.add('(')\n valid_numbers.add('?')\n valid_numbers.add('(')\n\n num_args = arg_numbers[-1]\n if last_token == END_SYMBOL:\n return {END_SYMBOL}\n elif last_token == '?':\n temp = valid_variables.copy()\n temp.remove('?')\n return temp\n elif last_token == START_SYMBOL:\n return {'('}\n elif last_token == ')' and len(function_calls) == 0:\n return {END_SYMBOL}\n elif last_token == '(':\n if len(function_calls) == 0:\n return {'Equals', 'And'}\n elif function_calls[-1] == 'And':\n return {'Equals'}\n elif function_calls[-1] == 'Equals':\n return {'Value', 'Rate', 'Times', 'Plus', 'Minus', 'Div'}\n elif function_calls[-1] == 'Join' or function_calls[-1] == 'Value' or \\\n function_calls[-1] == 'Rate':\n return {'Join'}\n elif function_calls[-1] == 'Minus' or function_calls[-1] == 'Plus' or function_calls[-1] == 'Times' or function_calls[-1] == 'Div':\n return {'Minus', 'Plus', 'Rate', 'Value', 'Times', 'Div'}\n else:\n raise Exception(str(function_calls) + ' aa ' + str(arg_numbers))\n else:\n if function_calls[-1] == 'And' and 0 < num_args < 15:\n return {'(', ')'}\n elif function_calls[-1] == 'And' and num_args < 15:\n return {'('}\n elif function_calls[-1] == 'Equals' and num_args < 2:\n return valid_numbers.union(valid_variables)\n elif function_calls[-1] == 'Join' and num_args < 2:\n return valid_variables\n elif function_calls[-1] == 'Value' and num_args == 0:\n return valid_variables\n elif function_calls[-1] == 'Value' and num_args == 1:\n return valid_types\n elif function_calls[-1] == 'Rate' and num_args == 0:\n return valid_variables\n elif function_calls[-1] == 'Rate' and (num_args == 1 or num_args == 2):\n return valid_types\n elif (function_calls[-1] == 'Minus' or function_calls[-1] == 'Plus' or function_calls[-1] == 'Times' or function_calls[-1] == 'Div') and arg_numbers[-1] < 2:\n return valid_numbers.union(valid_variables)\n else:\n return {')'}\n\n\ndef update_state(function_calls, arg_numbers, last_token):\n operators = {'Equals', 'And', 'Value', 'Rate', 'Join', 'Plus', 'Minus', 'Times', 'Div'}\n if last_token == START_SYMBOL or last_token == END_SYMBOL:\n pass\n elif last_token == '?':\n pass\n elif last_token in operators:\n function_calls = function_calls + [last_token]\n arg_numbers = arg_numbers + [0]\n elif last_token == ')':\n function_calls = function_calls[:-1]\n arg_numbers = arg_numbers[:-1]\n else:\n arg_numbers = arg_numbers[:]\n arg_numbers[-1] += 1\n return function_calls, arg_numbers\n\n\nif __name__ == '__main__':\n with open('../../../train.txt', 'r') as f:\n lines = f.read().splitlines()\n sentences = []\n for line in lines:\n sentences.append(line.split('\\t')[1].split())\n\n for sentence in sentences:\n tokens = [START_SYMBOL] + sentence + [END_SYMBOL]\n function_calls = []\n num_args = [0]\n valid_variables = {'var' + str(i) for i in range(20)}\n valid_variables.add('(')\n valid_variables.add('?')\n valid_units = {'unit' + str(i) for i in range(20)}\n valid_numbers = {'num' + str(i) for i in range(20)}\n valid_numbers = {x for x in valid_numbers if x.startswith('num')}\n valid_numbers.add('(')\n valid_numbers.add('?')\n valid_actions = {START_SYMBOL}\n for i, token in enumerate(tokens):\n # if i < len(tokens) - 1 and tokens[i + 1] == END_SYMBOL:\n # print(valid_actions, token, function_calls, num_args, tokens)\n assert token in valid_actions, (valid_actions, token, function_calls, num_args, ' '.join(tokens))\n function_calls, num_args = update_state(function_calls, num_args, token)\n # print(function_calls, token)\n valid_actions = valid_next_characters(function_calls, num_args, token,\n valid_numbers=valid_numbers,\n valid_types=valid_units,\n valid_variables=valid_variables)\n print('-' * 80)","sub_path":"allennlp/type_checking.py","file_name":"type_checking.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"122127441","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 12 14:16:38 2017\n\n@author: renn1995\n\nThe Hamming distance between two integers is the number of positions at which the corresponding bits are different.\n\nNow your job is to find the total Hamming distance between all pairs of the given numbers.\n\"\"\"\nclass Solution(object):\n def totalHammingDistance(self, nums):\n \"\"\"\n Calculates the total hamming distance between all pairs of ints\n given in list nums.\n \n Uses hammingDistance function (solved for a previous challenge) as a \n helper.\n \n :type nums: List[int]\n :rtype: int\n \"\"\"\n # Concept: iterate through each element in nums. Calculate the HD to\n # every other nums element and sum.\n \n # Helper function\n def hammingDistance(x, y):\n \"\"\"\n Calculates the hamming distance between two integers, defined as the\n number of dissimilar bits in a binary representation of the two ints.\n \n :type x: int\n :type y: int\n :rtype: int\n \"\"\"\n # Rev 2 Concept: Use bitwise XOR (^) on input ints to get a binary\n # number where 1s correspond to differences between the binary\n # representations of x and y. Sum the 1s and output.\n \n # Apply bitwise XOR\n hamDistBin = bin(x ^ y)\n \n # Count 1s to find hamming distance\n hamDist = hamDistBin.count('1')\n \n return hamDist\n \n # Initialise total hamming distance, to be summed for all elements\n totalHamDist = 0\n \n # Iterate through nums elements by index\n for i in range(len(nums)):\n # Iterate through elements to the right of index i call this (element j)\n for el_j in nums[i+1:]:\n # Calculate hamming distance for that pair; add to total\n totalHamDist += hammingDistance(nums[i], el_j)\n \n return totalHamDist\n \n## Test Code\nimport testOutput\n\ntest = Solution()\n\ntestNo = 1\n\n# Test\nnums = [4, 14, 2]\nexpect = 6\noutput = test.totalHammingDistance(nums)\ntestOutput.testOutput(expect, output, testNo)\ntestNo += 1\n ","sub_path":"477 Total Hamming Distance/totalHammingDistanceRev0.py","file_name":"totalHammingDistanceRev0.py","file_ext":"py","file_size_in_byte":2303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"580426484","text":"# coding=utf-8\nimport cv2\nimport os\nimport sys\nimport subprocess\nfrom run import process\nimport argparse\n\n\n\ndef main(inputpath,out):\n\tnome = out.strip('.jpg')\n\toutputpath = f'images/{nome}_renderizada.jpg'\n\tif isinstance(inputpath, list):\n\t\tfor item in inputpath:\n\t\t\twatermark = deep_nude_process(item)\n\t\t\tcv2.imwrite(\"output_\"+item, watermark)\n\telse:\n\t\twatermark = deep_nude_process(inputpath)\n\t\tcv2.imwrite(outputpath, watermark)\n\n\n\ndef deep_nude_process(item):\n print('Processing {}'.format(item))\n dress = cv2.imread(item)\n h = dress.shape[0]\n w = dress.shape[1]\n dress = cv2.resize(dress, (512,512), interpolation=cv2.INTER_CUBIC)\n watermark = process(dress)\n watermark = cv2.resize(watermark, (w,h), interpolation=cv2.INTER_CUBIC)\n return watermark\n\n\n\nif __name__ == '__main__':\n\t#parser = argparse.ArgumentParser(description=\"simple deep nude script tool\")\n\t#parser.add_argument(\"-i\", \"--input\", action=\"store\", nargs=\"*\", default=\"input.png\",\t\t\t\t\thelp=\"Use to enter input one or more files's name\")\n\t#parser.add_argument(\"-o\", \"--output\", action=\"store\", default=\"output.png\",\t\t\t\t\t\thelp=\"Use to enter output file name\")\n\t#inputpath, outputpath= parser.parse_args().input, parser.parse_args().output\n\t#main(inputpath, outputpath)\n\n\tinputpath = 'images/file.jpg'\n\toutputpath = 'images/renderizada.jpg'\n\tmain(inputpath,out)\n","sub_path":"Deep Flask/deepfake.py","file_name":"deepfake.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"644371407","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\n#DEGREE CENTRALITY\n#가장 중요한 사용자는 누구인가?\n\nusers = [\n {\"id\": 0, \"name\": \"Hero\"},\n {\"id\": 1, \"name\": \"Dunn\"},\n {\"id\": 2, \"name\": \"Sue\"},\n {\"id\": 3, \"name\": \"Chi\"},\n {\"id\": 4, \"name\": \"Thor\"},\n {\"id\": 5, \"name\": \"Clive\"},\n {\"id\": 6, \"name\": \"Hicks\"},\n {\"id\": 7, \"name\": \"Devin\"},\n {\"id\": 8, \"name\": \"Kate\"},\n {\"id\": 9, \"name\": \"Klein\"}\n]\n\nfriendship_pairs = [(0,1), (0,2), (1,2), (1,3), (2,3), (3,4), (4,5), (5,6), (5,7), (6,8), (7,8), (8,9)]\n\nfriendships = {user['id']: [] for user in users}\n\nfor i, j in friendship_pairs:\n friendships[i].append(j)\n friendships[j].append(i)\n\n\n# In[7]:\n\n\ndef number_of_friends(user):\n user_id = user['id']\n friend_ids = friendships[user_id]\n return len(friend_ids)\n\ntotal_connections = sum(number_of_friends(user)\n for user in users)\n\nprint(total_connections)\n\n\n# In[8]:\n\n\nnum_users = len(users)\navg_connections = total_connections / num_users\n\nprint(avg_connections)\n\n\n# In[11]:\n\n\nnum_friends_by_id = [(user['id'], number_of_friends(user))\n for user in users]\n\nnum_friends_by_id.sort(key=lambda id_and_friends: id_and_friends[1],\n reverse=True)\n\nprint(num_friends_by_id)\n\n\n# In[14]:\n\n\n#friends + friend of a friend\ndef foaf_ids_bad(user):\n return [foaf_id\n for friend_id in friendships[user['id']]\n for foaf_id in friendships[friend_id]]\n\nfoaf_ids_bad(users[0])\n\n\n# In[20]:\n\n\n#mutual friend가 몇명?\nfrom collections import Counter\n\ndef friends_of_friends(user):\n user_id = user['id']\n return Counter(\n foaf_id\n for friend_id in friendships[user_id]\n for foaf_id in friendships[friend_id]\n if foaf_id != user_id\n and foaf_id not in friendships[user_id]\n )\n \nprint(friends_of_friends(users[3]))\n\n\n# In[22]:\n\n\ninterests = [\n (0, \"Hadoop\"),(0, \"Big Data\"), (0, \"HBase\"), (0, \"Java\"), (0, \"Spark\"), (0, \"Storm\"), (0, \"Cassandra\"),\n (1, \"NoSQL\"), (1, \"MongoDB\"), (1, \"Cassandra\"), (1, \"Postgres\"), (1, \"HBase\"),\n (2, \"numpy\"), (2, \"Python\"), (2, \"scikit-learn\"), (2, \"scipy\"),\n (3, \"statistics\"), (3, \"regression\"), (3, \"probability\"),\n (4, \"machine learning\"), (4, \"regression\"), (4, \"decision trees\"), (4, \"libsvm\"),\n (5, \"Haskell\"), (5, \"programming languages\"), (5, \"Java\"), (5, \"C++\"), (5, \"Python\"), (5, \"R\"),\n (6, \"probability\"), (6, \"mathematics\"), (6, \"theory\"), (6, \"statistics\"),\n (7, \"machine learning\"), (7, \"scikit-learn\"), (7, \"Mahout\"), (7, \"neural networks\"), \n (8, \"neural networks\"), (8, \"artificial intelligence\"), (8, \"deep learning\"), (8, \"Big Data\"), \n (9, \"Hadoop\"), (9, \"Java\"), (9, \"MpaReduce\"), (9, \"Big Data\")\n]\n\n#특정 관심사를 가지고 있는 모든 사용자 id 반환\ndef data_scientists_who_like(target_interest):\n return [user_id\n for user_id, user_interest in interests\n if user_interest == target_interest]\n\nfrom collections import defaultdict\n\n#key = interest, value = id\nuser_ids_by_interest = defaultdict(list)\n\nfor user_id, interest in interests:\n user_ids_by_interest[interest].append(user_id)\n \n#key = id, value = interest\ninterests_by_user_id = defaultdict(list)\n\nfor user_id, interest in interests:\n interests_by_user_id[user_id].append(interest)\n\n\n# In[27]:\n\n\n#추천 시스템\ndef most_common_interests_with(user):\n return Counter(\n interested_user_id\n for interest in interests_by_user_id[user['id']]\n for interested_user_id in user_ids_by_interest[interest]\n if interested_user_id != user['id']\n )\n\nprint(most_common_interests_with(users[0]))\n\n\n# In[28]:\n\n\n#자연어 처리\nwords_and_counts = Counter(word\n for user, interest in interests\n for word in interest.lower().split())\n\nfor word, count in words_and_counts.most_common():\n if count > 1:\n print(word, count)\n\n","sub_path":"DS-01-overview.py","file_name":"DS-01-overview.py","file_ext":"py","file_size_in_byte":3940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"385183771","text":"\nimport random\n\nclass MyClass(object):\n # Self is the object in which the method was called\n def dothis(self):\n # instance dot attribute, instance will have the rand_val\n self.rand_val = random.randint(1,10)\n\n\nmyInst = MyClass()\nmyInst.dothis()\nprint(myInst.rand_val)\nprint();print()\n\n# myInst.rand_val is instance.attribute\n# We call the attribute of the instance as the state of the instance\n# Because the values change, according to what happens to the object, we call these values state\n# An instance can also get and set values in itself\n# Instance data takes the form of instance attribute values, set and accessed through...\n# ...object.attribute syntax\n\n\n\n####################################################################################\n# 4. Instances have their own data, instance attributes\n####################################################################################\n\n","sub_path":"OOP/Classes/instanceAttributes.py","file_name":"instanceAttributes.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"486130880","text":"def solution(people, limit):\n answer = 0\n # 보자마자 그리디 생각남\n people.sort()\n print(people)\n L = 0\n R = len(people)-1\n count = 0\n while L <= R:\n if people[L] + people[R] > limit:\n R -= 1\n else:\n L += 1\n R -= 1\n count += 1\n print(count)\n\n return count\n","sub_path":"2022/4주차/구명보트/김재환.py","file_name":"김재환.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"382672706","text":"import json\nimport re\n\nfrom collections import defaultdict\nfrom bs4 import BeautifulSoup\nfrom decimal import Decimal\n\nfrom storescraper.product import Product\nfrom storescraper.store import Store\nfrom storescraper.utils import session_with_proxy, remove_words\n\n\nclass Movistar(Store):\n preferred_discover_urls_concurrency = 1\n preferred_products_for_url_concurrency = 1\n prepago_url = 'http://ww2.movistar.cl/prepago/'\n planes_url = 'https://ww2.movistar.cl/movil/planes-portabilidad/'\n portability_choices = [\n (3, ''),\n (1, ' Portabilidad'),\n ]\n movistar1 = 0\n\n @classmethod\n def categories(cls):\n return [\n 'CellPlan',\n 'Cell'\n ]\n\n @classmethod\n def discover_entries_for_category(cls, category, extra_args=None):\n product_entries = defaultdict(lambda: [])\n\n if category == 'CellPlan':\n product_entries[cls.prepago_url].append({\n 'category_weight': 1,\n 'section_name': 'Planes',\n 'value': 1\n })\n\n product_entries[cls.planes_url].append({\n 'category_weight': 1,\n 'section_name': 'Planes',\n 'value': 2\n })\n elif category == 'Cell':\n catalogo_url = 'https://catalogo.movistar.cl/equipomasplan/' \\\n 'catalogo.html?limit=1000'\n session = session_with_proxy(extra_args)\n session.headers['user-agent'] = 'python-requests/2.21.0'\n soup = BeautifulSoup(session.get(catalogo_url).text, 'html.parser')\n containers = soup.findAll('li', 'itemsCatalogo')\n\n if not containers:\n raise Exception('No cells found')\n\n for idx, container in enumerate(containers):\n product_url = container.find('a')['href']\n if product_url.endswith('?codigo='):\n continue\n product_entries[product_url].append({\n 'category_weight': 1,\n 'section_name': 'Smartphones',\n 'value': idx + 1\n })\n\n return product_entries\n\n @classmethod\n def products_for_url(cls, url, category=None, extra_args=None):\n products = []\n if url == cls.prepago_url:\n # Plan Prepago\n p = Product(\n 'Movistar Prepago',\n cls.__name__,\n category,\n url,\n url,\n 'Movistar Prepago',\n -1,\n Decimal(0),\n Decimal(0),\n 'CLP',\n )\n products.append(p)\n elif url == cls.planes_url:\n # Plan Postpago\n products.extend(cls._plans(url, extra_args))\n elif 'catalogo.movistar.cl' in url:\n # Equipo postpago\n products.extend(cls._celular_postpago(url, extra_args))\n else:\n raise Exception('Invalid URL: ' + url)\n return products\n\n @classmethod\n def _plans(cls, url, extra_args):\n session = session_with_proxy(extra_args)\n session.headers['user-agent'] = 'python-requests/2.21.0'\n soup = BeautifulSoup(session.get(url, timeout=30).text, 'html5lib')\n products = []\n\n plan_containers = soup.findAll('div', 'mb-parrilla_col')\n\n for plan_container in plan_containers:\n print(plan_container)\n plan_link = plan_container.find('a')\n plan_url = plan_link['href']\n\n base_plan_name = 'Plan ' + plan_link.find('h3').text.strip()\n base_plan_name = base_plan_name.replace(' ', '')\n\n price_text = plan_container.find('div', 'mb-parrilla_price').find(\n 'p', 'price').text\n price = Decimal(remove_words(price_text.split()[0]))\n\n portability_suffixes = ['', ' Portabilidad']\n cuotas_suffixes = [\n ' (sin cuota de arriendo)',\n ' (con cuota de arriendo)'\n ]\n\n for portability_suffix in portability_suffixes:\n for cuota_suffix in cuotas_suffixes:\n plan_name = '{}{}{}'.format(\n base_plan_name, portability_suffix, cuota_suffix)\n\n products.append(Product(\n plan_name,\n cls.__name__,\n 'CellPlan',\n plan_url,\n url,\n plan_name,\n -1,\n price,\n price,\n 'CLP'\n ))\n\n return products\n\n @classmethod\n def _celular_postpago(cls, url, extra_args):\n print(url)\n session = session_with_proxy(extra_args)\n session.headers['user-agent'] = 'python-requests/2.21.0'\n ajax_session = session_with_proxy(extra_args)\n ajax_session.headers['Content-Type'] = \\\n 'application/x-www-form-urlencoded'\n ajax_session.headers['user-agent'] = 'python-requests/2.21.0'\n ajax_session.headers['x-requested-with'] = 'XMLHttpRequest'\n page = session.get(url)\n\n if page.status_code == 404:\n return []\n\n soup = BeautifulSoup(page.text, 'html.parser')\n base_name = soup.find('h1').text.strip()\n\n sku_color_choices = []\n for color_container in soup.find('ul', 'colorEMP').findAll('li'):\n color_element = color_container.find('a')\n sku = color_element['data-sku']\n color_id = color_element['data-id']\n color_name = color_element['data-nombre-color']\n sku_color_choices.append((sku, color_id, color_name))\n\n products = []\n\n base_url = url.split('?')[0]\n\n def get_json_response(_payload):\n _response = ajax_session.post(\n 'https://catalogo.movistar.cl/equipomasplan/'\n 'emp_detalle/planes',\n data=payload)\n\n return json.loads(_response.text)\n\n for sku, color_id, color_name in sku_color_choices:\n name = '{} {}'.format(base_name, color_name)\n\n for portability_type_id, portability_suffix in \\\n cls.portability_choices:\n\n if portability_type_id == 1:\n # Portabilidad\n\n # Sin arriendo\n\n payload = 'current%5Bsku%5D={}¤t%5Btype%5D=1&' \\\n 'current%5Bplan%5D=Plus+S+Cod_OAQ_Porta' \\\n '¤t%5Bpayment%5D=1¤t%5Bcode%5D=' \\\n ''.format(sku)\n json_response = get_json_response(payload)\n code = json_response['codeOfferCurrent']\n\n cell_url = '{}?codigo={}'.format(base_url, code)\n print('porta sin arriendo')\n print(cell_url)\n\n cell_soup = BeautifulSoup(session.get(cell_url).text,\n 'html.parser')\n json_soup = BeautifulSoup(json_response['planes']['html'],\n 'html.parser')\n\n price_container_text = cell_soup.find(\n 'div', 'boxEMPlan-int-costo-0').findAll(\n 'b')[1].text\n monthly_price = Decimal(\n re.search(\n r'\\$([\\d+.]+)',\n price_container_text).groups()[0].replace('.', '')\n )\n price = 18 * monthly_price\n\n for container in json_soup.findAll('article'):\n cell_plan_name = container['data-id']\n\n products.append(Product(\n name,\n cls.__name__,\n 'Cell',\n cell_url,\n cell_url,\n '{} - {} - {}'.format(sku, color_id,\n cell_plan_name),\n -1,\n price,\n price,\n 'CLP',\n cell_plan_name='{}'.format(cell_plan_name),\n cell_monthly_payment=Decimal(0)\n ))\n\n # Con arriendo\n\n has_arriendo_option = cell_soup.find(\n 'li', {'id': 'metodo2'})\n\n plan_containers = cell_soup.findAll('article')\n\n if has_arriendo_option:\n for container in plan_containers:\n cell_plan_name = container['data-id']\n price = Decimal(remove_words(container.find(\n 'strong', 'pie-price').text))\n\n monthly_payment_text = container.find(\n 'div', 'pie-detail').findAll('strong')[-1].text\n monthly_payment_text = re.search(\n r'\\$([\\d+.]+)',\n monthly_payment_text).groups()[0]\n cell_monthly_payment = Decimal(\n monthly_payment_text.replace('.', ''))\n\n products.append(Product(\n name,\n cls.__name__,\n 'Cell',\n cell_url,\n cell_url,\n '{} - {} - {} cuotas'.format(sku, color_id,\n cell_plan_name),\n -1,\n price,\n price,\n 'CLP',\n cell_plan_name='{} cuotas'.format(\n cell_plan_name),\n cell_monthly_payment=cell_monthly_payment\n ))\n elif portability_type_id == 3:\n # Nuevo\n # Sin arriendo\n\n payload = 'current%5Bsku%5D={}¤t%5Btype%5D=3&' \\\n 'current%5Bplan%5D=¤t%5Bmovistar1%5D=0&' \\\n 'current%5Bpayment%5D=1¤t%5Bcode%5D=' \\\n ''.format(sku)\n json_response = get_json_response(payload)\n code = json_response['codeOfferCurrent']\n\n cell_url = '{}?codigo={}'.format(base_url, code)\n print('nuevo')\n print(cell_url)\n\n cell_soup = BeautifulSoup(session.get(cell_url).text,\n 'html.parser')\n json_soup = BeautifulSoup(json_response['planes']['html'],\n 'html.parser')\n\n price_container_text = cell_soup.find(\n 'div', 'boxEMPlan-int-costo-0').findAll(\n 'b')[1].text\n monthly_price = Decimal(\n re.search(\n r'\\$([\\d+.]+)',\n price_container_text).groups()[0].replace('.', '')\n )\n price = 18 * monthly_price\n\n for container in json_soup.findAll('article'):\n # break\n cell_plan_name = container['data-id']\n\n products.append(Product(\n name,\n cls.__name__,\n 'Cell',\n cell_url,\n cell_url,\n '{} - {} - {}'.format(sku, color_id,\n cell_plan_name),\n -1,\n price,\n price,\n 'CLP',\n cell_plan_name='{}'.format(cell_plan_name),\n cell_monthly_payment=Decimal(0)\n ))\n\n return products\n","sub_path":"storescraper/stores/movistar.py","file_name":"movistar.py","file_ext":"py","file_size_in_byte":12479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"62850323","text":"\"\"\"Module for testing helper functions.\"\"\"\nfrom pytest import approx\nimport numpy as np\nimport tensorflow as tf\nfrom ..functions import log_loss\n\n\ndef test_log_loss(sample_predictions):\n tf.reset_default_graph()\n session = tf.Session()\n y_true, y_pred = sample_predictions\n\n def calc_log_loss(true_pred, pred):\n log_loss = (-true_pred * np.log(pred)) - (\n (1 - true_pred) * np.log(1 - pred))\n return log_loss\n\n calc_log_losses = np.vectorize(calc_log_loss)\n average_loss = np.mean(calc_log_losses(y_true, y_pred))\n test_average_loss = session.run(log_loss(y_true, y_pred, 1))\n session.close()\n\n assert test_average_loss == approx(average_loss)\n","sub_path":"sparseflow/tests/functions_test.py","file_name":"functions_test.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"398483772","text":"from os.path import join\n\nfrom Doc import doc\nfrom util import preprocess\nfrom util import DATA_DIR\n\n\"\"\"\n本文件实现两种展示结果的方法:\n1.命令行\n2.网页输出\n\n共同点是他们接受类Answer_query 中answer方法计算得出的\ndoc_index_scores 以及 query_tokens 作为输入\n\n读取源文件 经过分词、等步骤\n(需要保存源文件 的内容)\n\n做交集 看出哪些位置 有交叉\n使用 word_index sent_index 标出位置\n返回\n\n两个接口 对这个返回结果的方法处理不同\n\"\"\"\n\n\nclass Result(object):\n\n def __init__(self, doc_id, query_tokens, score, out):\n self.doc_id = doc_id\n self.query_tokens = query_tokens\n self.score = format(score, \".4f\")\n self.out = out\n\n self.doc_token_sents, self.num_sents, self.num_tokens = self.init_doc_sents()\n # 需要重点标出的区域\n self.highlight_pos = self.get_pos()\n self.highlights = self.get_highlights()\n\n def init_doc_sents(self):\n doc_path = join(DATA_DIR, str(self.doc_id) + '.story')\n document = doc(doc_path, return_sents_list=True)\n doc_sents = document.article + document.abstract\n # 返回文档中句子的长度 token的数量\n num_sents = len(doc_sents)\n doc_token_sents = list(map(preprocess, doc_sents))\n\n num_tokens = 0\n for sent in doc_token_sents:\n num_tokens += len(sent)\n\n return doc_token_sents, num_sents, num_tokens\n\n def get_pos(self):\n highlight_pos = []\n\n for sent_i, sent in enumerate(self.doc_token_sents):\n word_i_list = []\n for word_i, word in enumerate(sent):\n if word in self.query_tokens:\n word_i_list.append(word_i)\n if word_i_list:\n highlight_pos.append((sent_i, word_i_list))\n\n return highlight_pos\n\n def out_to_terminal(self):\n print(\"新闻ID: \", self.doc_id)\n print(\"相似度: \", self.score)\n print(\"搜索到的相关句子:\")\n print('\\n'.join(self.highlights))\n print(\"-\" * 50)\n\n def strong(self, word):\n if self.out == \"terminal\":\n OKGREEN = '\\033[92m'\n ENDC = '\\033[0m'\n return OKGREEN + word + ENDC\n else:\n return '<span style=\"color:blue;font-weight:bold\">' \\\n + word + \"</span>\"\n\n def get_highlights(self):\n highlights = []\n for sent_i, word_i_list in self.highlight_pos:\n for word_i in word_i_list:\n words = self.doc_token_sents[sent_i]\n words[word_i] = self.strong(words[word_i])\n highlight = str(sent_i + 1) + \" \" + \" \".join(words)\n highlights.append(highlight)\n\n return highlights\n\n\nclass Results(object):\n\n def __init__(self, doc_index_scores, query_tokens, out=\"terminal\"):\n assert out in ['terminal', 'html']\n self.doc_index_scores = doc_index_scores\n self.query_tokens = query_tokens\n self.out = out\n\n def get_results(self):\n results = []\n for doc_index, score in self.doc_index_scores.iteritems():\n result = Result(str(doc_index), self.query_tokens, score, self.out)\n results.append(result)\n return results\n\n def out_to_terminal(self):\n for result in self.get_results():\n result.out_to_terminal()\n","sub_path":"output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"610340682","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 21 13:58:38 2017\n\n@author: User\n\"\"\"\n\n#미국 S&P500 기업, wiki 백과에 올라온 기업 목록(위키 백과 상으로는 4월 초까지 업데이트 돼있음(5월4일 기준))\n\nfrom selenium import webdriver\nimport os\nimport time\nimport pandas as pd \nimport shutil\n\n###################################################################\n#################### 필요한 함수 정의 부분 #################\n###################################################################\n#입력한 폴더에 파일에서 한번이라도 등장한 종목과 코드 반환(key가 종목명이므로 같은 기업이 여러번 나올 경우 최근에 사용한 코드로 할거임(파일명 역순으로 해서....) )\ndef mk_comp_code_dict(file_nm):\n comp_code_dict = dict()\n list_file =pd.read_excel(file_nm)\n for code, comp in list_file.loc[:,['Ticker symbol', 'Security']].values:\n comp = comp.replace(' ', '_')\n comp = comp.replace(' ', '_')\n comp_code_dict[code] = comp\n return comp_code_dict\n\n\ndef file_copy_move(old, new):\n shutil.copy2(old, new)\n\n\ndef get_url(baseurl, stc_ecg, ccode, startdate, enddate):\n all_list = []\n all_list.append(stc_ecg)\n all_list.append(ccode)\n all_list.extend(startdate)\n all_list.extend(enddate)\n return baseurl.format(*all_list)\n\n\ndef get_google_comp_nm(driver, comp_code_dict, key):\n comp_name = driver.find_element_by_class_name('appbar-snippet-primary').text #google finance에 있는 기업 이름\n return comp_name\n\n\ndef data_down(driver):\n down_url = driver.find_element_by_class_name('nowrap').get_attribute('href') \n driver.get(down_url)\n\n\n\n\n###################################################################\n############# 변수 및 파라미터 설정 부분 ###################\n###################################################################\ndirectory = r\"C:\\Users\\User\\Documents\\bro_py\"\ndefault_dwld_dir =r'C:\\Users\\User\\Downloads'\n\n\n\n\nbaseurl = 'https://www.google.com/finance/historical?q={}%3A{}&&startdate={}+{}%2C+{}&enddate={}+{}%2C+{}'\nstartdate = ['Jan', 1, 1995]\nenddate = ['Apr', 1, 2017]\n\n\n\n\n#############################################################\n#################### 실행 부분 #######################\n#############################################################\nos.chdir(directory)\nwt_dir = r'Raw_DataSet\\SnP500' \nlist_dir ='Raw_DataSet\\\\corp_list\\\\'\n\n# 한번이라도 등장한 기업 목록 뽑기(code 기준으로 중복되는 기업명 제거, 남기는 기업명은 최근에 사용된 기업명)\ncomp_code_dict = mk_comp_code_dict(list_dir + 'S&P500_wiki.xlsx') \n\n\n#driver 실행 \ndriver = webdriver.Chrome(r\"crawler_code\\Chromdriver\\chromedriver.exe\")\ndriver.implicitly_wait(4)\n\n\n\nkrgog_comp_code_dict = dict() #key : 한글이름_영어이름, value : code\nnot_found_code = []\nfor key in comp_code_dict .keys():\n stk_ecg = 'NYSE'\n URL =get_url(baseurl, stk_ecg, key, startdate, enddate)\n driver.get(URL)\n \n \n try:\n time.sleep(0.2)\n comp_nm = get_google_comp_nm(driver, comp_code_dict , key)\n time.sleep(0.4)\n data_down(driver)\n krgog_comp_code_dict[key] = str(comp_code_dict[key]) + '(' + str(comp_nm) + ')'\n except:\n stk_ecg = 'NASDAQ'\n URL =get_url(baseurl,stk_ecg, key, startdate, enddate)\n driver.get(URL) \n try:\n time.sleep(0.2)\n comp_nm = get_google_comp_nm(driver, comp_code_dict , key)\n time.sleep(0.4)\n data_down(driver)\n krgog_comp_code_dict[key] = str(comp_code_dict[key]) + '(' + str(comp_nm) + ')'\n except: \n not_found_code.append(str(key)+ ':'+ str(comp_code_dict [key]))\n time.sleep(0.3)\n\nprint(\"---------------NYSE, NASDAQ 모두에서 코드가 검색되지 않는 기업들 ---------------------\")\nfor i in not_found_code:\n print(i) \n\ntime.sleep(2) # 다 받아 질 때 까지 기다려\n\n \n\n\nerr_text = '-------------------- 오류가 있는 부분 ------------------------\\n'\n\nif not os.path.exists(wt_dir):\n os.makedirs(wt_dir )\n\nfor key in comp_code_dict.keys():\n try:\n old = default_dwld_dir+'\\\\'+str(key)+'.csv'\n new = wt_dir +'\\\\' +str(comp_code_dict[key])+'_'+str(key)+'.csv'\n file_copy_move(old, new)\n except OSError:\n mod_nm = str(comp_code_dict[key]).replace('*', '-')\n new = wt_dir +'\\\\'+mod_nm+'_'+str(key)+'.csv'\n file_copy_move(old, new)\n err_text += str('회사명에 * 기호를 - 로 바꿈 code: %s, name: %s\\n'%(key, str(comp_code_dict[key])))\n except KeyError:\n err_text += str('google finance 검색 안된 기업 code: %s, name: %s\\n'%(key, str(comp_code_dict[key]))) \n except FileNotFoundError:\n err_text += str('google finance 검색은 됐지만, 자료 다운 못한 기업 code: %s, name: %s\\n'%(key, str(comp_code_dict[key])))\n\nerr_text += '-----------------------------------------------------\\n\\n'\nprint(err_text)\n\nwith open(list_dir+'\\\\SnP500_err_text.txt', \"w\") as err:\n err.write(err_text)\n ","sub_path":"crawler_code/financwr_SnP_v1.py","file_name":"financwr_SnP_v1.py","file_ext":"py","file_size_in_byte":5156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"458011668","text":"#!/usr/bin/env python\n\nfrom scapy.all import *\n\ndef spoof(pkt):\n src = pkt[IP].src\n dst = pkt[IP].dst\n sport = pkt[TCP].sport\n dport = pkt[TCP].dport\n seq = pkt[TCP].seq\n ack = pkt[TCP].ack if pkt[TCP].ack else 0\n\n ip = IP(src=dst, dst=src)\n tcp = TCP(sport=dport, dport=sport, flags=\"R\", ack=seq, seq=ack)\n send(ip/tcp, iface=\"enp0s3\")\n \nif __name__ == \"__main__\":\n filter_str = \"src host 10.0.2.4 and dst host 10.0.2.5 and dst port 22\"\n sniff(filter=filter_str, prn=spoof)\n","sub_path":"courses/su/cse644/Lab4_TCP/code/ssh_rst.py","file_name":"ssh_rst.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"590171166","text":"# -*- coding: utf-8 -*-\n\nimport os.path\nfrom tempfile import NamedTemporaryFile\n\nfrom flask import render_template\nfrom flask_script import Manager\n\nimport pytest\n\nfrom starterkit.hashedassets import HashAssetsCommand, HashedAssetNotFoundError, HashedAssets\n\nfrom .helpers import with_tst_request_context\n\n\ndef mktempfile():\n with NamedTemporaryFile() as fd:\n name = fd.name\n return name\n\n\n@with_tst_request_context\ndef test_hashed_assets(*args, **kwargs):\n test_app = kwargs[\"test_app\"]\n\n HashedAssets(test_app)\n\n assert render_template(\"tests/starterkit/hashedassets/hashedassets.html\")\n\n\n@pytest.mark.xfail(raises=HashedAssetNotFoundError)\n@with_tst_request_context\ndef test_hashed_asset_not_found_error(*args, **kwargs):\n test_app = kwargs[\"test_app\"]\n\n test_app.config[\"HASHEDASSETS_CATALOG\"] = \"\"\n HashedAssets(test_app)\n\n assert render_template(\"tests/starterkit/hashedassets/hashedassets.html\")\n\n\n@with_tst_request_context\ndef test_hash_assets_command(*args, **kwargs):\n test_app = kwargs[\"test_app\"]\n\n catalog_name = mktempfile()\n assert os.path.exists(catalog_name) is False\n test_app.config[\"HASHEDASSETS_CATALOG\"] = catalog_name\n manager = Manager(test_app)\n manager.add_command(\"hashassets\", HashAssetsCommand())\n manager.handle(\"what-the-hell-is-this?\", [\"hashassets\"])\n assert os.path.exists(catalog_name) is True\n","sub_path":"flask-app/starterkit/tests/test_hashedassets.py","file_name":"test_hashedassets.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"223504921","text":"#!/usr/bin/env python\n\n#背景图片:\nBackGround_MChess = 'MChessBoard.jpg'\n#两个国家的棋子:\nSKoreaChess = 'SKorea.png'\nNKoreaChess = 'NKorea.png'\n#黑叉\nBlock = 'Block_Black.png'\n#鼠标\nmouse = 'mouse.png'\n\n#导入pygame库\nimport pygame\n\n#导入MChess_Global.py\nimport MChess_Global\n\n#导入一些常用的函数和常量\nfrom pygame.locals import *\n\n#向sys模块借一个exit函数用来退出程序\nfrom sys import exit\n\n#初始化pygame,为使用硬件做准备\npygame.init()\n\n#创建了一个窗口\nscreen = pygame.display.set_mode((845, 715),0, 32)\n\n#设置窗口标题\npygame.display.set_caption(\"Milltary Chess\")\n\n#加载并转换图像\nbackground = pygame.image.load(BackGround_MChess).convert()\nSKorea = pygame.image.load(SKoreaChess).convert_alpha()\nNKorea = pygame.image.load(NKoreaChess).convert_alpha()\nBlock_Black = pygame.image.load(Block).convert_alpha()\nmouse_cursor = pygame.image.load(mouse).convert_alpha()\n\n#设置图像的宽和高与窗口相等\nwidth,height = background.get_size()\nbackground = pygame.transform.smoothscale(background,(845,715))\n\n#设置图像的宽和高与背景图的每个格子相匹配\nSKorea_width,SKorea_height = SKorea.get_size()\nNKorea_width,NKorea_height = NKorea.get_size()\nSKorea = pygame.transform.smoothscale(SKorea,(60,60))\nNKorea = pygame.transform.smoothscale(NKorea,(65,65))\nBlock_Black = pygame.transform.smoothscale(Block_Black,(70,70))\nmouse_cursor = pygame.transform.smoothscale(mouse_cursor,(80,60))\n\n# 二维数组存储整个棋盘(逻辑结构)\n# 初始化棋盘为0(空)\nMChessBoard = [([0] * 10) for i in range(13)]\n\n#初始化游戏\ndef CreatGame():\n #将朝鲜军队初始化:\n for N_x in range(13):\n for N_y in range(10):\n NKorea_pos = [N_x+1,N_y+1]\n if NKorea_pos in MChess_Global.NKorea_ArmyPos:\n MChessBoard[N_x][N_y] = 1\n if NKorea_pos in MChess_Global.NKorea_NavyPos:\n MChessBoard[N_x][N_y] = 1\n if NKorea_pos in MChess_Global.Peace_Zone:\n MChessBoard[N_x][N_y] = 3\n\n #将韩国军队初始化:\n for S_x in range(13):\n for S_y in range(10):\n SKorea_pos = [S_x+1, S_y+1]\n if SKorea_pos in MChess_Global.SKorea_ArmyPos:\n MChessBoard[S_x][S_y] = 2\n if SKorea_pos in MChess_Global.SKorea_NavyPos:\n MChessBoard[S_x][S_y] = 2\n\nCreatGame()\n\n#画出棋子\ndef GamePaint():\n #遍历二维数组,根据二维数组的值打印出棋子\n for pos_x in range(13):\n for pos_y in range(10):\n if MChessBoard[pos_x][pos_y] == 1:\n #pass\n screen.blit(NKorea, (pos_x*65, pos_y*65))\n if MChessBoard[pos_x][pos_y] == 2:\n screen.blit(SKorea, (pos_x*65, pos_y*65))\n if MChessBoard[pos_x][pos_y] == 3:\n screen.blit(Block_Black, (pos_x*65, pos_y*65))\n\n#回合计数(朝鲜率先发动进攻):\nturn = 1\n#记录鼠标点击次数:\nmouse_count = 0\n#标记当前选中的格子(初值为[0,0]):\nselected = [0,0]\n#标记攻击棋子:\nAttacker = [0,0]\n#标记被攻击棋子:\nVictim = [0,0]\n\ndef Attack(Attacker,Victim,int):\n #M_x = Victim[0]\n #M_y = Victim[1]\n M_x,M_y = Victim\n MChessBoard[M_x][M_y] = 0\n\n#游戏主循环\nwhile True:\n for event in pygame.event.get():\n # 接收到退出事件后退出程序\n if event.type == QUIT:\n exit()\n\n # 接收到鼠标点击的事件\n if event.type == MOUSEBUTTONDOWN:\n mouse_count = mouse_count + 1\n\n # 获得鼠标位置:\n x, y = pygame.mouse.get_pos()\n\n # 计算逻辑坐标:\n x_Checker = int (x / 65)\n y_Checker = int (y / 65)\n selected = [x_Checker, y_Checker]\n\n if mouse_count % 2 == 0:\n MChessBoard[x_Checker][y_Checker] = 0\n\n\n # 将背景图画在(0,0)的坐标处\n screen.blit(background, (0,0))\n\n # 画出棋子\n GamePaint()\n\n # 获得鼠标位置\n x, y = pygame.mouse.get_pos()\n # 计算光标的左上角位置\n x-= mouse_cursor.get_width() / 2\n y-= mouse_cursor.get_height() / 2\n # 把光标画上去\n screen.blit(mouse_cursor, (x, y))\n\n # 刷新一下画面\n pygame.display.update()","sub_path":"MChess/MChess_Main.py","file_name":"MChess_Main.py","file_ext":"py","file_size_in_byte":4324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"650311839","text":"#!/usr/bin/env python\nimport numpy as np\nimport matplotlib.pyplot as plt\n \n# data to plot\nNumber_of_groups = 13\nData = [ # [Method, File, (Ratios)]\n ['A', 'LI.class', (90, 55, 40, 65, 1, 2, 3, 4, 5, 6, 0, 1, 2)],\n ['B', 'LI.class', (85, 62, 54, 20, 1, 2, 3, 4, 5, 6, 0, 1, 2)],\n ['C', 'LI.class', (85, 62, 54, 20, 1, 2, 3, 4, 5, 6, 0, 1, 2)],\n ]\n \n# create plot\nfig, ax = plt.subplots()\nindex = np.arange(Number_of_groups)\nbar_width = 0.1\nopacity = 0.8\n \nrects1 = plt.bar(index, Data[0][2], bar_width,\n alpha=opacity,\n color='b',\n label='A, LI.class')\n \nrects2 = plt.bar(index + bar_width, Data[1][2], bar_width,\n alpha=opacity,\n color='g',\n label='B, LI.class')\n\nrects3 = plt.bar(index + bar_width*2, Data[2][2], bar_width,\n alpha=opacity,\n color='y',\n label='C, LI.class')\n \nplt.xlabel('Bytecode Method')\nplt.ylabel('Similarity Ratio')\nplt.title('Bytecode Analysis')\nplt.xticks(index + bar_width, ('createFrame', '\\nwriteDWord', 'writeWordBigEndian', \n '\\nwriteWord', 'writeDWordBigEndian', '\\nmethod403', \n 'writeQWord', '\\nwriteString', 'method424', \n '\\nmethod425', 'method431', '\\nmethod432', 'method433'))\nplt.legend()\n \nplt.tight_layout()\nplt.show()\n","sub_path":"Data Visualization Samples/Plotly_Bar_Graph_Example.py","file_name":"Plotly_Bar_Graph_Example.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"38157439","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Setting up vars\r\nfilepath = \"Gen70\\\\\"\r\next = \".npy\"\r\ngens = [\"10\", \"20\", \"30\", \"40\", \"50\", \"60\", \"70\"]\r\n\r\nfitness = []\r\ngpool = []\r\nmodels = []\r\ntest_acc = []\r\ntest_loss = []\r\ntrain_acc = []\r\ntrain_loss = []\r\n\r\nlfitness = False\r\nlgpool = False\r\nlmodels = False\r\nltest_acc = True\r\nltest_loss = True\r\nltrain_acc = True\r\nltrain_loss = True\r\n\r\n# Loading data\r\nfor gen in gens:\r\n\tif lfitness: fitness.append(np.load(filepath+\"fitness\"+gen+ext))\r\n\tif lgpool: gpool.append(np.load(filepath+\"gpool\"+gen+ext))\r\n\tif lmodels: models.append(np.load(filepath+\"models\"+gen+ext))\r\nif ltest_acc: test_acc = np.load(filepath+\"test_acc\"+gens[-1]+ext)\r\nif ltest_loss: test_loss = np.load(filepath+\"test_loss\"+gens[-1]+ext)\r\nif ltrain_acc: train_acc = np.load(filepath+\"train_acc\"+gens[-1]+ext)\r\nif ltrain_loss: train_loss = np.load(filepath+\"train_loss\"+gens[-1]+ext)\r\n\r\n# Postprocess data\r\n\r\nave_ep = lambda x: np.average(x, axis=1).T\r\nave_gen = lambda x: np.average(x[:,:,-1], axis=1)\r\nmax_gen = lambda x: np.max(x[:,:,-1], axis=1)\r\n\r\ntest_acc = np.array([i for i in test_acc if i])\r\ntest_loss = np.array([i for i in test_loss if i])\r\ntrain_acc = np.array([i for i in train_acc if i])\r\ntrain_loss = np.array([i for i in train_loss if i])\r\n\r\ntest_acc_ep = ave_ep(test_acc)\r\ntest_loss_ep = ave_ep(test_loss)\r\ntrain_acc_ep = ave_ep(train_acc)\r\ntrain_loss_ep = ave_ep(train_loss)\r\n\r\ntest_acc_gen_max = max_gen(test_acc)\r\ntest_acc_gen_ave = ave_gen(test_acc)\r\ntrain_acc_gen_max = max_gen(train_acc)\r\ntrain_acc_gen_ave = ave_gen(train_acc)\r\n\r\nprint(test_acc.shape)\r\nprint(test_acc_ep.shape)\r\nprint(test_acc_gen_max.shape)\r\nprint(test_acc_gen_ave.shape)\r\n\r\n#raise Exception\r\n\r\n# Setting up graphs\r\n\r\ngen_idx = [0, 10, 20, 30, 40, 50, 60, 69]\r\n\r\nlegend = [\"Generation {}\".format(i) for i in gen_idx]\r\n\r\n# Graphing epoch on x\r\n\r\nplt.figure(figsize = (10, 10))\r\n\r\nplt.subplot(2,2,1)\r\nplt.plot(train_loss_ep[:, gen_idx])\r\nplt.title('Model Loss On Training Dataset Per Epoch')\r\nplt.xlabel('Epoch')\r\nplt.ylabel('Training data loss')\r\nplt.legend(legend)\r\n\r\nplt.subplot(2,2,2)\r\nplt.plot(test_loss_ep[:, gen_idx])\r\nplt.title('Model Loss On Testing Dataset Per Epoch')\r\nplt.xlabel('Epoch')\r\nplt.ylabel('Testing data loss')\r\nplt.legend(legend)\r\n\r\nplt.subplot(2,2,3)\r\nplt.plot(train_acc_ep[:, gen_idx])\r\nplt.title('Model Accuracy On Training Dataset')\r\nplt.xlabel('Epoch')\r\nplt.ylabel('Training data Accuracy')\r\nplt.legend(legend)\r\n\r\nplt.subplot(2,2,4)\r\nplt.plot(test_acc_ep[:, gen_idx])\r\nplt.title('Model Accuracy On Testing Dataset')\r\nplt.xlabel('Epoch')\r\nplt.ylabel('Testing data Accuracy')\r\nplt.legend(legend)\r\n\r\n#print(\"Train loss graph dim=\" + str(train_loss[:, gen_idx].T.shape))\r\n\r\nplt.show()\r\n\r\n# Getting generational info\r\n\r\n\r\n\r\n# Graphing generation on x\r\n\r\nplt.figure(figsize = (10, 10))\r\n\r\nplt.subplot(2,2,1)\r\nplt.plot(train_acc_gen_max)\r\nplt.title('Maximum Model Accuracy on Training Dataset per Generation')\r\nplt.xlabel('Generation')\r\nplt.ylabel('Max Accuracy')\r\n\r\nplt.subplot(2,2,2)\r\nplt.plot(train_acc_gen_ave)\r\nplt.title('Average Model Accuracy on Training Dataset per Generation')\r\nplt.xlabel('Generation')\r\nplt.ylabel('Average Accuracy')\r\n\r\nplt.subplot(2,2,3)\r\nplt.plot(test_acc_gen_max)\r\nplt.title('Maximum Model Accuracy on Testing Dataset per Generation')\r\nplt.xlabel('Generation')\r\nplt.ylabel('Max Accuracy')\r\n\r\nplt.subplot(2,2,4)\r\nplt.plot(test_acc_gen_ave)\r\nplt.title('Average Model Accuracy on Testing Dataset per Generation')\r\nplt.xlabel('Generation')\r\nplt.ylabel('Average Accuracy')\r\n\r\nplt.show()","sub_path":"dataprocessing.py","file_name":"dataprocessing.py","file_ext":"py","file_size_in_byte":3546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"449577723","text":"import sys\r\nsys.stdin = open(\"이웃한요소와의차의절대값.txt\")\r\n\r\nN = int(input())\r\narr = [list(map(int, input().split())) for _ in range(N)]\r\n# print(arr)\r\n# 4 방향선언\r\ndx = [-1, 1, 0, 0]\r\ndy = [0, 0, -1, 1]\r\n# 2 for 문 순회\r\n\r\n\r\nsum = 0\r\nfor x in range(N):\r\n for y in range(N):\r\n # 4방향 순회\r\n for i in range(4):\r\n # 방향 설정\r\n testX = x + dx[i]\r\n testY= y + dy[i]\r\n # 인덱스 체크\r\n if testX < 0 or testX >= N: continue\r\n if testY < 0 or testY >= N: continue\r\n # 할 일\r\n sum += abs(arr[x][y] - arr[testX][testY])\r\nprint(sum)","sub_path":"python_bms/파이참/이웃한요소와의차의절대값.py","file_name":"이웃한요소와의차의절대값.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"595020141","text":"import torch\nimport torch.nn as nn\nfrom torch.nn.init import kaiming_normal_\nfrom . import model_utils\n\nclass FeatExtractor(nn.Module):\n def __init__(self, batchNorm=False, c_in=3, other={}):\n super(FeatExtractor, self).__init__()\n self.other = other\n self.conv1 = model_utils.conv(batchNorm, c_in, 64, k=3, stride=1, pad=1)\n self.conv2 = model_utils.conv(batchNorm, 64, 128, k=3, stride=2, pad=1)\n self.conv3 = model_utils.conv(batchNorm, 128, 128, k=3, stride=1, pad=1)\n self.conv4 = model_utils.conv(batchNorm, 128, 256, k=3, stride=2, pad=1)\n self.conv5 = model_utils.conv(batchNorm, 256, 256, k=3, stride=1, pad=1)\n self.conv6 = model_utils.deconv(256, 128)\n self.conv7 = model_utils.conv(batchNorm, 128, 128, k=3, stride=1, pad=1)\n\n def forward(self, x):\n out = self.conv1(x)\n out = self.conv2(out)\n out = self.conv3(out)\n out = self.conv4(out)\n out = self.conv5(out)\n out = self.conv6(out)\n out_feat = self.conv7(out)\n n, c, h, w = out_feat.data.shape\n out_feat = out_feat.view(-1)\n return out_feat, [n, c, h, w]\n\nclass Regressor(nn.Module):\n def __init__(self, batchNorm=False, other={}): \n super(Regressor, self).__init__()\n self.other = other\n self.deconv1 = model_utils.conv(batchNorm, 128, 128, k=3, stride=1, pad=1)\n self.deconv2 = model_utils.conv(batchNorm, 128, 128, k=3, stride=1, pad=1)\n self.deconv3 = model_utils.deconv(128, 64)\n self.est_normal= self._make_output(64, 3, k=3, stride=1, pad=1)\n self.other = other\n\n def _make_output(self, cin, cout, k=3, stride=1, pad=1):\n return nn.Sequential(\n nn.Conv2d(cin, cout, kernel_size=k, stride=stride, padding=pad, bias=False))\n\n def forward(self, x, shape):\n x = x.view(shape[0], shape[1], shape[2], shape[3])\n out = self.deconv1(x)\n out = self.deconv2(out)\n out = self.deconv3(out)\n normal = self.est_normal(out)\n normal = torch.nn.functional.normalize(normal, 2, 1)\n return normal\n\nclass PS_FCN(nn.Module):\n def __init__(self, fuse_type='max', batchNorm=False, c_in=3, other={}):\n super(PS_FCN, self).__init__()\n self.extractor = FeatExtractor(batchNorm, c_in, other)\n self.regressor = Regressor(batchNorm, other)\n self.c_in = c_in\n self.fuse_type = fuse_type\n self.other = other\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n kaiming_normal_(m.weight.data)\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def forward(self, x):\n img = x[0]\n img_split = torch.split(img, 3, 1)\n if len(x) > 1: # Have lighting\n light = x[1]\n light_split = torch.split(light, 3, 1)\n\n feats = []\n for i in range(len(img_split)):\n net_in = img_split[i] if len(x) == 1 else torch.cat([img_split[i], light_split[i]], 1)\n feat, shape = self.extractor(net_in)\n feats.append(feat)\n if self.fuse_type == 'mean':\n feat_fused = torch.stack(feats, 1).mean(1)\n elif self.fuse_type == 'max':\n feat_fused, _ = torch.stack(feats, 1).max(1)\n normal = self.regressor(feat_fused, shape)\n return normal\n\n","sub_path":"models/PS_FCN.py","file_name":"PS_FCN.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"426884207","text":"######################################################\n#\n#\t\t\t\t\tNOTICE!!\n#\t\tThis file was not meant to be part of the\n#\t\tassignment. This file is purely for \n#\t\tadministrative work. please ignore this file\n#\n######################################################\n\nfor x in range(10):\n\ty = 1\n\tfilename = \"superPeer\" + str(x) + \".conf\"\n\tconfig = open(filename, 'w+')\n\tconfig.write(\"LINEAR_LOCAL_PORT = \" + str(8000+x) + \"\\n\")\n\tconfig.write(\"LINEAR_NEIGHBOR_IP = 198.37.24.124\\n\")\n\tconfig.write(\"LINEAR_NEIGHBOR_PORT = \" + str(8000 + x + y) + \"\\n\")\n\tconfig.write(\"BROADCAST_SUPER_PEER_PORT = \" + str(7000+x) + \"\\n\")\n\tconfig.write(\"BROADCAST_SUPER_PEER_ID = \" + str(x) +\"\\n\")\n\tconfig.write(\"LEAF_NODE_PORT = \" + str(5000 + x) + \"\\n\")\n\t","sub_path":"Homework/PA2/SuperPeer/conf/superPeerGenerator.py","file_name":"superPeerGenerator.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"380632182","text":"\nclass KiwiJuiceEasy:\n \n def __init__(self):\n self.result = tuple()\n \n def thePouring(self, capacities, bottles, fromId, toId):\n \n capacities = list(capacities)\n bottles = list(bottles)\n \n for i,_ in enumerate(fromId):\n \n if bottles[fromId[i]] + bottles[toId[i]] <= capacities[toId[i]]:\n bottles[toId[i]] = bottles[fromId[i]] + bottles[toId[i]]\n bottles[fromId[i]] = 0\n \n else:\n bottles[fromId[i]] = bottles[fromId[i]] + bottles[toId[i]] - capacities[toId[i]]\n bottles[toId[i]] = capacities[toId[i]]\n \n self.result = tuple(bottles)\n print(self.result)\n \n return self.result\n\n\nkiwi = KiwiJuiceEasy()\n\nkiwi.thePouring((14, 35, 86, 58, 25, 62), (6, 34, 27, 38, 9, 60), (1, 2, 4, 5, 3, 3, 1, 0), (0, 1, 2, 4, 2, 5, 3, 1))\n\n","sub_path":"topcoder/Easy/KiwiJuiceEasy/KiwiJuiceEasy.py","file_name":"KiwiJuiceEasy.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"619578569","text":"class Solution:\n def isNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n try:\n # 用python自己的转换语句,如果可以转换成flaot类型,显然就是合法的字符串\n a = float(s)\n return True\n # 如果引发异常,那就不是合法的字符串\n except:\n return False\n\n\nclass Solution:\n def isNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n # 先把字符串左右的空格去掉\n s = s.strip()\n pointseen = False\n eseen = False\n numberseen = False\n numberaftere = True\n for i in range(len(s)):\n if s[i].isdigit():\n numberseen = True\n numberaftere = True\n elif s[i] == '.':\n if eseen or pointseen:\n return False\n elif s[i] == 'e':\n if eseen or not numberseen:\n return False\n numberaftere = False\n eseen = True\n elif s[i] == '-' or s[i] == '+':\n if i != 0 and s[i - 1] != 'e':\n return False\n else:\n return False\n return numberseen and numberaftere\n","sub_path":"valid_number_65.py","file_name":"valid_number_65.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"150850607","text":"# Preprocessing steps:\nimport os\nimport shutil\nimport pandas as pd\n\nsorted_folder = \"./sorted_classes\"\ntrain_folder = \"./sorted_classes/train\"\ntest_folder = \"./sorted_classes/test\"\nfrom_folder = \"./train/The Picnic Hackathon 2019/train/\"\n\ntrain_metadata = pd.read_csv('train.tsv', sep='\\t', header=0)\n\ntrain_split = 0.8\n\ntotal_train = 0\ntotal_test = 0\n\n# sort images by label\nfor row, column in train_metadata.iterrows():\n if not os.path.exists('sorted_classes'):\n os.makedirs('sorted_classes')\n if not os.path.exists('sorted_classes/' + column.label):\n os.makedirs('sorted_classes/' + column.label)\n # Change to match proper directory of data\n data_from = from_folder + column.file\n data_to = './sorted_classes/' + column.label + '/' + column.file\n\n shutil.copyfile(data_from, data_to)\n\ndef createFolder(folder_name, image_class):\n if not os.path.exists('sorted_classes/' + folder_name):\n os.makedirs('sorted_classes/%s' % folder_name)\n if not os.path.exists('sorted_classes/%s/%s' % (folder_name, image_class)):\n os.makedirs('sorted_classes/%s/%s' % (folder_name, image_class))\n\n print(\"Created folder for class [%s] in folder [%s]\" % (image_class, folder_name))\n return 'sorted_classes/%s/%s' % (folder_name, image_class)\n\ndef copyFiles(files_array, from_dir, to_dir):\n try:\n for file in files_array:\n shutil.copy(getPathForClass(from_dir, file), getPathForClass(to_dir, file))\n except Exception as e:\n print(\"error: %s\" % e)\n\ndef getPathForClass(folder, class_name):\n return \"%s/%s\" % (folder, class_name)\n\nfor dirname, _, files in os.walk(sorted_folder, followlinks=False):\n if len(files) == 0:\n print(\"Skipping, folder empty.\")\n continue\n\n image_class = dirname.split(\"\\\\\")[-1]\n print(\"Found class [%s]\" % image_class)\n\n train_folder = createFolder(\"train\", image_class)\n test_folder = createFolder(\"test\", image_class)\n\n total_images = len(files)\n train_index = int(round(total_images * train_split))\n\n print(\"Received [%s] as train folder, [%s] as test folder\" % (train_folder, test_folder))\n print(\"Copying [%d] files for train and [%d] files for test\" % (len(files[:train_index]), len(files[train_index + 1:])))\n copyFiles(files[:train_index], dirname, train_folder)\n copyFiles(files[train_index + 1:], dirname, test_folder)\n\n print(\"\")\n total_train += train_index\n total_test += len(files[train_index + 1:])\n\nprint(\"I copied [%d] files to train on, and [%d] files to test on.\" % (total_train, total_test))\n\n","sub_path":"split_test_train.py","file_name":"split_test_train.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"609244221","text":"from bs4 import BeautifulSoup\nimport argparse as ap\nimport requests, os, pickle, json, sys\n\n\ndef pull_ritual_html(ritual_code):\n url = \"https://order.ritual.co/menu/\" + ritual_code\n r = requests.get(url)\n encoding = r.encoding if 'charset' in r.headers.get('content-type', '').lower() else None\n soup = BeautifulSoup(r.content, \"lxml\") # BeautifulSoup produces HTML of webpage\n return(soup)\n\ndef pull_items(soup):\n output = []\n for menu in soup.find_all('div', attrs={'class':'menu-group'}):\n section_name = menu.h4.contents[0]\n if(section_name == 'MOST POPULAR'):\n continue\n for item in menu.ul.find_all('li'):\n item = item.a\n item_name = item.div.find(\"h2\").contents[0]\n price = item.div.find(\"span\").span.next[1:] + item.div.find(\"span\").sup.next\n try:\n description = item.p.contents[0]\n except:\n description = \"\"\n output.append([str(item_name), str(description), str(price.strip()), str(section_name), \"\"])\n return(output)\n\ndef write_menu(menu_items, foodie_id):\n foodie_id = foodie_id.replace('/', '-')\n script_dir = os.path.abspath(os.path.join(__file__ ,\"../..\"))\n print(\"Saving menu items at \" + script_dir + \"/output_menu_items/foodie/\" + foodie_id + \".txt\")\n with open(script_dir + \"/output_menu_items/foodie/\" + foodie_id + \".txt\", 'wb') as f:\n pickle.dump(menu_items, f)\n\ndef scrape_menu_ritual(ritual_code, foodie_id):\n soup = pull_ritual_html(ritual_code)\n output = {}\n output['Food'] = pull_items(soup)\n write_menu(output, foodie_id)\n\nif __name__ == '__main__':\n parser = ap.ArgumentParser()\n parser.add_argument('-r', '--ritual_code', help='Ritual Code', default='tokyo-lunch-box-catering-wells-calhoun-chicago/81dd')\n\n args = vars(parser.parse_args())\n ritual_code = args['ritual_code']\n scrape_menu_ritual(ritual_code, ritual_code)\n","sub_path":"scrape_menu_ritual.py","file_name":"scrape_menu_ritual.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"617424362","text":"from configurations import Configuration, values\nfrom urlparse import urljoin\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\nclass Base(Configuration):\n\n # Quick-start development settings - unsuitable for production\n # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n # SECURITY WARNING: keep the secret key used in production secret!\n SECRET_KEY = 'SECRET'\n\n ALLOWED_HOSTS = ['localhost']\n\n # Application definition\n DEFAULT_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.sites',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n )\n\n THIRD_PARTY_APPS = (\n 'bootstrap3',\n 'django_crontab',\n )\n\n LOCAL_APPS = (\n 'iuvo_app',\n )\n\n ALLAUTH_APPS = (\n 'allauth',\n 'allauth.account',\n 'allauth.socialaccount',\n 'allauth.socialaccount.providers.google',\n )\n\n INSTALLED_APPS = DEFAULT_APPS + THIRD_PARTY_APPS + LOCAL_APPS + ALLAUTH_APPS\n\n # ACCOUNT_ACTIVATION_DAYS = 3\n\n EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\n EMAIL_USE_TLS = True\n EMAIL_HOST = 'smtp.gmail.com'\n EMAIL_HOST_USER = 'XXXX'\n EMAIL_HOST_PASSWORD = 'XXXX'\n DEFAULT_FROM_EMAIL = 'Iuvo Staff <XXXX>'\n EMAIL_PORT = 587\n\n # Allauth config settings\n ACCOUNT_EMAIL_VERIFICATION = 'mandatory'\n ACCOUNT_EMAIL_REQUIRED = True\n # ACCOUNT_UNIQUE_EMAIL = False\n SOCIALACCOUNT_EMAIL_REQUIRED = True\n SOCIALACCOUNT_EMAIL_VERIFICATION = 'mandatory'\n SOCIALACCOUNT_PROVIDERS = {\n 'google':\n {'SCOPE': ['profile',],\n 'AUTH_PARAMS': {'access_type': 'online'}}\n }\n\n\n TEMPLATE_DIRS = (\n 'iuvo_app/templates/allauth',\n )\n\n MIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n )\n\n ROOT_URLCONF = 'iuvo.urls'\n\n WSGI_APPLICATION = 'iuvo.wsgi.application'\n\n DEBUG = False\n TEMPLATE_DEBUG = False\n\n # Database\n # https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'iuvodb',\n 'USER': 'iuvo_user',\n 'PASSWORD': 'XXXX',\n 'HOST': 'localhost',\n }\n }\n\n # Internationalization\n # https://docs.djangoproject.com/en/1.6/topics/i18n/\n\n LANGUAGE_CODE = 'en-us'\n\n TIME_ZONE = 'UTC'\n\n USE_I18N = True\n\n USE_L10N = True\n\n USE_TZ = True\n\n SITE_ID = 2\n\n LOGIN_URL = 'login'\n LOGOUT_URL = 'logout'\n LOGIN_REDIRECT_URL = '/'\n\n TEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.messages.context_processors.messages',\n 'django.contrib.auth.context_processors.auth',\n # Required by allauth template tags\n 'django.core.context_processors.request',\n # allauth specific context processors\n 'allauth.account.context_processors.account',\n 'allauth.socialaccount.context_processors.socialaccount',\n )\n\n AUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n 'allauth.account.auth_backends.AuthenticationBackend',)\n\n\nclass Dev(Base):\n # SECURITY WARNING: don't run with debug turned on in production!\n DEBUG = True\n TEMPLATE_DEBUG = True\n INSTALLED_APPS = Base.INSTALLED_APPS + ('debug_toolbar',)\n\n EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\n STATIC_URL = '/static/'\n\n STATICFILES_DIRS = (\n '/var/www/iuvo/static',\n )\n\n BOOTSTRAP3 = {\n 'jquery_url': urljoin(STATIC_URL, 'jquery.min.js'),\n 'base_url': urljoin(STATIC_URL, 'bootstrap-3.2.0-dist/'),\n 'css_url': urljoin(STATIC_URL, 'bootstrap.css'),\n 'theme_url': None,\n 'javascript_url': None,\n 'javascript_in_head': False,\n 'include_jquery': True,\n 'horizontal_label_class': 'col-md-2',\n 'horizontal_field_class': 'col-md-4',\n 'set_required': True,\n 'form_required_class': '',\n 'form_error_class': '',\n 'form_renderers': {\n 'default': 'bootstrap3.renderers.FormRenderer',\n },\n 'formset_renderers':{\n 'default': 'bootstrap3.renderers.FormsetRenderer',\n },\n 'field_renderers': {\n 'default': 'bootstrap3.renderers.FieldRenderer',\n 'inline': 'bootstrap3.renderers.InlineFieldRenderer',\n },\n }\n\n # run \"python manage.py crontab add\" to add jobs to crontab\n # run \"python manage.py crontab remove\" to remove jobs\n CRONJOBS = [\n # ('*/1 * * * *', 'iuvo_app.cron.send_with_username'),\n ('*/1 * * * *', 'iuvo_app.cron.send_notifications'),\n ('*/1 * * * *', 'iuvo_app.cron.send_3day_notifications'),\n # ('*/1 * * * *', 'iuvo_app.cron.test'),\n # # runs every day at midnight.\n # ('0 0 * * *', 'iuvo_app.cron.send_3day_notifications'),\n ]\n\nclass Prod(Base):\n ALLOWED_HOSTS = ['*']\n ADMINS = (\n ('James White', 'jwhite007@gmail.com'),\n )\n CACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n 'LOCATION': '127.0.0.1:11211'\n }\n }\n # Allauth setting\n ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'\n\n INSTALLED_APPS = Base.INSTALLED_APPS + ('s3_folder_storage',)\n\n # DEFAULT_FILE_STORAGE = 's3_folder_storage.s3.DefaultStorage'\n # DEFAULT_S3_PATH = \"media\"\n STATICFILES_STORAGE = 's3_folder_storage.s3.StaticStorage'\n STATIC_S3_PATH = \"static\"\n AWS_ACCESS_KEY_ID = 'XXXX'\n AWS_SECRET_ACCESS_KEY = 'XXXX'\n AWS_STORAGE_BUCKET_NAME = 'XXXX'\n\n # MEDIA_ROOT = '/%s/' % DEFAULT_S3_PATH\n # For use with http:\n # MEDIA_URL = '//s3.amazonaws.com/%s/media/' % AWS_STORAGE_BUCKET_NAME\n # For use with https:\n # MEDIA_URL = 'https://%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME\n STATIC_ROOT = \"/%s/\" % STATIC_S3_PATH\n # For use with http:\n # STATIC_URL = '//s3.amazonaws.com/%s/static/' % AWS_STORAGE_BUCKET_NAME\n # For use with https:\n STATIC_URL = 'https://%s.s3.amazonaws.com/static/' % AWS_STORAGE_BUCKET_NAME\n ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'\n\n BOOTSTRAP3 = {\n 'jquery_url': urljoin(STATIC_URL, 'jquery.min.js'),\n 'base_url': urljoin(STATIC_URL, 'bootstrap-3.2.0-dist/'),\n 'css_url': urljoin(STATIC_URL, 'bootstrap.css'),\n 'theme_url': None,\n 'javascript_url': None,\n 'javascript_in_head': False,\n 'include_jquery': True,\n 'horizontal_label_class': 'col-md-2',\n 'horizontal_field_class': 'col-md-4',\n 'set_required': True,\n 'form_required_class': '',\n 'form_error_class': '',\n 'form_renderers': {\n 'default': 'bootstrap3.renderers.FormRenderer',\n },\n 'formset_renderers':{\n 'default': 'bootstrap3.renderers.FormsetRenderer',\n },\n 'field_renderers': {\n 'default': 'bootstrap3.renderers.FieldRenderer',\n 'inline': 'bootstrap3.renderers.InlineFieldRenderer',\n },\n }\n\n CRONTAB_COMMAND_PREFIX = 'DJANGO_CONFIGURATION=Prod'\n # run \"python manage.py crontab add\" to add jobs to crontab\n # run \"python manage.py crontab remove\" to remove jobs\n CRONJOBS = [\n ('*/15 * * * *', 'iuvo_app.cron.send_notifications'),\n # # runs every day at midnight.\n ('0 0 * * *', 'iuvo_app.cron.send_3day_notifications'),\n ]","sub_path":"iuvo/iuvo/settings_ghver.py","file_name":"settings_ghver.py","file_ext":"py","file_size_in_byte":7782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"515100700","text":"from stacker.blueprints.base import Blueprint\nimport stacker.blueprints.variables.types as types\n\nfrom troposphere import (\n GetAtt,\n Ref,\n ec2,\n ecs,\n elasticloadbalancingv2 as elb,\n iam,\n logs,\n route53,\n)\n\n\nclass EcsWebStack(Blueprint):\n \"\"\"A blueprint for standing up a Web app on ECS with Fargate.\"\"\"\n\n VARIABLES = {\n \"Image\": {\n \"type\": str,\n \"description\": \"repo/image:tag for the image to run.\"\n },\n \"ContainerEnvironment\": {\n \"type\": dict,\n \"description\": \"Dict of the environment for the container.\"\n },\n \"DatabaseSecurityGroup\": {\n \"type\": types.EC2SecurityGroupId,\n \"description\": \"The database security group id.\"\n },\n # \"Domain\": {\n # \"type\": str,\n # \"description\": \"The fully qualified domain for this service.\"\n # },\n # \"DomainZoneId\": {\n # \"type\": str,\n # \"description\": \"The Route53 Zone ID to which add the domain.\"\n # },\n # \"SslCertificateArn\": {\n # \"type\": str,\n # \"description\": \"The ARN for your SSL certificate.\"\n # },\n \"PrivateSubnets\": {\n \"type\": types.EC2SubnetIdList,\n \"description\": \"Private subnets for EC2 instances running ecs.\"\n },\n \"PublicSubnets\": {\n \"type\": types.EC2SubnetIdList,\n \"description\": \"Public subnets for ALB.\"\n },\n \"ServiceDesiredCount\": {\n \"type\": int,\n \"description\": \"The desired number of tasks.\"\n },\n \"VpcId\": {\n \"type\": types.EC2VPCId,\n \"description\": \"The ID of the VPC to launch Fargage.\"\n },\n \"WebPort\": {\n \"type\": str,\n \"description\": \"The port to expose from the container to the web.\"\n },\n }\n\n @property\n def stacker_fqn(self):\n \"\"\"Get the fully qualified stacker name.\"\"\"\n return self.context.get_fqn(self.name)\n\n @property\n def variables(self):\n \"\"\"Access the variables!\"\"\"\n return self.get_variables()\n\n @property\n def ecs_assumed_role_policy(self):\n \"\"\"Assumed role policy doc for ECS\"\"\"\n return {\n \"Version\": \"2012-10-17\",\n \"Statement\": [{\n \"Sid\": \"\",\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"Service\": \"ecs-tasks.amazonaws.com\"\n },\n \"Action\": \"sts:AssumeRole\"\n }]\n }\n\n @property\n def task_role_policies(self):\n \"\"\"Return policy to grant to our tasks which fall outside of the normal ECS operations.\n\n These policies are needed so that the command center can manage Route53, ACM and\n CloudFormation resources in order to setup client applications under a subdomain.\n\n \"\"\"\n return [\n iam.Policy(\n PolicyName=\"CommandCenterStarPolicy\",\n PolicyDocument={\n \"Statement\": {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"acm:ListCertificates\",\n \"acm:RequestCertificate\",\n \"cloudfront:CreateDistribution\",\n \"cloudfront:GetDistribution\",\n \"cloudfront:TagResource\",\n \"route53:CreateHostedZone\",\n \"route53:GetHostedZone\",\n \"route53:GetChange\",\n \"route53:ListHostedZones\",\n ],\n \"Resource\": \"*\",\n }\n }),\n iam.Policy(\n PolicyName=\"CommandCenterACMPolicy\",\n PolicyDocument={\n \"Statement\": {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"acm:DescribeCertificate\",\n ],\n \"Resource\": [\"arn:aws:acm:us-east-1:*:certificate/*\"],\n }\n }),\n iam.Policy(\n PolicyName=\"CommandCenterRoute53ResourcePolicy\",\n PolicyDocument={\n \"Statement\": {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"route53:ChangeResourceRecordSets\",\n \"route53:ListResourceRecordSets\",\n ],\n \"Resource\": [\n \"arn:aws:route53:::hostedzone/*\",\n ],\n }\n }),\n iam.Policy(\n PolicyName=\"CommandCenterCFNPolicy\",\n PolicyDocument={\n \"Statement\": {\n \"Effect\": \"Allow\",\n \"Action\": [\n \"cloudformation:DescribeStacks\",\n \"cloudformation:CreateStack\",\n ],\n \"Resource\": [\n \"arn:aws:cloudformation:us-east-2:*:stack/*\",\n ],\n }\n }),\n ]\n\n def build_environment(self, extra_env_vars=None):\n \"\"\"Build the environment for the container.\"\"\"\n if extra_env_vars is None:\n extra_env_vars = []\n\n envvars = self.get_variables()[\"ContainerEnvironment\"]\n\n return extra_env_vars + [\n ecs.Environment(Name=key, Value=value) for key, value in envvars.iteritems()\n ]\n\n def create_log_group(self):\n \"\"\"Create a CloudFormation log group.\"\"\"\n return self.template.add_resource(\n logs.LogGroup(\"LogGroup\", LogGroupName=\"%s-ecs\" % (self.stacker_fqn)))\n\n def create_task_role(self):\n \"\"\"Give our containers permissions to execute AWS APIs\"\"\"\n return self.template.add_resource(\n iam.Role(\n \"TaskRole\",\n RoleName=\"%s-%s\" % (\"ecsTaskRole\", self.stacker_fqn),\n AssumeRolePolicyDocument=self.ecs_assumed_role_policy,\n Policies=self.task_role_policies))\n\n def create_task_execution_role(self):\n \"\"\"This gives ECS tasks authority to manage Load Balancers as well as other things.\"\"\"\n return self.template.add_resource(\n iam.Role(\n \"TaskExecutionRole\",\n RoleName=\"%s-%s\" % (\"ecsTaskExecRole\", self.stacker_fqn),\n AssumeRolePolicyDocument=self.ecs_assumed_role_policy,\n ManagedPolicyArns=[\n \"arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy\"\n ],\n ))\n\n def create_load_balancer_sg(self):\n \"\"\"Create a security group for the load balancer.\"\"\"\n return self.template.add_resource(\n ec2.SecurityGroup(\n \"LoadBalancerSecurityGroup\",\n GroupName=\"%s-load-balancer\" % (self.stacker_fqn),\n GroupDescription=\"LoadBalancer Security Group for %s\" % (self.stacker_fqn),\n SecurityGroupIngress=[\n ec2.SecurityGroupRule(\n CidrIp=\"0.0.0.0/0\",\n IpProtocol=\"tcp\",\n FromPort=\"80\",\n ToPort=\"80\",\n ),\n ec2.SecurityGroupRule(\n CidrIp=\"0.0.0.0/0\",\n IpProtocol=\"tcp\",\n FromPort=\"443\",\n ToPort=\"443\",\n )\n ],\n VpcId=Ref(\"VpcId\")))\n\n def create_service_sg(self):\n \"\"\"Create a security group for the service running our containers.\"\"\"\n service_sg = self.template.add_resource(\n ec2.SecurityGroup(\n \"EcsServiceSecurityGroup\",\n GroupName=\"%s-ecs-service\" % (self.stacker_fqn),\n GroupDescription=\"ECS Service Security Group for %s\" % (self.stacker_fqn),\n SecurityGroupEgress=[\n ec2.SecurityGroupRule(\n CidrIp=\"0.0.0.0/0\",\n IpProtocol=\"-1\",\n FromPort=\"-1\",\n ToPort=\"-1\",\n ),\n ],\n SecurityGroupIngress=[\n ec2.SecurityGroupRule(\n CidrIp=\"0.0.0.0/0\",\n IpProtocol=\"tcp\",\n FromPort=self.variables[\"WebPort\"],\n ToPort=self.variables[\"WebPort\"],\n ),\n ],\n VpcId=Ref(\"VpcId\")))\n\n self.template.add_resource(\n ec2.SecurityGroupIngress(\n \"DatabaseSecurityGroupIngress\",\n GroupId=Ref(\"DatabaseSecurityGroup\"),\n FromPort=\"5432\",\n ToPort=\"5432\",\n IpProtocol=\"tcp\",\n SourceSecurityGroupId=Ref(service_sg),\n ))\n\n return service_sg\n\n # def create_domain(self, app_lb):\n # \"\"\"Create domain record for our app!\"\"\"\n # self.template.add_resource(\n # route53.RecordSetType(\n # \"AppDomain\",\n # AliasTarget=route53.AliasTarget(\n # DNSName=GetAtt(app_lb, \"DNSName\"),\n # HostedZoneId=GetAtt(app_lb, \"CanonicalHostedZoneID\")),\n # HostedZoneId=self.variables[\"DomainZoneId\"],\n # Name=self.variables[\"Domain\"],\n # Type=\"A\",\n # ))\n\n def create_app_load_balancer(self):\n \"\"\"Create a load balancer for our app.\"\"\"\n app_lb = self.template.add_resource(\n elb.LoadBalancer(\n \"AppLoadBalancer\",\n SecurityGroups=[Ref(self.create_load_balancer_sg())],\n Subnets=Ref(\"PublicSubnets\"),\n Type=\"application\"))\n\n # self.create_domain(app_lb)\n\n app_lb_group = self.template.add_resource(\n elb.TargetGroup(\n \"AppLoadBalancerTargetGroup\",\n HealthCheckPath=\"/api/healthcheck\",\n Port=self.variables[\"WebPort\"],\n Protocol=\"HTTP\",\n TargetType=\"ip\",\n VpcId=Ref(\"VpcId\")))\n\n app_http_listener = self.template.add_resource(\n elb.Listener(\n \"AppHttpListener\",\n DefaultActions=[elb.Action(TargetGroupArn=Ref(app_lb_group), Type=\"forward\")],\n LoadBalancerArn=Ref(app_lb),\n Port=80,\n Protocol=\"HTTP\",\n ))\n\n # app_https_listener = self.template.add_resource(\n # elb.Listener(\n # \"AppHttpsListener\",\n # Certificates=[elb.Certificate(CertificateArn=self.variables[\"SslCertificateArn\"])],\n # DefaultActions=[elb.Action(TargetGroupArn=Ref(app_lb_group), Type=\"forward\")],\n # LoadBalancerArn=Ref(app_lb),\n # Port=443,\n # Protocol=\"HTTPS\",\n # ))\n\n ecs_balancer = ecs.LoadBalancer(\n ContainerName=\"web\",\n ContainerPort=self.variables[\"WebPort\"],\n TargetGroupArn=Ref(app_lb_group))\n\n # return {\"ecs_balancer\": ecs_balancer, \"listeners\": [app_http_listener, app_https_listener]}\n return {\"ecs_balancer\": ecs_balancer, \"listeners\": [app_http_listener]}\n\n def create_ecs_task(self, task_execution_role, task_role):\n \"\"\"Create the ECS task definition\"\"\"\n container_defintion = ecs.ContainerDefinition(\n Name=\"web\",\n Image=self.variables[\"Image\"],\n Essential=True,\n Environment=self.build_environment(\n extra_env_vars=[ecs.Environment(Name=\"MASTER\", Value=\"1\")]),\n LogConfiguration=ecs.LogConfiguration(\n LogDriver=\"awslogs\",\n Options={\n \"awslogs-region\": Ref(\"AWS::Region\"),\n \"awslogs-group\": Ref(self.create_log_group()),\n \"awslogs-stream-prefix\": self.stacker_fqn,\n \"awslogs-datetime-format\": \"%H:%M:%S\"\n }),\n HealthCheck=ecs.HealthCheck(Command=[\n \"CMD-SHELL\",\n \"curl -f http://localhost:%s/api/healthcheck || exit 1\" % (self.variables[\"WebPort\"])\n ]),\n PortMappings=[ecs.PortMapping(ContainerPort=self.variables[\"WebPort\"])])\n\n return self.template.add_resource(\n ecs.TaskDefinition(\n \"EcsTaskDefinition\",\n Cpu=\"256\",\n Family=self.stacker_fqn,\n Memory=\"512\",\n NetworkMode=\"awsvpc\",\n RequiresCompatibilities=[\"FARGATE\"],\n ExecutionRoleArn=GetAtt(task_execution_role, \"Arn\"),\n TaskRoleArn=GetAtt(task_role, \"Arn\"),\n DependsOn=[task_execution_role, task_role],\n ContainerDefinitions=[container_defintion]))\n\n def create_ecs_service(self):\n \"\"\"Create the ecs service that will serve up our app!\"\"\"\n cluster = self.template.add_resource(ecs.Cluster(\"Cluster\"))\n load_balancer = self.create_app_load_balancer()\n task_execution_role = self.create_task_execution_role()\n task_role = self.create_task_role()\n\n self.template.add_resource(\n ecs.Service(\n \"EcsService\",\n DependsOn=load_balancer[\"listeners\"],\n Cluster=Ref(cluster),\n DeploymentConfiguration=ecs.DeploymentConfiguration(\n MaximumPercent=300, MinimumHealthyPercent=100),\n DesiredCount=self.variables[\"ServiceDesiredCount\"],\n LaunchType=\"FARGATE\",\n TaskDefinition=Ref(self.create_ecs_task(task_execution_role, task_role)),\n LoadBalancers=[load_balancer[\"ecs_balancer\"]],\n NetworkConfiguration=ecs.NetworkConfiguration(\n AwsvpcConfiguration=ecs.AwsvpcConfiguration(\n AssignPublicIp=\"ENABLED\",\n Subnets=Ref(\"PrivateSubnets\"),\n SecurityGroups=[Ref(self.create_service_sg())]))))\n\n def create_template(self):\n \"\"\"Create the CFN template\"\"\"\n self.create_ecs_service()\n","sub_path":"template/infrastructure/blueprints/ecs_stack.py","file_name":"ecs_stack.py","file_ext":"py","file_size_in_byte":14457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"228010774","text":"import requests\nfrom bs4 import BeautifulSoup as BS\nimport json\nimport time\nfrom requests.exceptions import ConnectionError\n\n\n# with open('xbet.html', 'w', encoding='utf8') as html_file:\n# html_file.write(r.text)\n\nclass XBetParser:\n def __init__(self):\n self.url = 'https://1xstavka.ru/live/Basketball/'\n self.delay = 0.15\n self.main_headers = {\n 'Accept-Language': 'ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0'\n }\n\n def get_request_events(self):\n return [self.url], [self.main_headers]\n\n def get_events(self, response):\n soup = BS(response, 'lxml')\n champs = soup.select('.c-events__liga')\n champs_string = []\n for champ in champs:\n champs_string.append(champ.text.strip())\n events = soup.select('.c-events__item.c-events__item_col')\n events_info = []\n if not events:\n return events_info\n for i in range(0, len(events)):\n event_info = {}\n href = events[i].select('.c-events__name')[0]['href']\n #print(href)\n #print(len(events_info))\n if i != 0:\n try:\n if events_info[i-1]['href'].split('/')[-3] == href.split('/')[-3]:\n champ = events_info[i-1]['champ']\n else:\n champ = champs_string.pop(0)\n except IndexError:\n print(events)\n print(events_info)\n return []\n else:\n champ = champs_string.pop(0)\n teams = events[i].select('.c-events__team')\n if not teams:\n continue\n command1 = teams[0].text\n command2 = teams[1].text\n total_score = events[i].select('.c-events-scoreboard__cell.c-events-scoreboard__cell--all')\n if total_score:\n total_score1 = total_score[0].text\n total_score2 = total_score[1].text\n if not events[i].select('.c-events__time')[0].select('span'):\n continue\n time_event = events[i].select('.c-events__time')[0].select('span')[0].text\n scores = events[i].select('.c-events-scoreboard__cell')\n scores_1 = [int(el.text) for el in scores[1:int(len(scores) / 2)]]\n scores_2 = [int(el.text) for el in scores[int(len(scores) / 2 + 1):]]\n else:\n total_score1 = 0\n total_score2 = 0\n time_event = '00:00'\n scores_1 = 0\n scores_2 = 0\n event_info['href'] = href\n event_info['champ'] = champ\n event_info['command1'] = command1\n event_info['command2'] = command2\n event_info['total_score1'] = int(total_score1)\n event_info['total_score2'] = int(total_score2)\n event_info['scores_1'] = scores_1\n event_info['scores_2'] = scores_2\n event_info['time'] = time_event\n events_info.append(event_info)\n return events_info\n\n def get_request_value(self, href):\n id, split_href = self.get_id(href)\n url_koef = f'https://1xstavka.ru/LiveFeed/GetGameZip?id={id}&lng=ru&cfview=0&isSubGames=true&GroupEvents=true&allEventsGroupSubGames=true&countevents=250&partner=51&grMode=2'\n headers = self.main_headers\n headers['Referer'] = 'https://1xstavka.ru/' + id + split_href\n return url_koef, headers\n\n def selected_values(self, json_object):\n if json_object['Value']['GE']:\n value = {}\n for el in json_object['Value']['GE']:\n if el['G'] == 4:\n t_ot_m = [{'coef': t['C'], 'points':t['P']} for t in el['E'][0]]\n t_ot_s = [{'coef': t['C'], 'points':t['P']} for t in el['E'][1]]\n value['total_total'] = {'more': t_ot_m, 'smaller': t_ot_s}\n if el['G'] == 5:\n t_it_m_1 = [{'coef': t['C'], 'points':t['P']} for t in el['E'][0]]\n t_it_s_1 = [{'coef': t['C'], 'points':t['P']} for t in el['E'][1]]\n value['individ_total_1'] = {'more':t_it_m_1, 'smaller': t_it_s_1}\n if el['G'] == 6:\n t_it_m_2 = [{'coef': t['C'], 'points': t['P']} for t in el['E'][0]]\n t_it_s_2 = [{'coef': t['C'], 'points': t['P']} for t in el['E'][1]]\n value['individ_total_2'] = {'more': t_it_m_2, 'smaller': t_it_s_2}\n # if 'SG' in json_object['Value']:\n # value['id_quarter'] = str(json_object['Value']['SG'][-1]['I'])\n # if 'PN' in json_object['Value']['SG'][-1]:\n # value['name_quarter'] = json_object['Value']['SG'][-1]['PN']\n else:\n # ставок нету\n value = {}\n return value\n\n def get_id(self, url):\n return url.split('/')[-2].split('-')[0], url.split('/')[-2].replace(url.split('/')[-2].split('-')[0], '')+'/'\n\n def get_value(self, response):\n values_main_time = self.selected_values(json.loads(response))\n return values_main_time\n\n\nclass XBetParserTest:\n def get_events(self):\n try:\n with open(\"xbet_events.json\", \"r\") as file:\n return json.load(file)\n except PermissionError:\n time.sleep(2)\n with open(\"xbet_events.json\", \"r\") as file:\n return json.load(file)\n\n def get_value(self):\n try:\n with open(\"xbet_value.json\", \"r\") as file:\n return json.load(file)\n except PermissionError:\n time.sleep(2)\n with open(\"xbet_value.json\", \"r\") as file:\n return json.load(file)\n\n\nif __name__ == \"__main__\":\n parser = XBetParserTest()\n parser.get_events()\n while True:\n print(parser.get_value())","sub_path":"xbet.py","file_name":"xbet.py","file_ext":"py","file_size_in_byte":6021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"438291620","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\nfrom django.shortcuts import render,HttpResponse,redirect,reverse\nfrom django.http.response import JsonResponse\nfrom web.models import Host,Command\n\n# from .command_from import\nimport json\n\n#分页功能\nfrom utils.pagination import Pagination\n#搜索功能\nfrom django.db.models import Q\n\nfrom utils.ansible2.inventory import Inventory\nfrom utils.ansible2.runner import AdHocRunner,PlayBookRunner,CommandRunner\ndef command_issued(request):\n '''\n 命令下发页面\n :param request:\n :return:\n '''\n hosts = Host.objects.all()\n ips = [{\"id\": 1, \"pId\": 0, \"name\": \"随意勾选 1\", \"open\": \"true\"}]\n for h in hosts:\n ips.append({\"id\": 11, \"pId\": 1, \"name\": h.hostip})\n if request.method == \"POST\":\n #print(request.method)\n #<QueryDict: {'node_ips[]': ['192.168.179.140'], 'command': ['lsss'], 'csrfmiddlewaretoken': ['A1psD6C6JxS4L0A87GkkchrJJLUWx7DozsSBvxkHI0DnYztzOK9xfMKlTXvqYY6r']}>\n\n #按照上面的格式,应该这样👇取数据:\n\n # 取命令:\n print(\"POST\",request.POST)\n com = request.POST.get(\"command\")\n\n #取主机列表:\n node_ips=request.POST.getlist(\"node_ips[]\")\n # print(node_ips) #['192.168.179.140', '192.168.179.142']\n\n\n #通过上面获取的node_ips(主机ip列表),从host表获取hostip字段数据(hostip存在于node_ips列表中的数据)\n host_list=Host.objects.filter(hostip__in=node_ips)\n\n #执行command函数(传入主机ip,命令 两个参数)\n res=command(host_list,com)\n\n #将数据加到command表中:\n host=\" \".join(node_ips) #将node_ips列表转为字符串(列表形式也可以直接存到数据表,这样美观)\n Command.objects.create(hosts_list=host,result=res,user=request.account,command=com.strip().replace(\"\\n\",\",\"))\n return JsonResponse({\"status\":0,\"msg\":res})\n \n\n\n\n return render(request, \"command/commandissued.html\",{\"page_title\": \"命令下发\",\"ips\":ips})\n\n\ndef command_list(request):\n '''\n 命令日志(展示页面)\n :param request:\n :return:\n '''\n search = request.GET.get(\"table_search\", \"\")\n command = Command.objects.filter(Q(command__contains=search)|Q(user__name__contains=search)|Q(hosts_list__contains=search))\n pages = Pagination(request.GET.get(\"page\", 1), command.count(), request.GET.copy(), 15)\n return render(request, \"command/command_list.html\",\n {\"command\": command[pages.start:pages.end], \"page_html\": pages.page_html, \"page_title\": \"命令下发历史\"})\n\ndef command_details(request,pk):\n '''\n 命令下发历史详情展示\n :param request:\n :param pk:\n :return:\n '''\n command_obj=Command.objects.filter(pk=pk).first()\n\n return render(request,\"command/command_details.html\",{\"command_details\":command_obj})\n\ndef command(hostlist,com):\n '''\n 根据主机和命令,执行 本方法使用ansible api中的CommandRunner方法\n :param hostlist: 主机\n :param com: 命令\n :return:\n '''\n\n host_data = [{\"hostname\": h.hostip, \"ip\": h.hostip, \"port\": h.ssh_port} for h in hostlist]\n inventory = Inventory(host_data) # 重新组成虚拟组\n runner = CommandRunner(inventory)\n res = runner.execute(com) #执行命令\n return res.results_raw #返回结果","sub_path":"web/command/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":3362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"105736118","text":"import imageio \nimport os\nfrom PIL import Image\nimageio.plugins.ffmpeg.download()\n\n\n#---=== choose path of images you want to merged together into a video --- \npath = '/Users/swebb/Documents/DWF/sky_plots/DWF_world_plot/images/globe_final/'\n\n\n# --- create array of all files you want to merger from path ----- \nfilelist = []\nfiles = []\n\nfor filename in os.listdir(path):\n\tif filename.startswith('MOD_all_label_'): # or use .endswith to choose ext. type \n\t\tfiles.append(filename) # add filename to the array \n\t\t\nfiles.sort() # sort the files into accessending order \n\nwriter = imageio.get_writer('/Users/swebb/Documents/DWF/sky_plots/DWF_world_plot/images/DWF_World_15fps.mp4', fps = 15) #make path and name of video you want to create and choose frames per second with fps. \n\n# --- Create the video \nfor im in files:\n\twriter.append_data(imageio.imread(path + im)) \nwriter.close() \n\n","sub_path":"make_globe_video.py","file_name":"make_globe_video.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"305999197","text":"from math import ceil\nfrom typing import Union\nfrom sys import exit\n\n# 忘れないうちに、何が難しかったかめもしておくよ\n# - Leafと中間Nodeでの挙動の違い\n# データは p1 k1 p2 k2 ... pn-1 kn-1 pn というように並んでいる\n# 中間Nodeでは k_jが有効であれば、 p_j と p_j+1 も必ず有効 (そうでなければ走査が失敗する)\n# これに対し、Leafでは p_j は k_jの指すキーのデータポインタとしての役割しか果たしていない\n# また、中間Nodeではpnはkn-1以上の要素を指すのに対し、\n# Leftではpnはデータ構造を保つために、次のLeafを指している\n# こういった違いから、キーとポインターの挿入がLeafと中間Nodeでは異なったものとなっている\n# - 番兵の選択\n# ここでは、ループ不変式に「必ず左のキーは右のキーよりも小さい」ということを利用している\n# と目星を付け、INF(十分に巨大な数)を番兵とした\n\nKey = int\nPointer = str\nN = 3\nINF = 9999\n\n\ndef count(from_: int, to: int):\n return range(from_, to+1)\n\n\ndef down_to(from_: int, to: int):\n return range(from_, to - 1, -1)\n\n\nclass Node(object):\n def __init__(self, size=N-1):\n self.size = size\n self.p_body = [None] * (size+1)\n self.k_body = [INF] * size\n self.parent = None\n\n def p(self, index: int):\n return self.p_body[index - 1]\n\n def set_p(self, index: int, pointer):\n self.p_body[index - 1] = pointer\n\n def k(self, index: int) -> Key:\n return self.k_body[index - 1]\n\n def set_k(self, index: int, key: Key):\n self.k_body[index - 1] = key\n\n def insert_before_p1(self, P: Pointer, K: Key):\n for i in down_to(self.size - 1, 1):\n self.set_k(i + 1, self.k(i))\n for i in down_to(self.size - 1, 1):\n self.set_p(i + 1, self.p(i))\n self.set_p(1, P)\n self.set_k(1, K)\n\n # [Key]以下で最大、あるいはそれと等しいキーのindexを返す\n def highest_key_index_less_than_or_equal_to_arg(self, K: Key):\n prev = 1\n for i in count(1, self.size):\n if K >= self.k(i) > prev:\n prev = i\n return prev\n\n @property\n def is_not_full(self):\n return self.k(self.size) == INF\n\n @property\n def has_less_than_n_pointers(self) -> bool:\n return self.p(self.size+1) is None\n\n @property\n def smallest_key(self):\n return self.k(1)\n\n @property\n def is_leaf(self) -> bool:\n return isinstance(self.p(1), Pointer)\n\n def erase_p_and_k(self):\n self.p_body = [None] * (self.size+1)\n self.k_body = [INF] * self.size\n\n def erase_partly(self):\n tmp = self.p(N)\n self.erase_p_and_k()\n self.set_p(N, tmp)\n\n def clone(self):\n copy = Node()\n copy.p_body = self.p_body.copy()\n copy.k_body = self.k_body.copy()\n copy.parent = self.parent\n copy.size = self.size\n return copy\n\n def add_size(self, additional_size):\n for _ in count(1, additional_size):\n self.p_body.append(None)\n self.k_body.append(INF)\n self.size += additional_size\n\n def __str__(self):\n res = \"\"\n for i in count(1, self.size):\n res += \"(\" + str(self.p(i)) + \")\"\n res += \" \" + str(self.k(i)) + \" \"\n # res += \" parent -> (\" + str(self.parent) + \")\"\n return res\n\n def __repr__(self):\n return self.__str__()\n\n\nclass Tree:\n def __init__(self):\n self.root = None\n\n @property\n def is_empty(self) -> bool:\n return self.root is None\n\n\ntree = Tree()\n\n\ndef insert(K: Key, P: Pointer):\n if tree.is_empty:\n L = Node()\n tree.root = L\n else:\n L = search_leaf(tree.root, K)\n if L.is_not_full:\n insert_in_leaf(L, K, P)\n else:\n L_ = Node()\n T = L.clone()\n T.add_size(1)\n insert_in_leaf(T, K, P)\n L_.set_p(N, L.p(N))\n L.set_p(N, L_)\n L.erase_partly()\n for i in count(1, ceil(N / 2)):\n L.set_p(i, T.p(i))\n L.set_k(i, T.k(i))\n for i in count(ceil(N / 2) + 1, N):\n offset = ceil(N / 2)\n L_.set_p(i - offset, T.p(i))\n L_.set_k(i - offset, T.k(i))\n K_ = L_.smallest_key\n insert_in_parent(L, K_, L_)\n\n\ndef search_leaf(node: Node, contain: Key):\n if node.is_leaf:\n return node\n\n if 0 < contain < node.k(1):\n return search_leaf(node.p(1), contain)\n\n for i in count(1, node.size -1):\n if node.k(i) <= contain < node.k(i+1):\n return search_leaf(node.p(i+1), contain)\n\n if node.k(node.size) < contain:\n return search_leaf(node.p(node.size+1), contain)\n\n raise ValueError(\"Should not reach here\")\n\n\ndef insert_in_leaf(L: Node, K: Key, P: Pointer):\n if K < L.k(1):\n L.insert_before_p1(P, K)\n else:\n index = L.highest_key_index_less_than_or_equal_to_arg(K)\n # L.insert_after(i, P, K)\n for i in down_to(L.size - 1, index + 1): # p_index+1以降を一個ずらす\n L.set_k(i + 1, L.k(i))\n for i in down_to(L.size - 1, index + 1):\n L.set_p(i + 1, L.p(i))\n L.set_p(index + 1, P)\n L.set_k(index + 1, K)\n\ndef insert_in_parent(n: Node, K_: Key, N_: Union[Node, Pointer]):\n if n == tree.root:\n R = Node()\n R.set_p(1, n)\n n.parent = R\n R.set_k(1, K_)\n R.set_p(2, N_)\n N_.parent = R\n tree.root = R\n return\n P = n.parent\n if P.has_less_than_n_pointers:\n index = P.highest_key_index_less_than_or_equal_to_arg(K_)\n for ki in down_to(P.size-1, index+1):\n P.set_k(ki+1, P.k(ki))\n for pi in down_to(P.size, index+2):\n P.set_p(pi+1, P.p(pi))\n P.set_k(index+1, K_)\n P.set_p(index+2, N_)\n N_.parent = P\n else:\n T = P.clone()\n T.add_size(1)\n\n index = T.highest_key_index_less_than_or_equal_to_arg(K_)\n for ki in count(index + 1, T.size - 1):\n T.set_k(ki + 1, T.k(ki))\n for pi in count(index + 2, T.size - 1):\n T.set_p(pi + 1, T.p(pi))\n T.set_k(index + 1, K_)\n T.set_p(index + 2, N_)\n\n\n N_.parent = T # link parent\n P.erase_p_and_k()\n P_ = Node()\n for i in count(1, ceil((N+1)/2)-1):\n P.set_p(i, T.p(i))\n P.set_k(i, T.k(i))\n P.set_p(ceil((N+1)/2),T.p(ceil((N+1)/2)))\n K__ = T.k(ceil((N + 1) / 2))\n offset = ceil((N + 1) / 2)\n for i in count(ceil((N + 1) / 2)+1, N):\n P_.set_p(i - offset, T.p(i))\n P_.set_k(i - offset, T.k(i))\n P_.set_p(N+1 - offset, T.p(N+1))\n insert_in_parent(P, K__, P_)\n\n\nif __name__ == \"__main__\":\n insert(3, \"Dog\")\n insert(2, \"Cat\")\n insert(5, \"Wolf\")\n insert(4, \"God\")\n\n insert(6, \"God\")\n insert(1, \"God\")\n insert(10, \"God\")\n insert(7, \"Monkey\")\n insert(11, \"Monkey\")\n insert(13, \"Human\")\n insert(20, \"Ogiwara\")\n\n print(tree.root.p(2).p(2))\n\n","sub_path":"algorithm_introduction/bptree4.py","file_name":"bptree4.py","file_ext":"py","file_size_in_byte":7117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"99536187","text":"from QuickPotato.database.queries import Crud\nfrom QuickPotato.configuration.management import options\nfrom sqlalchemy_utils import database_exists\nfrom sqlalchemy import create_engine\nfrom demo.example_code import *\nimport unittest\n\nSAMPLE_SIZE = 1\nUNIT_TEST_DATABASE_NAME = \"quickprofiling\"\n\n\nclass TestUsage(unittest.TestCase):\n\n def setUp(self):\n \"\"\"\n\n \"\"\"\n options.enable_intrusive_profiling = True\n\n def tearDown(self):\n \"\"\"\n\n \"\"\"\n options.enable_intrusive_profiling = False\n self.clean_up_database()\n\n @staticmethod\n def clean_up_database():\n \"\"\"\n\n \"\"\"\n database_manager = Crud()\n database_manager.delete_result_database(UNIT_TEST_DATABASE_NAME)\n\n def test_profiling_outside_of_test_case(self):\n\n for _ in range(0, SAMPLE_SIZE):\n fast_method()\n\n # Checking if a database has been spawned\n database_manager = Crud()\n url = database_manager._validate_connection_url(UNIT_TEST_DATABASE_NAME)\n engine = create_engine(url, echo=True)\n\n self.assertTrue(database_exists(engine.url))\n","sub_path":"tests/test_upt_quick_profiling.py","file_name":"test_upt_quick_profiling.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"593729419","text":"import os\nimport cv2.data as cvdata\nfrom cv2 import cv2 \nimport numpy as np\n\ndef face_detector(frame):\n face_cascade = cv2.CascadeClassifier(cvdata.haarcascades + 'haarcascade_frontalface_default.xml')\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n if faces is not None:\n for (x,y,w,h) in faces: \n return frame[y:y+h, x:x+w, :]\n else:\n return None\n \ndef train():\n dir_name = os.getcwd() + '/datas/images/faces/'\n if not os.path.exists(dir_name):\n return 0\n\n onlyfiles = [f for f in os.listdir(dir_name) if os.path.isfile(os.path.join(dir_name,f))]\n\n Training_Data, Labels = list(), list()\n for i, files in enumerate(onlyfiles):\n image_path = dir_name + files\n images = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)\n Training_Data.append(np.asarray(images, dtype=np.uint8))\n Labels.append(i)\n\n Labels = np.asarray(Labels, dtype=np.int32)\n model = cv2.face.LBPHFaceRecognizer_create()\n model.train(np.asarray(Training_Data), np.asarray(Labels))\n model.save(\"tmp.yml\")\n\n \n\ndef test():\n model = cv2.face.LBPHFaceRecognizer_create()\n model.read(\"tmp.yml\")\n capture = cv2.VideoCapture(0)\n while capture.isOpened():\n ret, frame = capture.read()\n cascade_face = face_detector(frame)\n try:\n face = cv2.cvtColor(cascade_face, cv2.COLOR_BGR2GRAY)\n result = model.predict(face)\n display_string = ''\n if result[1] < 500:\n confidence = int(100*(1-(result[1]/300)))\n display_string = f'{confidence}% Confidence, '\n if confidence > 75:\n display_string = display_string + \"Unlocked\"\n else:\n display_string = display_string + \"Locked\"\n cv2.putText(frame, display_string, (250,450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)\n except:\n print(\"not Found\")\n cv2.imshow(\"frame\", frame)\n if cv2.waitKey(1)==ord('q'):\n break\n capture.release()\n cv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n # train()\n test()","sub_path":"DetectOwnFace_TrainLBPH.py","file_name":"DetectOwnFace_TrainLBPH.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"135242243","text":"import acm\nimport csv\nimport os\nimport calendar\nimport ChorusHierarchy\nimport at_logging\nfrom at_ael_variables import AelVariableHandler\n\nTODAY = acm.Time().DateToday()\nLASTMONTH = acm.Time().DateAdjustPeriod(TODAY, \"-1m\")\nFIRSTOFLASTMONTH = acm.Time().FirstDayOfMonth(LASTMONTH)\nyear, month, day = FIRSTOFLASTMONTH.split('-')\nLASTDAYOFFLASTMONTH = \"%s-%s-%s\" % (year, month, calendar.monthrange(int(year), int(month))[1])\nOUTPUTLOCATION = 'C:\\\\'\nFILENAME = 'SettlementsWithChorusHierarchy_%s-%s' % (year, month)\nLOGOUTPUT = True\nLOGGER = at_logging.getLogger()\n\n\n\ndef changeMode(varMode):\n varStartDate = ael_variables.get('start')\n varEndDate = ael_variables.get('end')\n\n if varMode.value == 'true':\n varStartDate.enabled = False\n varEndDate.enabled = False\n else:\n varStartDate.enabled = True\n varEndDate.enabled = True\n\nael_variables = AelVariableHandler()\n\nael_variables.add_bool('lastmonth',\n label='Generate for last month',\n default=True,\n hook=changeMode)\n\nael_variables.add('start',\n label='Start date',\n default=FIRSTOFLASTMONTH,\n enabled=False,\n cls='date')\n\nael_variables.add('end',\n label='End date',\n default=LASTDAYOFFLASTMONTH,\n enabled=False,\n cls='date')\n\nael_variables.add_directory('outputLocation',\n label='Output location',\n default=OUTPUTLOCATION)\n\n\ndef log(message):\n if LOGOUTPUT:\n LOGGER.info(message)\n\n\ndef getSettlements(startDate, endDate):\n log(\"Getting settlements from %s to %s\" % (startDate, endDate))\n settlements = acm.FSettlement.Select(\"valueDay>='%s' and valueDay<='%s'\" % (startDate, endDate))\n result = [sett.Oid() for sett in settlements]\n return result\n\n\ndef writeOutput(data, outputFile):\n emptyCell = 'N/A'\n if len(data) > 0:\n outputFile = \"%s.csv\" % outputFile\n outfile = open(outputFile, 'wb')\n writer = csv.writer(outfile, dialect='excel')\n\n head = [\"Settlement\", \"Parent settlement\", \"Trade\", \"Amount\", \"Currency\",\n \"Value Day\", \"Status\", \"Trans Ref\", \"Trade Counterparty\", \"Acquirer\",\n \"Portfolio\", \"Instrument Type\", \"Underlying instrument\",\n \"Funding InsType\", \"Counterparty type\", \"Cashflow type\"]\n chorusHeader = [\"MasterBookName\", \"MinorDeskName\", \"DeskName\", \"SubProductName\"]\n head.extend(chorusHeader)\n writer.writerow(head)\n\n for row in data:\n formattedRow = [cell if cell else emptyCell for cell in row]\n writer.writerow(formattedRow)\n outfile.close()\n log('Wrote output to %s' % outputFile)\n else:\n log(\"No data to write.\")\n\n\ndef isValid(settlement):\n if settlement.Amount() == 0.0:\n return False\n elif settlement.Status() == \"Void\":\n return False\n elif settlement.Trade() and (settlement.Trade().Instrument().OpenEnd() == \"Terminated\"):\n return False\n else:\n return True\n\n\ndef checkIfName(obj):\n return obj.Name() if obj else ''\n\n\ndef getReport(settlements):\n log(\"Generating report.\")\n report = []\n if len(settlements) > 0:\n log(\"Getting Chorus Hierarchy.\")\n chorus = ChorusHierarchy.ChorusDelegate()\n\n for settlementNumber in settlements:\n settlement = acm.FSettlement[settlementNumber]\n\n if isValid(settlement):\n trade = settlement.Trade()\n tradeCounterparty = trade.Counterparty() if trade else None\n portfolio = trade.Portfolio() if trade else None\n instype = trade.Instrument().InsType() if trade else None\n underlying = trade.Instrument().Underlying() if trade else None\n settlementCPType = settlement.Counterparty().Type() if settlement.Counterparty() else None\n cashflowType = settlement.CashFlow().CashFlowType() if settlement.CashFlow() else None\n transref = trade.TrxTrade().Name() if trade and trade.TrxTrade() else None\n fundingIns = trade.add_info(\"Funding Instype\") if trade else None\n parentSettlement = settlement.Parent().Oid() if settlement.Parent() else None\n\n row = [settlementNumber,\n parentSettlement,\n checkIfName(trade),\n settlement.Amount(),\n checkIfName(settlement.Currency()),\n settlement.ValueDay(),\n settlement.Status(),\n transref,\n checkIfName(tradeCounterparty),\n checkIfName(settlement.Acquirer()),\n checkIfName(portfolio),\n instype,\n checkIfName(underlying),\n fundingIns,\n settlementCPType,\n cashflowType,\n chorus.getMasterbook(portfolio),\n chorus.getMinordesk(portfolio),\n chorus.getDesk(portfolio),\n chorus.getSubproduct(portfolio)]\n\n report.append(row)\n\n return report\n else:\n log('No settlements for report.')\n return []\n\n\ndef ael_main(aelDict):\n log(\"-----START-----\")\n if aelDict['lastmonth'] == 1:\n start = FIRSTOFLASTMONTH\n end = LASTDAYOFFLASTMONTH\n else:\n start = aelDict['start']\n end = aelDict['end']\n path = aelDict['outputLocation'].SelectedDirectory().AsString()\n output = os.path.join(path, FILENAME)\n settlements = getSettlements(start, end)\n report = getReport(settlements)\n writeOutput(report, output)\n log(\"-----DONE-----\")\n","sub_path":"Python modules/SettlementsReport.py","file_name":"SettlementsReport.py","file_ext":"py","file_size_in_byte":5884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"568645366","text":"\"\"\"\nUtility file containing useful functionality for throughout the project.\n\"\"\"\n\nimport re\nfrom pathlib import Path\n\n# From https://github.com/sphinx-doc/sphinx/blob/4.x/sphinx/util/nodes.py\n_explicit_title_re = re.compile(r'^(.+?)\\s*(?<!\\x00)<([^<]*?)>$', re.DOTALL)\n\n# From Docutils:\n# https://github.com/docutils-mirror/docutils/blob/master/docutils/nodes.py\n_non_id_chars = re.compile('[^a-z0-9/]+')\n_non_id_at_ends = re.compile('^[-0-9]+|-+$')\n\n\ndef link_explicit(link: str):\n \"\"\"Check whether the link format is a 'explicit link'.\n\n Explicit links are of the format:\n Link Title <link_ref>\n If this is the case, return tuple (Title, Reference).\n Otherwise return None.\n \"\"\"\n res = _explicit_title_re.match(link)\n if res:\n title = res.group(1)\n ref = res.group(2)\n return (title, ref)\n\n return None\n\n\n# https://stackoverflow.com/questions/4984647/accessing-dict-keys-like-an-attribute\nclass Config(dict):\n \"\"\"\n Dictionary that can be accessed using attributes\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"\n Initialize Config\n \"\"\"\n super(Config, self).__init__(*args, **kwargs)\n self.__dict__ = self\n\n\ndef make_id(ref: str) -> str:\n \"\"\"Convert a string to an id format.\"\"\"\n ref_list = ref.split('#')\n\n for i, ref in enumerate(ref_list):\n ref = str(Path(ref).with_suffix(''))\n ref = ref.lower()\n ref = _non_id_chars.sub('-', ' '.join(ref.split()))\n ref = _non_id_at_ends.sub('', ref)\n ref_list[i] = ref\n\n return '#'.join(ref_list)\n","sub_path":"src/quaker_lib/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"364572883","text":"'''\nCreated on 10 nov. 2017\n\n@author: Vincent RICHAUD\n'''\nimport pickle\nimport os\nfrom Plant import Plant\n\nclass PlantsDict(object):\n '''\n This class is a dictionary containing all the plants known by the system\n '''\n\n DEFAULT_PATH = \"../data/plants\"\n\n def __init__(self, pathToPlantsFile=DEFAULT_PATH):\n '''\n Constructor\n '''\n #If the path is the default check for the file to exists\n if pathToPlantsFile == PlantsDict.DEFAULT_PATH:\n #if it does not exist, create it\n if not os.path.isfile(pathToPlantsFile):\n if not os.path.isdir(os.path.dirname(pathToPlantsFile)):\n os.makedirs(os.path.dirname(pathToPlantsFile))\n file = open(pathToPlantsFile, 'wb')\n file.close()\n self._plants = {}\n self._setPath(pathToPlantsFile)\n \n def __str__(self, *args, **kwargs):\n return str(self.__dict__)\n \n#Getters and Setters\n def _setPath(self, path):\n if type(path) is str:\n if os.path.isfile(path):\n self._path = path\n else:\n raise ValueError(\"Param 'path' given does not refer to an existing file\")\n else:\n raise TypeError(\"Param 'path' given is not of type str\")\n \n def _getPath(self):\n return self._path\n \n def _setPlants(self, plants):\n if type(plants) is dict:\n for plant in plants.values():\n if type(plant) is Plant:\n self._plants[plant.name] = plant\n else:\n raise TypeError(\"Param 'plants' given is not a dictionary\")\n \n def _getPlants(self):\n return self._plants\n \n#Properties\n plants = property(_getPlants, _setPlants)\n path = property(_getPath, _setPath)\n \n#functions\n def loadPlantsFromFile(self):\n '''\n Load the dictionary with the plants in the file define by the path\n '''\n if os.stat(self._path).st_size != 0 : \n try:\n with open(self._path, \"rb\") as plantsFile:\n unpickler = pickle.Unpickler(plantsFile)\n self._setPlants(unpickler.load())\n del unpickler\n except IOError:\n print(\"Error, the file {} couldn't be loaded\".format(self.path))\n \n def addPlant(self, plant):\n '''\n add a plant to the dictionary\n if the plant already exists, its updated\n '''\n if type(plant) is Plant:\n self._plants[plant.name] = plant\n else:\n raise TypeError(\"Param 'plant' given is not of Type src.Plant\")\n \n def findPlant(self, name):\n '''\n Find the plant in the dictionary having the given name\n return None if there is no plant with this name in the dictionary\n '''\n if type(name) is str:\n if name in self._plants:\n return self._plants[name]\n else:\n return None\n else :\n raise TypeError(\"Param 'name' given is not of type str\")\n \n def removePlant(self, name):\n '''\n Delete the plant having the given name in the dictionary\n '''\n if type(name) is str:\n if name in self._plants:\n del self._plants[name]\n else :\n raise TypeError(\"Param 'name' given is not of type str\")\n \n def saveInFile(self):\n '''\n save the dictionary on the file define by path\n Return True if it succeed\n '''\n try:\n with open(self._path, 'wb') as file:\n pickler = pickle.Pickler(file)\n pickler.dump(self._plants)\n return True\n except IOError:\n print(\"IOError couldn't write the plants file {}\").format(self._path)\n return False\n","sub_path":"src/PlantsDict.py","file_name":"PlantsDict.py","file_ext":"py","file_size_in_byte":3903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"456109554","text":"from django.shortcuts import render_to_response\nfrom django.contrib.auth.decorators import login_required\nfrom localground.apps.site.decorators import process_project\nfrom django.template import RequestContext\nfrom localground.apps.site.models import Project\n\n\n@login_required\n@process_project\ndef init_upload_form(request,\n media_type='default',\n template_name='forms/uploader.html',\n base_template='base/base_new.html',\n embed=False, project=None):\n if embed:\n base_template = 'base/iframe_new.html'\n\n projects = Project.objects.get_objects(request.user)\n image_types = 'png, jpg, jpeg, gif'\n audio_types = 'audio\\/x-m4a, m4a, mp3, m4a, mp4, mpeg, video\\/3gpp, 3gp, aif, aiff, ogg, wav'\n media_types = [(\n 'default',\n 'Photo & Audio Files',\n image_types + ', ' + audio_types,\n '/upload/'\n ),(\n 'map-images',\n 'Paper Maps',\n image_types,\n '/upload/map-images/'\n )\n ]\n selected_media_type = (None, 'Error')\n for mt in media_types:\n if mt[0] == media_type:\n selected_media_type = mt\n extras = {\n 'media_types': media_types,\n 'selected_media_type': selected_media_type,\n 'embed': embed,\n 'base_template': base_template,\n 'projects': projects,\n 'selected_project': project,\n 'selected_project_id': project.id,\n 'image_types': image_types,\n 'audio_types': audio_types\n }\n return render_to_response(template_name, extras,\n context_instance=RequestContext(request))\n","sub_path":"apps/site/views/uploader.py","file_name":"uploader.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"68804788","text":"# -*- coding: utf-8 -*-\nfrom django.test import TestCase\n\nfrom apps.supervisor.models import Supervisor\nfrom apps.casaestudiantil.models import CasaEstudiantil\nfrom apps.casaestudiantil.models import DescripcionCasa\nfrom apps.comedor.models import Comedor\n\nfrom apps.solicitante.models import Domicilio\nfrom apps.solicitante.models import Municipio\nfrom apps.solicitante.models import Estado\nfrom apps.solicitante.models import Telefono\n\nfrom django.core.exceptions import ValidationError\n\n\nclass ModelsTest(TestCase):\n def setUp(self):\n self.estado = Estado.objects.create(\n estado=\"Zacatecas\"\n )\n self.municipio = Municipio.objects.create(\n municipio=\"Zacatecas\",\n estado_fk=self.estado,\n )\n self.domicilio = Domicilio.objects.create(\n numero='311',\n calle='Preparatoria',\n colonia=\"Centro\",\n codigo_postal=\"98000\",\n estado=self.estado,\n municipio=self.municipio,\n )\n self.domicilio_casa = Domicilio.objects.create(\n numero='311',\n calle='Preparatoria',\n colonia=\"Centro\",\n codigo_postal=\"98000\",\n estado=self.estado,\n municipio=self.municipio,\n )\n self.telefono = Telefono.objects.create(\n telefono=\"4921001212\",\n tipo=\"FIJO\",\n )\n self.telefono_casa = Telefono.objects.create(\n telefono=\"4921011112\",\n tipo=\"FIJO\",\n )\n self.comedor = Comedor.objects.create(\n nombre=\"INGENIERIA\",\n telefono_fk=self.telefono,\n domicilio_fk=self.domicilio,\n )\n\n self.descripcion_casa = DescripcionCasa.objects.create(\n nombre_dueno=\"CASE UAZ\",\n capacidad = 100,\n camas = 50,\n cuartos = 15,\n sillas = 5,\n cocinas = 3,\n banios = 5,\n )\n\n self.casa_estudiantil = CasaEstudiantil.objects.create(\n nombre=\"MODULO A\",\n telefono_fk=self.telefono_casa,\n domicilio_fk=self.domicilio_casa,\n descripcion_casa_fk=self.descripcion_casa,\n )\n self.supervisor = Supervisor.objects.create(\n nombre='', # se modifica este campo para la pruea test_cannot\n apellido_paterno=\"Rodriguez\",\n apellido_materno=\"Aguayo\",\n comedor_fk=self.comedor,\n casas_estudiantil_fk=self.casa_estudiantil,\n )\n\n\n def test_guardando_y_recuperando_datos_supervisor(self):\n self.supervisor.save()\n saved_supervisor = Supervisor.objects.first()\n self.assertEqual(saved_supervisor, self.supervisor)\n saved_supervisores = Supervisor.objects.all()\n self.assertEqual(saved_supervisores.count(), 1)\n first_saved_supervisor = saved_supervisores[0]\n self.assertEqual(first_saved_supervisor.nombre,\n '')\n self.assertEqual(first_saved_supervisor.apellido_paterno,\n 'Rodriguez')\n self.assertEqual(first_saved_supervisor.apellido_materno,\n 'Aguayo')\n self.assertEqual(first_saved_supervisor.comedor_fk.telefono_fk,\n self.telefono)\n self.assertEqual(first_saved_supervisor.comedor_fk.domicilio_fk,\n self.domicilio)\n\n self.assertEqual(first_saved_supervisor.casas_estudiantil_fk.telefono_fk,\n self.telefono_casa)\n self.assertEqual(first_saved_supervisor.casas_estudiantil_fk.domicilio_fk,\n self.domicilio_casa)\n\n def test_no_se_puede_guardar_registros_vacios(self):\n with self.assertRaises(ValidationError):\n self.supervisor.save()\n self.supervisor.full_clean()\n\n def test_get_absolute_url(self):\n self.assertEqual('/supervisor/', u'/supervisor/')\n\n def test_duplicate_items_are_invalid(self):\n supervisor = self.supervisor\n with self.assertRaises(ValidationError):\n supervisor = self.supervisor\n supervisor.full_clean()\n supervisor.save()\n\n\n\n","sub_path":"apps/supervisor/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":4184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"511380883","text":"from flask import Flask\nfrom flask import request\nfrom flask import request, redirect, render_template\n\napp = Flask(__name__, template_folder=\"template\", static_url_path='/static')\n\n\n@app.route('/')\ndef hello():\n return \"Hello world!\"\n\n\n@app.route('/weather/', methods=['get'])\ndef weather():\n date = request.args.get('date', default=\"2019-08-12\")\n # weather_data = db.query(\"select weather data where date = 2019-08-12\")\n # weather_data = request.get(\"http://weather.open.map:8080/date=2019-08-12\")\n weather_data = \"28c\"\n #return render_template('index.html', data=weather_data, date = date)\n return date + \" weather is \" + (weather_data)\n\n\n@app.route('/humidity/', methods=['get'])\ndef humidity():\n date = request.args.get('date', default=\"2019-08-12\")\n # weather_data = db.query(\"select weather data where date = 2019-08-12\")\n # weather_data = request.get(\"http://weather.open.map:8080/date=2019-08-12\")\n weather_data = \"54%\"\n return \"humidity is \" + (weather_data)\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"501779587","text":"import pytest\n\nimport os\nimport numpy as np\n\nimport resqpy.model as rq\nimport resqpy.grid as grr\nimport resqpy.property as rqp\nimport resqpy.derived_model as rqdm\nimport resqpy.olio.weights_and_measures as bwam\n\n\n# ---- Test PropertyCollection ---\n\n# TODO\n\n\n# ---- Test Property ---\n\ndef test_property(tmp_path):\n epc = os.path.join(tmp_path, 'test_prop.epc')\n model = rq.new_model(epc)\n grid = grr.RegularGrid(model, extent_kji = (2, 3, 4))\n grid.write_hdf5()\n grid.create_xml()\n a1 = np.random.random(grid.extent_kji)\n p1 = rqp.Property.from_array(model, a1, source_info = 'random', keyword = 'NETGRS', support_uuid = grid.uuid,\n property_kind = 'net to gross ratio', indexable_element = 'cells', uom = 'm3/m3')\n pk = rqp.PropertyKind(model, title = 'facies', parent_property_kind = 'discrete')\n pk.create_xml()\n facies_dict = {0: 'background'}\n for i in range(1, 10): facies_dict[i] = 'facies ' + str(i)\n sl = rqp.StringLookup(model, int_to_str_dict = facies_dict, title = 'facies table')\n sl.create_xml()\n shape2 = tuple(list(grid.extent_kji) + [2])\n a2 = (np.random.random(shape2) * 10.0).astype(int)\n p2 = rqp.Property.from_array(model, a2, source_info = 'random', keyword = 'FACIES', support_uuid = grid.uuid,\n local_property_kind_uuid = pk.uuid, indexable_element = 'cells', discrete = True,\n null_value = 0, count = 2, string_lookup_uuid = sl.uuid)\n model.store_epc()\n model = rq.Model(epc)\n ntg_uuid = model.uuid(obj_type = p1.resqml_type, title = 'NETGRS')\n assert ntg_uuid is not None\n p1p = rqp.Property(model, uuid = ntg_uuid)\n assert np.all(p1p.array_ref() == p1.array_ref())\n assert p1p.uom() == 'm3/m3'\n facies_uuid = model.uuid(obj_type = p2.resqml_type, title = 'FACIES')\n assert facies_uuid is not None\n p2p = rqp.Property(model, uuid = facies_uuid)\n assert np.all(p2p.array_ref() == p2.array_ref())\n assert p2p.null_value() is not None and p2p.null_value() == 0\n grid = model.grid()\n assert grid.property_collection.number_of_parts() == 5 # two created here, plus 3 regular grid cell lengths properties\n\n\ndef test_create_Property_from_singleton_collection(tmp_model):\n\n # Arrange\n grid = grr.RegularGrid(tmp_model, extent_kji = (2, 3, 4))\n grid.write_hdf5()\n grid.create_xml(add_cell_length_properties = True)\n collection = rqp.selective_version_of_collection(grid.property_collection, property_kind = 'cell length',\n facet_type = 'direction', facet='J')\n assert collection.number_of_parts() == 1\n # Check property can be created\n prop = rqp.Property.from_singleton_collection(collection)\n assert np.all(np.isclose(prop.array_ref(), 1.0))\n\n\n# ---- Test uom from string ---\n\n\n@pytest.mark.parametrize(\"case_sensitive, input_uom, expected_uom\", [\n (False, 'gapi', 'gAPI'),\n (True, 'gapi', 'Euc'),\n (False, 'm', 'm'),\n (False, 'M', 'm'),\n (True, 'foobar', 'Euc'),\n (True, '', 'Euc'),\n (False, 'gal[UK]/mi', 'gal[UK]/mi'),\n (False, 'GAL[UK]/MI', 'gal[UK]/mi'),\n (False, None, 'Euc'),\n])\ndef test_uom_from_string(case_sensitive, input_uom, expected_uom):\n validated_uom = rqp.validate_uom_from_string(input_uom, case_sensitive=case_sensitive)\n assert expected_uom == validated_uom\n\n\n# ---- Test property kind parsing ---\n\n\ndef test_property_kinds():\n prop_kinds = bwam.properties_data()['property_kinds']\n assert \"angle per time\" in prop_kinds.keys()\n assert \"foobar\" not in prop_kinds.keys()\n assert prop_kinds['area'] is None\n assert prop_kinds['amplitude'] == \"Amplitude of the acoustic signal recorded. \" \\\n \"It is not a physical property, only a value.\"\n\n\n# ---- Test infer_property_kind ---\n\n@pytest.mark.parametrize(\"input_name, input_unit, kind, facet_type, facet\", [\n ('gamma ray API unit', 'gAPI', 'gamma ray API unit', None, None), # Just a placeholder for now\n ('', '', 'Unknown', None, None), # What should default return?\n])\ndef test_infer_property_kind(input_name, input_unit, kind, facet_type, facet):\n kind_, facet_type_, facet_ = rqp.infer_property_kind(input_name, input_unit)\n assert kind == kind_\n assert facet_type == facet_type_\n assert facet == facet_\n\n\n# ---- Test bespoke property kind reuse ---\n\ndef test_bespoke_property_kind():\n model = rq.Model(create_basics = True)\n em = {'something': 'important', 'and_another_thing': 42}\n pk1 = rqp.PropertyKind(model, title = 'my kind of property', extra_metadata = em)\n pk1.create_xml()\n assert len(model.uuids(obj_type = 'PropertyKind')) == 1\n pk2 = rqp.PropertyKind(model, title = 'my kind of property', extra_metadata = em)\n pk2.create_xml()\n assert len(model.uuids(obj_type = 'PropertyKind')) == 1\n pk3 = rqp.PropertyKind(model, title = 'your kind of property', extra_metadata = em)\n pk3.create_xml()\n assert len(model.uuids(obj_type = 'PropertyKind')) == 2\n pk4 = rqp.PropertyKind(model, title = 'my kind of property')\n pk4.create_xml()\n assert len(model.uuids(obj_type = 'PropertyKind')) == 3\n pk5 = rqp.PropertyKind(model, title = 'my kind of property', parent_property_kind = 'discrete', extra_metadata = em)\n pk5.create_xml()\n assert len(model.uuids(obj_type = 'PropertyKind')) == 4\n pk6 = rqp.PropertyKind(model, title = 'my kind of property', parent_property_kind = 'continuous')\n pk6.create_xml()\n assert len(model.uuids(obj_type = 'PropertyKind')) == 4\n assert pk6 == pk4\n\n\n# ---- Test string lookup ---\n\ndef test_string_lookup():\n model = rq.Model(create_basics = True)\n d = {1: 'peaty',\n 2: 'muddy',\n 3: 'sandy',\n 4: 'granite'}\n sl = rqp.StringLookup(model, int_to_str_dict = d, title = 'stargazing')\n sl.create_xml()\n assert sl.length() == 5 if sl.stored_as_list else 4\n assert sl.get_string(3) == 'sandy'\n assert sl.get_index_for_string('muddy') == 2\n d2 = {0: 'nothing',\n 27: 'something',\n 173: 'amazing',\n 1072: 'brilliant'}\n sl2 = rqp.StringLookup(model, int_to_str_dict = d2, title = 'head in the clouds')\n assert not sl2.stored_as_list\n assert sl2.length() == 4\n assert sl2.get_string(1072) == 'brilliant'\n assert sl2.get_string(555) is None\n assert sl2.get_index_for_string('amazing') == 173\n sl2.create_xml()\n assert set(model.titles(obj_type = 'StringTableLookup')) == set(['stargazing', 'head in the clouds'])\n assert sl != sl2\n\n\n\ndef test_property_extra_metadata(tmp_path):\n # set up test model with a grid\n epc = os.path.join(tmp_path, 'em_test.epc')\n model = rq.new_model(epc)\n grid = grr.RegularGrid(model, extent_kji = (2,3,4))\n grid.write_hdf5()\n grid.create_xml()\n model.store_epc()\n # add a grid property with some extra metadata\n a = np.arange(24).astype(float).reshape((2, 3, 4))\n em = {'important': 'something', 'also': 'nothing'}\n uuid = rqdm.add_one_grid_property_array(epc, a, 'length', title = 'nonsense', uom = 'm', extra_metadata = em)\n # re-open the model and check that extra metadata has been preserved\n model = rq.Model(epc)\n p = rqp.Property(model, uuid = uuid)\n for item in em.items():\n assert item in p.extra_metadata.items()\n","sub_path":"tests/test_property.py","file_name":"test_property.py","file_ext":"py","file_size_in_byte":7223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"454623240","text":"import json\nimport boto3\nimport decimal\nfrom boto3.dynamodb.conditions import Key, Attr\nfrom botocore.exceptions import ClientError\n\nclass DecimalEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, decimal.Decimal):\n if abs(o) % 1 >0:\n return float(o)\n else:\n return int(o)\n return super(DecimalEncoder, self).default(o)\n\ndef lambda_handler(event, context):\n message = \"\"\n dynamoDB = boto3.resource(\"dynamodb\")\n table = dynamoDB.Table(\"Connect4Players\")\n \n temp = json.loads(event[\"body\"])\n \n username = temp[\"Username\"]\n level = temp[\"PlayerLevel\"]\n draw = temp[\"MatchesDrawn\"]\n lost = temp[\"MatchesLost\"]\n won = temp[\"MatchesWon\"]\n skill = temp[\"SkillLv\"]\n total = temp[\"TotalMatches\"]\n \n response = table.update_item(\n Key={ \"Username\":username },\n UpdateExpression=\"set PlayerLevel=:l, MatchesDrawn=:d, MatchesLost=:t, MatchesWon=:w, SkillLv=:s, TotalMatches=:m\",\n ExpressionAttributeValues={\n \":l\":str(level),\n \":d\":str(draw),\n \":t\":str(lost),\n \":w\":str(won),\n \":s\":str(skill),\n \":m\":str(total)\n })\n \n return {\n 'statusCode': 200,\n 'body': json.dumps(response, indent=4, cls=DecimalEncoder)\n }\n","sub_path":"Lambdas/UpdatePlayer.py","file_name":"UpdatePlayer.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"419141777","text":"import sys\nimport threading\nimport logging\nimport chatServerSnd\nimport fnmatch\n\nclass Client:\n\t\"\"\"\n\tServer uses this class to record information for each client that has an account.\n\t\n\tWe save the socket through which we talk to the client. If the client logs out or we detect that it failed\n\tthen we use the reset_socket function to make its socket None. If it logs in again then we update the socket from\n\tNone to the real value using the function set_socket.\n\t\n\tAttributes:\n\t\tsocket: an integer denoting the socket through which we talk to the client or None if the client is not\n\t\t\tonline or we detected that it failed.\n\t\tmsg: a queue of messages (strings) that were received for the client while it was off-line or had failed.\n\t\"\"\"\n\tdef __init__(self):\n\t\t\"\"\"Initializes an entry about a new client. Socket is set to None and no messages are to be delivered.\"\"\"\n\t\tself.socket = None\n\t\tself.msg = []\n\n\tdef set_socket(self, socket):\n\t\t\"\"\"Changes the value of the socket from None, once the client connencts.\"\"\"\n\t\tself.socket = socket\n\t\tlogging.debug('socket set.')\n\n\tdef reset_socket(self):\n\t\t\"\"\"Sets the value of the socket to None whenever the client logs out or we detect that it failed.\"\"\"\n\t\tself.socket = None\n\t\tlogging.debug('socket reset.')\n\n\tdef add_msg(self, msg):\n\t\t\"\"\"Adds a new message to the queue of undelivered messages for the client.\"\"\"\n\t\tself.msg.append(msg)\n\t\tlogging.debug('message added.')\n\n\tdef display_all_msg(self):\n\t\t\"\"\"Deliver all undelivered messages to the client whenever it is requested or before deleting its account.\"\"\" \n\t\tmsg = ''\n\t\tfor i in self.msg:\n\t\t\tmsg = msg + i\n\t\treturn msg\n\n\tdef reset_msg_queue(self):\n\t\t\"\"\"Clear the message queue.\"\"\"\n\t\tself.msg = []\n\n\tdef get_socket(self):\n\t\t\"\"\"Return the socket assigned to the client.\"\"\"\n\t\treturn self.socket\n\ndef create_account(package, client_socket, data, lock, version):\n\t\"\"\" \n\tHandles a message from a client to create a new account.\n\n\tIf the account name already exists in the dictionary keeping the user records it returns an error,\n\totherwise it creates a new account entry in the dictionary with the name requested as a key and \n\ta new instance of Client as a value.\n\n\tArgs:\n\t\tpackage: contains the protocol version and the account name\n\t\tclient_socket: the socket through which the client connects\n\t\tdata: the dictionary data structure that keeps the records for all clients in the system\n\t\tlock: a lock to the dictionary keeping the client records to make sure that the data remains consistent\n\t\t\teven if many clients are accessing it simultaneously\n\t\tversion: the version of the protocol\n\t\n\tReturns:\n\t\tNothing\n\t\n\t\"\"\"\n\taccount_name = package.msg # the msg in the package contains the name of the new account\n\n\tlock.acquire()\n\n\ttry:\n\t\tif account_name not in data:\n\t\t\tclient_entry = Client()\n\t\t\tdata[account_name] = client_entry\n\t\t\tchatServerSnd.create_account_success(client_socket, account_name, version)\n\t\t\tlogging.info('server successfully created account.')\n\t\telse:\n\t\t\tchatServerSnd.create_account_failure(client_socket, account_name, version)\n\t\t\tlogging.info('server cannot create a new account because it exists.')\n\texcept:\n\t\tlogging.warning('exception occurred when server runs create_account.')\n\t\tchatServerSnd.create_account_failure(client_socket, account_name, version)\n\tfinally:\n\t\tlock.release()\n\t\tlogging.info('server performed create_account.')\n\ndef log_in(package, client_socket, data, lock, version):\n\t\"\"\"\n\tHandles a message from a client to log in into an account.\n\n\tIf the account name does not exist in the dictionary keeping the user records or the user of the account\n\tis already logged in it returns an error. Otherwise it updates the entry corresponding to that account \n\twith the socket through which the client is connected. In that way the server can talk to the client.\n\t\n\tArgs:\n\t\tpackage: contains the protocol version and the account name\n\t\tclient_socket: the socket through which the client connects\n\t\tdata: the dictionary data structure that keeps the records for all clients in the system\n\t\tlock: a lock to the dictionary keeping the client records to make sure that the data remains consistent\n\t\t\teven if many clients are accessing it simultaneously\n\t\tversion: the version of the protocol\n\t\n\tReturns:\n\t\tNothing\n\t\"\"\"\n\taccount_name = package.msg # the msg in the package contains the name of the account to log in\n\n\tlock.acquire()\n\n\terror = False\n\n\ttry:\n\t\tif account_name in data:\n\t\t\tfor acc in data:\n\t\t\t\tclient_entry = data[acc]\n\t\t\t\tif client_socket == client_entry.get_socket():\n\t\t\t\t\tif acc == account_name:\n\t\t\t\t\t\tchatServerSnd.log_in_already(client_socket, account_name, version)\n\t\t\t\t\t\tlogging.info('account has logged in already.')\n\t\t\t\t\t\terror = True\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tclient_entry = data[acc]\n\t\t\t\t\t\tclient_entry.reset_socket()\n\n\t\t\t\t\t\tnew_client = data[account_name]\n\t\t\t\t\t\tnew_client.set_socket(client_socket)\n\t\t\t\t\t\tchatServerSnd.log_in_other(client_socket, acc, version)\n\t\t\t\t\t\tlogging.info('%s has logged in here. Forced logged out', acc)\n\t\t\t\t\t\terror = True\n\t\t\t\t\t\tbreak\n\t\t\tif not error:\n\t\t\t\tclient_entry = data[account_name]\n\t\t\t\tclient_entry.set_socket(client_socket)\n\t\t\t\tchatServerSnd.log_in_success(client_socket, account_name, version)\n\t\t\t\tlogging.info('account is successfully logged in.')\n\t\telse:\n\t\t\tchatServerSnd.log_in_failure(client_socket, account_name, version)\n\t\t\tlogging.info('the account cannot be logged in as it does not exist. Create an account first.')\n\t\t\t\n\texcept:\n\t\tlogging.warning('exception occurred when server runs log_in.')\n\t\tchatServerSnd.log_in_failure(client_socket, account_name, version)\n\tfinally:\n\t\tlock.release()\n\t\tlogging.info('server performed log_in.')\n\ndef send_message(package, client_socket, data, lock, version):\n\t\"\"\"\n\tSends a message from one client to another client, specified in the package.\n\n\tIf the receiver does not exist in the dictionary keeping the user records it returns an error. If the socket of the\n\treceiver is set to None (the receiver is off-line) we add the message in the queue of unread messages in the\n\trecord of the receiver. If the socket of the receiver is not None then the receiver is either online or it \n\tfailed but we have not detected the failure yet. We try to deliver the message instantly. If we get a response from\n\tthe receiver that the message was delivered then no further action is taken. If we do not hear back however, we\n\tconsider the receiver to have failed, we reset its socket to None and add the message in the queue of unread messages\n\tin the record of the receiver.\n\t\t\n\tArgs:\n\t\tpackage: contains the protocol version and the account name of the receiver and the message to be sent\n\t\tclient_socket: the socket through which the client connects\n\t\tdata: the dictionary data structure that keeps the records for all clients in the system\n\t\tlock: a lock to the dictionary keeping the client records to make sure that the data remains consistent\n\t\t\teven if many clients are accessing it simultaneously\n\t\tversion: the version of the protocol\n\t\n\tReturns:\n\t\tNothing\n\t\"\"\"\n\treceiver = package.receiver\t # the receiver in the package contains the recipient of the message\n\t\n\tlock.acquire()\n\n\terror = True\n\n\ttry:\n\t\tif receiver not in data:\n\t\t\tchatServerSnd.send_message_failure_receiver(client_socket, receiver, version)\n\t\t\tlogging.info('server cannot send the message to a non-existent user.')\n\t\telse:\n\t\t\tfor acc in data:\n\t\t\t\tclient_entry = data[acc]\n\t\t\t\tif client_entry.get_socket() == client_socket:\n\t\t\t\t\tsender = acc\n\t\t\t\t\treceiver_entry = data[receiver]\n\t\t\t\t\tmessage = sender + \":\" + package.msg + \"\\n\"\n\n\t\t\t\t\treceiver_socket = receiver_entry.get_socket()\n\t\t\t\t\tif not (receiver_socket is None):\n\t\t\t\t\t\tsuccess = chatServerSnd.direct_send(receiver_socket, message, version)\n\t\t\t\t\telse:\n\t\t\t\t\t\treceiver_entry.add_msg(message)\n\t\t\t\t\t\tsuccess = True\n\t\t\t\t\tif not success:\n\t\t\t\t\t\treceiver_entry.add_msg(message)\n\t\t\t\t\t\treceiver_entry.reset_socket()\n\n\t\t\t\t\tchatServerSnd.send_message_success(client_socket, receiver, version)\n\t\t\t\t\tlogging.info('server successfully sent the message to %s.', receiver)\n\t\t\t\t\terror = False\n\t\t\tif error:\n\t\t\t\tchatServerSnd.send_message_failure_sender(client_socket, receiver, version)\n\t\t\t\tlogging.info('sender is not a registered user on the server.')\n\texcept:\n\t\tlogging.warning('exception occurred when server runs send_message.')\n\t\tchatServerSnd.send_message_failure_receiver(client_socket, receiver, version)\n\tfinally:\n\t\tlock.release()\n\t\tlogging.info('server performed send_message.')\n\ndef check_message(package, client_socket, data, lock, version):\n\t\"\"\"\n\tDelivers all undelivered messages to a user.\n\t\n\tThe server picks all the undelivered messages from the dictionary record for that client and sends them\n\tto it. Subsequently, it flushes the queue since there are no unread messages for that client.\n\t\n\tIf the user is not logged in to an account then no messages are delivered and a failure message\n\tis printed in the log.\n\t\t\n\tArgs:\n\t\tpackage: not useful in this function\n\t\tclient_socket: the socket through which the client connects\n\t\tdata: the dictionary data structure that keeps the records for all clients in the system\n\t\tlock: a lock to the dictionary keeping the client records to make sure that the data remains consistent\n\t\t\teven if many clients are accessing it simultaneously\n\t\tversion: the version of the protocol\n\t\n\tReturns:\n\t\tNothing\n\t\"\"\"\n\terror = True\n\n\tlock.acquire()\n\n\ttry:\n\t\tfor acc in data:\n\t\t\tclient_entry = data[acc]\n\t\t\tif client_entry.get_socket() == client_socket:\n\t\t\t\tsender = acc\n\t\t\t\tmessage = client_entry.display_all_msg()\n\t\t\t\tclient_entry.reset_msg_queue()\n\t\t\t\n\t\t\t\tchatServerSnd.check_message_success(client_socket, message, version)\n\t\t\t\tlogging.info('server sent all unread messages to %s.', sender)\n\t\t\t\terror = False\n\t\tif error:\n\t\t\tsender = 'Unknown'\n\t\t\tchatServerSnd.check_message_failure(client_socket, sender, version)\n\t\t\tlogging.info('sender is not logged in on the server to check message.')\n\texcept:\n\t\tlogging.warning('exception occurred when server runs check_message.')\n\t\tchatServerSnd.check_message_failure(client_socket, sender, version)\n\tfinally:\n\t\tlock.release()\n\t\tlogging.info('server performed check_message.')\n\ndef delete_account(package, client_socket, data, lock, version):\n\t\"\"\"\n\tDeletes the account of the user that is logged in.\n\t\n\tAll the unread messages for the account to be deleted are sent to the client and subsequently the\n\trecord in the dictionary regarding the account to be deleted is removed.\n\t\n\tIf the client is not logged in to an account then no account is deleted and a \n\tfailure message is printed in the log.\n\t\t\n\tArgs:\n\t\tpackage: not useful in this function\n\t\tclient_socket: the socket through which the client connects\n\t\tdata: the dictionary data structure that keeps the records for all clients in the system\n\t\tlock: a lock to the dictionary keeping the client records to make sure that the data remains consistent\n\t\t\teven if many clients are accessing it simultaneously\n\t\tversion: the version of the protocol\n\t\n\tReturns:\n\t\tNothing\n\t\"\"\"\n\terror = True\n\n\tlock.acquire()\n\n\ttry:\n\t\tfor acc in data:\n\t\t\tclient_entry = data[acc]\n\t\t\tif client_entry.get_socket() == client_socket:\n\t\t\t\tsender = acc\n\t\t\t\tmessage = \"The account \" + sender + \" is permanently deleted. You have the following unread messages:\\n\"\n\t\t\t\tmessage = message + client_entry.display_all_msg()\n\t\t\t\tdel data[sender]\n\t\t\t\n\t\t\t\tchatServerSnd.delete_account_success(client_socket, message, version)\n\t\t\t\tlogging.info('server successfully deleted the account %s.', sender)\n\t\t\t\terror = False\n\t\tif error:\n\t\t\tsender = 'Unknown'\n\t\t\tchatServerSnd.delete_account_failure(client_socket, sender, version)\n\t\t\tlogging.info('%s account to delete. Need to log in first.', sender)\n\texcept:\n\t\tlogging.warning('exception occurred when server runs delete_account.')\n\t\tchatServerSnd.delete_account_failure(client_socket, sender, version)\n\tfinally:\n\t\tlock.release()\n\t\tlogging.info('server performed delete_account.')\n\ndef list_account(package, client_socket, data, lock, version):\n\t\"\"\"\n\tList the names of all accounts that match the regular expression specified from the client,\n\tor the names of all accounts if none is given.\n\t\n\tArgs:\n\t\tpackage: potentially contains a regular expression to be matched\n\t\tclient_socket: the socket through which the client connects\n\t\tdata: the dictionary data structure that keeps the records for all clients in the system\n\t\tlock: a lock to the dictionary keeping the client records to make sure that the data remains consistent\n\t\t\teven if many clients are accessing it simultaneously\n\t\tversion: the version of the protocol\n\t\n\tReturns:\n\t\tNothing\n\t\"\"\"\n\tcriteria = package.msg # user provides the matching criteria\n\tresults = \"\"\n\n\tlock.acquire()\n\n\ttry:\n\t\tfor account_name in data:\n\t\t\treplaced_criteria = criteria.replace(\"_\", \"?\")\n\t\t\tif fnmatch.fnmatch(account_name, replaced_criteria):\n\t\t\t\tresults = results + account_name + '\\n'\n\t\tchatServerSnd.list_account_success(client_socket, results, version)\n\t\tlogging.info('server listed account that matched.')\n\texcept:\n\t\tlogging.warning('exception occurred when server runs list_account.')\n\t\tchatServerSnd.list_account_failure(client_socket, results, version)\n\tfinally:\n\t\tlock.release()\n\t\tlogging.info('server performed list_account.')\n\ndef quit(package, client_socket, data, lock, version):\n\t\"\"\"\n\tAllows a user to logout. Once a logout request is received we set the socket of the user to None,\n\tindicating that it is not active anymore hence it cannot receive direct messages. All messages for that\n\tuser will be queued until it logs back in the system.\n\t\n\tIf this function is called by a client that has not logged in then no socket is set to None and an\n\terror message is printed in the log.\n\n\tArgs:\n\t\tpackage: not useful in this function\n\t\tclient_socket: the socket through which the client connects\n\t\tdata: the dictionary data structure that keeps the records for all clients in the system\n\t\tlock: a lock to the dictionary keeping the client records to make sure that the data remains consistent\n\t\t\teven if many clients are accessing it simultaneously\n\t\tversion: the version of the protocol\n\t\n\tReturns:\n\t\tNothing\n\t\"\"\"\n\terror = True\n\n\tlock.acquire()\n\n\ttry:\n\t\tfor acc in data:\n\t\t\tclient_entry = data[acc]\n\t\t\tif client_entry.get_socket() == client_socket:\n\t\t\t\tsender = acc\n\t\t\t\tclient_entry.reset_socket()\n\t\t\t\tchatServerSnd.quit_success(client_socket, sender, version)\n\t\t\t\tlogging.info('server received quit signal from the client: %s.', sender)\n\t\t\t\terror = False\n\t\tif error:\n\t\t\tsender = 'Unknown'\n\t\t\tchatServerSnd.quit_failure(client_socket, sender, version)\n\t\t\tlogging.info('unknown account to quit.')\n\texcept:\n\t\tlogging.warning('exception occurred when server runs quit.')\n\t\tchatServerSnd.quit_failure(client_socket, sender, version)\n\tfinally:\n\t\tlock.release()\n\t\tlogging.info('server performed quit.')\n\n\n\n\n\n\n\n\t\n","sub_path":"v1/chatServerRcv.py","file_name":"chatServerRcv.py","file_ext":"py","file_size_in_byte":14737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"86207733","text":"''' Copyright [2018] [Siddhant Mahapatra]\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n https://github.com/Robosid/Drone-Intelligence/blob/master/License.pdf\n https://github.com/Robosid/Drone-Intelligence/blob/master/License.rtf\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# Created by Siddhant Mahapatra (aka Robosid). for AutoMav of Project Heartbeat. \n\n# Script to import and export files in the Waypoint file format (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format). The commands are imported\n# into a list, and can be modified before saving and/or uploading..\n\n# Last modified by : Robosid\n# Last modifed on : 03 / 22 / 2018\n\nfrom __future__ import print_function\n\n\nfrom dronekit import connect, Command\nimport time\n\n'''\n#Set up option parsing to get connection string\nimport argparse \nparser = argparse.ArgumentParser(description='Demonstrates mission import/export from a file.')\nparser.add_argument('--connect', \n help=\"Vehicle connection target string. If not specified, SITL automatically started and used.\")\nargs = parser.parse_args()\n\nconnection_string = args.connect\nsitl = None\n\n\n#Start SITL if no connection string specified\nif not connection_string:\n import dronekit_sitl\n sitl = dronekit_sitl.start_default()\n connection_string = sitl.connection_string()\n'''\n\n#-- Connect to the vehicle\n#print('Connecting...')\n#vehicle = connect('udp:127.0.0.1:14551')\nprint(\">>>> Connecting with the UAV <<<\")\nimport argparse\nparser = argparse.ArgumentParser(description='commands')\nparser.add_argument('--connect', default='/dev/ttyS0')\nargs = parser.parse_args()\n\nconnection_string = args.connect\n\n\nprint(\"Connection to the vehicle on %s\"%connection_string)\nvehicle = connect(args.connect, baud=921600, wait_ready=True) #- wait_ready flag hold the program untill all the parameters are been read (=, not .)\n\n# Check that vehicle is armable. \n# This ensures home_location is set (needed when saving WP file)\n\nwhile not vehicle.is_armable:\n print(\" Waiting for vehicle to initialise...\")\n time.sleep(1)\n\n\ndef readmission(aFileName):\n \"\"\"\n Load a mission from a file into a list. The mission definition is in the Waypoint file\n format (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format).\n\n This function is used by upload_mission().\n \"\"\"\n print(\"\\nReading mission from file: %s\" % aFileName)\n cmds = vehicle.commands\n missionlist=[]\n with open(aFileName) as f:\n for i, line in enumerate(f):\n if i==0:\n if not line.startswith('QGC WPL 110'):\n raise Exception('File is not supported WP version')\n else:\n linearray=line.split('\\t')\n ln_index=int(linearray[0])\n ln_currentwp=int(linearray[1])\n ln_frame=int(linearray[2])\n ln_command=int(linearray[3])\n ln_param1=float(linearray[4])\n ln_param2=float(linearray[5])\n ln_param3=float(linearray[6])\n ln_param4=float(linearray[7])\n ln_param5=float(linearray[8])\n ln_param6=float(linearray[9])\n ln_param7=float(linearray[10])\n ln_autocontinue=int(linearray[11].strip())\n cmd = Command( 0, 0, 0, ln_frame, ln_command, ln_currentwp, ln_autocontinue, ln_param1, ln_param2, ln_param3, ln_param4, ln_param5, ln_param6, ln_param7)\n missionlist.append(cmd)\n return missionlist\n\n\ndef upload_mission(aFileName):\n \"\"\"\n Upload a mission from a file. \n \"\"\"\n #Read mission from file\n missionlist = readmission(aFileName)\n \n print(\"\\nUpload mission from a file: %s\" % import_mission_filename)\n #Clear existing mission from vehicle\n print(' Clear mission')\n cmds = vehicle.commands\n cmds.clear()\n #Add new mission to vehicle\n for command in missionlist:\n cmds.add(command)\n print(' Upload mission')\n vehicle.commands.upload()\n\n\ndef download_mission():\n \"\"\"\n Downloads the current mission and returns it in a list.\n It is used in save_mission() to get the file information to save.\n \"\"\"\n print(\" Download mission from vehicle\")\n missionlist=[]\n cmds = vehicle.commands\n cmds.download()\n cmds.wait_ready()\n for cmd in cmds:\n missionlist.append(cmd)\n return missionlist\n\ndef save_mission(aFileName):\n \"\"\"\n Save a mission in the Waypoint file format \n (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format).\n \"\"\"\n print(\"\\nSave mission from Vehicle to file: %s\" % export_mission_filename) \n #Download mission from vehicle\n missionlist = download_mission()\n #Add file-format information\n output='QGC WPL 110\\n'\n #Add home location as 0th waypoint\n home = vehicle.home_location\n output+=\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\" % (0,1,0,16,0,0,0,0,home.lat,home.lon,home.alt,1)\n #Add commands\n for cmd in missionlist:\n commandline=\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n\" % (cmd.seq,cmd.current,cmd.frame,cmd.command,cmd.param1,cmd.param2,cmd.param3,cmd.param4,cmd.x,cmd.y,cmd.z,cmd.autocontinue)\n output+=commandline\n with open(aFileName, 'w') as file_:\n print(\" Write mission to file\")\n file_.write(output)\n \n \ndef printfile(aFileName):\n \"\"\"\n Print a mission file to demonstrate \"round trip\"\n \"\"\"\n print(\"\\nMission file: %s\" % aFileName)\n with open(aFileName) as f:\n for line in f:\n print(' %s' % line.strip()) \n\n\nimport_mission_filename = 'mpmission.txt'\nexport_mission_filename = 'exportedmission.txt'\n\n\n#Upload mission from file\nupload_mission(import_mission_filename)\n\n#Download mission we just uploaded and save to a file\nsave_mission(export_mission_filename)\n\n#Close vehicle object before exiting script\nprint(\"Close vehicle object\")\nvehicle.close()\n\n# Shut down simulator if it was started.\nif sitl is not None:\n sitl.stop()\n\n\nprint(\"\\nShow original and uploaded/downloaded files:\")\n#Print original file (for test purposes only)\nprintfile(import_mission_filename)\n#Print exported file (for test purposes only)\nprintfile(export_mission_filename)\n","sub_path":"AutoMav_Heartbeat/mission_handling/mission_import_export.py","file_name":"mission_import_export.py","file_ext":"py","file_size_in_byte":6672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"139043717","text":"#coding:utf-8\r\n#import random\r\n\r\nfrom openpyxl import Workbook, load_workbook\r\nfrom contextlib import closing\r\n\r\n\r\nimport sys\r\nreload(sys)\r\n\r\n\r\nclass recordLoanData(object):\r\n ROBOT_LIBRARY_SCOPE = 'GLOBAL'\r\n ROBOT_LIBRARY_VERSION = 0.1\r\n\r\n\r\n def __init__(self):\r\n pass\r\n\r\n ## 创建Excel\r\n def createExcel(self, file_name):\r\n with closing(Workbook()) as wb:\r\n wb.save(file_name)\r\n \r\n \r\n ## 获取Excel行数\r\n def getExcelRowCount(self, file_name, sheet_name):\r\n with closing(load_workbook(filename=file_name)) as wb:\r\n rows = wb.get_sheet_by_name(name = str(sheet_name)).max_row\r\n return rows\r\n ## 获取Excel列数\r\n def getExcelColumnCount(self, file_name, sheet_name):\r\n with closing(load_workbook(filename=file_name)) as wb:\r\n columns = wb.get_sheet_by_name(name = str(sheet_name)).max_column\r\n return columns\r\n \r\n ## 读取从某一行某一列开始的n个值\r\n def listReadExcel(self, file_name, sheet_name, cell_row,cell_col,n ):\r\n with closing(load_workbook(filename=file_name, data_only=True)) as wb:\r\n ws = wb.get_sheet_by_name(str(sheet_name))\r\n cellValueList = []\r\n for i in range(int(n)):\r\n cellValue = ws.cell(row=int(cell_row),column=int(cell_col)+i).value\r\n cellValueList.append(cellValue)\r\n return cellValueList\r\n \r\n ## 读取从某一列某一行开始的n个值\r\n def listExcel(self, file_name, sheet_name, cell_row, cell_col, n):\r\n with closing(load_workbook(filename=file_name, data_only=True)) as wb:\r\n ws = wb.get_sheet_by_name(str(sheet_name))\r\n cellValueList = []\r\n for i in range(int(n)):\r\n cellValue = ws.cell(row=int(cell_row)+i,column=int(cell_col)).value\r\n cellValueList.append(cellValue)\r\n return cellValueList","sub_path":"src/practice/操作excel.py","file_name":"操作excel.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"382243536","text":"from custom_components.dyson_local.sensor import SENSORS\nfrom typing import List, Type\nfrom homeassistant.util.unit_system import IMPERIAL_SYSTEM\nfrom libdyson.dyson_device import DysonDevice, DysonFanDevice\nfrom unittest.mock import MagicMock, patch\nfrom libdyson.const import DEVICE_TYPE_360_EYE, DEVICE_TYPE_PURE_COOL_LINK, ENVIRONMENTAL_OFF, MessageType\nimport pytest\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.const import ATTR_DEVICE_CLASS, ATTR_ENTITY_ID, ATTR_ICON, ATTR_UNIT_OF_MEASUREMENT, CONF_HOST, CONF_NAME, STATE_OFF, STATE_ON, TEMP_CELSIUS, TEMP_FAHRENHEIT\nfrom homeassistant.helpers import entity_registry\nfrom tests.common import MockConfigEntry\nfrom custom_components.dyson_local import DOMAIN\nfrom libdyson import DEVICE_TYPE_PURE_COOL, DysonPureCool, DysonPureCoolLink, Dyson360Eye\nfrom . import NAME, SERIAL, CREDENTIAL, HOST, MODULE, get_base_device, name_to_entity, update_device\n\nDEVICE_TYPE = DEVICE_TYPE_PURE_COOL\n\n\n@pytest.fixture\ndef device(request: pytest.FixtureRequest) -> DysonDevice:\n with patch(f\"{MODULE}._async_get_platforms\", return_value=[\"sensor\"]):\n yield request.param()\n\n\ndef _get_fan(spec: Type[DysonFanDevice], device_type: str) -> DysonFanDevice:\n device = get_base_device(spec, device_type)\n device.humidity = 50\n device.temperature = 280\n return device\n\n\ndef _get_pure_cool_link() -> DysonPureCoolLink:\n device = _get_fan(DysonPureCoolLink, DEVICE_TYPE_PURE_COOL_LINK)\n device.filter_life = 200\n return device\n\n\ndef _get_pure_cool_combined() -> DysonPureCool:\n device = _get_fan(DysonPureCool, DEVICE_TYPE_PURE_COOL)\n device.carbon_filter_life = None\n device.hepa_filter_life = 50\n return device\n\n\ndef _get_pure_cool_seperated() -> DysonPureCool:\n device = _get_fan(DysonPureCool, DEVICE_TYPE_PURE_COOL)\n device.carbon_filter_life = 30\n device.hepa_filter_life = 50\n return device\n\n\ndef _get_360_eye() -> Dyson360Eye:\n device = get_base_device(Dyson360Eye, DEVICE_TYPE_360_EYE)\n device.battery_level = 80\n return device\n\n\n@pytest.mark.parametrize(\n \"device,sensors\",\n [\n (_get_pure_cool_link, [\"humidity\", \"temperature\", \"filter_life\"]),\n (_get_pure_cool_combined, [\"humidity\", \"temperature\", \"combined_filter_life\"]),\n (_get_pure_cool_seperated, [\"humidity\", \"temperature\", \"carbon_filter_life\", \"hepa_filter_life\"]),\n (_get_360_eye, [\"battery_level\"]),\n ],\n indirect=[\"device\"]\n)\nasync def test_sensors(\n hass: HomeAssistant,\n device: DysonFanDevice,\n sensors: List[str],\n):\n er = await entity_registry.async_get_registry(hass)\n assert len(hass.states.async_all()) == len(sensors)\n for sensor in sensors:\n name, attributes = SENSORS[sensor]\n entity_id = f\"sensor.{NAME}_{name_to_entity(name)}\"\n state = hass.states.get(entity_id)\n assert state.name == f\"{NAME} {name}\"\n for attr, value in attributes.items():\n assert state.attributes[attr] == value\n assert er.async_get(entity_id).unique_id == f\"{SERIAL}-{sensor}\"\n\n\n@pytest.mark.parametrize(\n \"device\", [_get_pure_cool_link, _get_pure_cool_combined], indirect=True\n)\nasync def test_fan(hass: HomeAssistant, device: DysonFanDevice):\n assert hass.states.get(f\"sensor.{NAME}_humidity\").state == \"50\"\n state = hass.states.get(f\"sensor.{NAME}_temperature\")\n assert state.state == \"6.9\"\n assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == TEMP_CELSIUS\n\n device.humidity = 30\n device.temperature = 300\n hass.config.units = IMPERIAL_SYSTEM\n await update_device(hass, device, MessageType.ENVIRONMENTAL)\n assert hass.states.get(f\"sensor.{NAME}_humidity\").state == \"30\"\n state = hass.states.get(f\"sensor.{NAME}_temperature\")\n assert state.state == \"80.3\"\n assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == TEMP_FAHRENHEIT\n\n device.temperature = ENVIRONMENTAL_OFF\n await update_device(hass, device, MessageType.ENVIRONMENTAL)\n assert hass.states.get(f\"sensor.{NAME}_temperature\").state == STATE_OFF\n\n\n@pytest.mark.parametrize(\n \"device\", [_get_pure_cool_link], indirect=True\n)\nasync def test_pure_cool_link(hass: HomeAssistant, device: DysonFanDevice):\n assert hass.states.get(f\"sensor.{NAME}_filter_life\").state == \"200\"\n device.filter_life = 100\n await update_device(hass, device, MessageType.STATE)\n assert hass.states.get(f\"sensor.{NAME}_filter_life\").state == \"100\"\n\n\n@pytest.mark.parametrize(\n \"device\", [_get_pure_cool_combined], indirect=True\n)\nasync def test_pure_cool_combined(hass: HomeAssistant, device: DysonFanDevice):\n assert hass.states.get(f\"sensor.{NAME}_filter_life\").state == \"50\"\n device.hepa_filter_life = 30\n await update_device(hass, device, MessageType.STATE)\n assert hass.states.get(f\"sensor.{NAME}_filter_life\").state == \"30\"\n\n\n@pytest.mark.parametrize(\n \"device\", [_get_pure_cool_seperated], indirect=True\n)\nasync def test_pure_cool_combined(hass: HomeAssistant, device: DysonFanDevice):\n assert hass.states.get(f\"sensor.{NAME}_carbon_filter_life\").state == \"30\"\n assert hass.states.get(f\"sensor.{NAME}_hepa_filter_life\").state == \"50\"\n device.carbon_filter_life = 20\n device.hepa_filter_life = 30\n await update_device(hass, device, MessageType.STATE)\n assert hass.states.get(f\"sensor.{NAME}_carbon_filter_life\").state == \"20\"\n assert hass.states.get(f\"sensor.{NAME}_hepa_filter_life\").state == \"30\"\n\n\n@pytest.mark.parametrize(\n \"device\", [_get_360_eye], indirect=True\n)\nasync def test_360_eye(hass: HomeAssistant, device: DysonFanDevice):\n assert hass.states.get(f\"sensor.{NAME}_battery_level\").state == \"80\"\n device.battery_level = 40\n await update_device(hass, device, MessageType.STATE)\n assert hass.states.get(f\"sensor.{NAME}_battery_level\").state == \"40\"\n","sub_path":"tests/dyson_local/test_sensor.py","file_name":"test_sensor.py","file_ext":"py","file_size_in_byte":5796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"104721577","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.utils import timezone\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.contrib.auth import logout, login, authenticate\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\n\nfrom rest_framework import generics\n\nfrom .models import Quiz, QuizSession\nfrom .forms import LoginForm\n\n\ndef quiz_list(request):\n if request.user.is_authenticated():\n quizzes = Quiz.published.exclude(expiration__lte=timezone.now())\n\n paginator = Paginator(quizzes, 20) # 20 quizzes per page\n page = request.GET.get('page')\n\n try:\n quizzes = paginator.page(page)\n except PageNotAnInteger:\n # if page is not an integer deliver the first page\n quizzes = paginator.page(1)\n except EmptyPage:\n # if page is out of range deliver last page of results\n quizzes = paginator.page(paginator.num_pages)\n\n return render(request, 'quizzer/quiz_list.html', {'page': page, 'quizzes': quizzes})\n\n return redirect('quizzer:home')\n\n\ndef home(request):\n return render(request, 'index.html')\n\n\ndef login_view(request):\n message = ''\n if request.method == 'POST':\n form = LoginForm(request.POST)\n if form.is_valid():\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username, password=password)\n if user is not None:\n login(request, user)\n return HttpResponseRedirect(reverse('quizzer:home'))\n message = 'Invalid username/password!'\n else:\n form = LoginForm()\n return render(request, 'quizzer/login.html', {'form': form, 'message': message})\n\n\ndef quiz_view(request, quiz_id):\n quiz = get_object_or_404(Quiz, id=quiz_id)\n if request.method == 'POST':\n session = QuizSession(quiz=quiz, user=request.user, date_taken=timezone.now())\n correct = 0\n wrong = 0\n answers = {}\n for question in quiz.question_set.all():\n answer = question.choice_set.get(id=request.POST[str(question.id)])\n answers[question.id] = answer.id\n if answer in question.choice_set.filter(is_correct=True):\n correct += 1\n else:\n wrong += 1\n session.answers = answers\n session.score = correct\n session.save()\n return HttpResponseRedirect(reverse('quizzer:session_results', kwargs={'quiz_id': quiz.id,\n 'session_id': session.id}))\n return render(request, 'quizzer/quizform.html', {'quiz': quiz, 'start': timezone.now()})\n\n\ndef session_results(request, quiz_id, session_id):\n quiz = get_object_or_404(Quiz, id=quiz_id)\n session = get_object_or_404(QuizSession, quiz=quiz, id=session_id)\n\n results = dict()\n for question in quiz.question_set.all():\n results[question.id] = question.text\n\n return render(request, 'quizzer/quiz_results.html', {'results': results, 'session': session})\n\n\ndef logout_view(request):\n logout(request)\n return HttpResponseRedirect(reverse('quizzer:home'))\n\n\ndef register(request):\n message = ''\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('quizzer:login'))\n # else:\n # message = 'Passwords do not match'\n else:\n form = UserCreationForm()\n return render(request, 'quizzer/registration.html', {'message': message, 'form': form})\n","sub_path":"quizzer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"523275805","text":"# region Header\n# ---\n# TODO: Censorship warning system, download image to check for adult content, read text, and keep track of who has recieved warnings and why\n# TODO: Connect to a student database to auto-assign roles and nick-names? Same system that does schedule changes with\n# student ID, first letter of last name, email, etc. (Doubt we would get access... unless..?)\n# TODO: Try to make this ass professional as possible :) - IN PROGRESS\n# ---\n# endregion\n\n\n# region Imports\nimport re\nimport ast\nimport sys\nimport json\nimport furl\nimport discord\nimport requests\nimport psycopg2\nimport sqlalchemy\nimport sqlalchemy_utils\nimport pytesseract\nimport datetime as dt\nfrom PIL import Image\nfrom io import BytesIO\nfrom bs4 import BeautifulSoup\nfrom discord.ext import commands\nfrom sqlalchemy_utils import CompositeType\nfrom sqlalchemy.dialects import postgresql\nfrom sqlalchemy import *\nfrom sightengine.client import SightengineClient\nfrom profanity_check import predict, predict_prob\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler\n# endregion\n\n\n# region Miscellaneous Functions/Other\n\nemojiA = 'https://i.imgur.com/dmTKeTi.png'\nemojiB = 'https://i.imgur.com/oLJnbDL.png'\nemojiAB = 'https://i.imgur.com/dVOtgZq.png'\nemojiAnnouncements = 'https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/twitter/228/public-address-loudspeaker_1f4e2.png'\nemojiExclamation = 'https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/twitter/228/double-exclamation-mark_203c.png'\nemojiWave = 'https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/twitter/228/waving-hand-sign_1f44b.png'\nannouncements = []\ndate = ''\ndayType = ''\n\n# URL Validation\n\n\nasync def URL(str):\n url = re.findall(\n r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', str)\n return url\n\n\nclass Warning():\n def __init__(self, c=None, o=None):\n self.cause, self.offences = c, o\n\n\nasync def predictText(text):\n prob = predict_prob(text)\n return prob\n\n\nasync def predictImage(url):\n txt = pytesseract.image_to_string(Image.open(\n BytesIO(requests.get(url).content))) # ughhhhh\n img_prob = predict_prob([txt])\n\n return img_prob\n\n\n# TODO: Train these variables? Make them modifyable in json?\nasync def Sight(message, url):\n output = sight.check(\n 'nudity', 'wad', 'offensive').set_url(url)\n if output['status'] == 'success':\n offenses = []\n\n # check nudity\n if output['nudity']['raw'] > 0.35:\n offenses.append('RAW NUDITY')\n if output['nudity']['partial'] > 0.35:\n offenses.append('PARTIAL NUDITY')\n\n # check weapons, alcohol, & drugs\n if output['weapon'] > 0.4:\n offenses.append('WEAPON')\n if output['alcohol'] > 0.5:\n offenses.append('ALCOHOL')\n if output['drugs'] > 0.5:\n offenses.append('DRUGS')\n\n # check offensive\n if output['offensive']['prob'] > 0.5:\n offenses.append('OFFENSIVE')\n\n with open('test.json', 'w') as outfile:\n json.dump(output, outfile, indent=4)\n outfile.close()\n\n return offenses\n else: # error, send to be manually reviewed\n addReport(message, message.id)\n\n\nasync def Warn(cause, offences, author):\n # add to user's warnings, if > 3 then ban\n giveWarning('discord_id', author, cause, offences)\n warnings = warningCount('discord_id', author)\n\n embed = discord.Embed(title='WARNING', type='rich', color=0xf04923)\n embed.set_author(name='Sprague Bot', url='https://github.com/Th4tGuy69/Sprague-Bot',\n icon_url=emojiExclamation)\n\n text = 'YOU POSTED AN IMAGE CONTAINING: `{}`'.format(', '.join(offences))\n\n if warnings == 1:\n embed.add_field(\n name=text, value=':x::heavy_multiplication_x::heavy_multiplication_x:')\n elif warnings == 2:\n embed.add_field(\n name=text, value=':x::x::heavy_multiplication_x:')\n elif warnings >= 3:\n banned = True # TODO: Ban them fools\n embed.add_field(name=text, value=':x::x::x:')\n\n if URL(cause) != None:\n embed.set_image(url=URL(cause))\n embed.set_footer(text='Remember to make it a great day!')\n\n # TODO: Send to an admin chat to confirm warnings\n await author.send(embed=embed)\n\n\n# Web crawler grabs announcements, modifies, then posts to id=619772443116175370\nasync def postAnnouncements():\n announcements.clear()\n\n today = dt.date.today()\n date = str(today).split('-')\n\n if dt.date.today().weekday() is 1 or 3:\n dayType = 'an **A** day'\n elif dt.date.today().weekday() is 2 or 4:\n dayType = 'a **B** day'\n elif dt.date.today().weekday() is 0:\n dayType = 'an **A/B** day'\n\n # Web crawler\n page = requests.get('http://spragueannouncements.blogspot.com/')\n\n soup = BeautifulSoup(page.content, 'lxml')\n whole = soup.find(class_='post-body entry-content')\n class_ = whole.find_all('div')\n class_.pop(0)\n for div in class_:\n if len(div.text) > 3:\n text = div.text\n if '/' in text:\n text = text[:-4]\n text = re.sub(r'\\s+', ' ', text)\n\n announcements.append(text)\n\n # Embed setup\n embed = discord.Embed(title='Announcements for **{}/{}/{}**, {}.'.format(date[1].replace(\n '0', ''), date[2], date[0][2:], dayType), type='rich', url='http://spragueannouncements.blogspot.com/', color=0xf04923)\n embed.set_author(name='Sprague Bot', url='https://github.com/Th4tGuy69/Sprague-Bot',\n icon_url=emojiAnnouncements)\n time = dt.date(day=today.day, month=today.month,\n year=today.year).strftime('%A %B %d, %Y')\n embed.set_footer(text='Keep on a\\'rocking Sprague! | ' + time)\n if dt.date.today().weekday() is 1 or 3:\n embed.set_thumbnail(url=emojiA)\n elif dt.date.today().weekday() is 2 or 4:\n embed.set_thumbnail(url=emojiB)\n elif dt.date.today().weekday() is 0:\n embed.set_thumbnail(url=emojiAB)\n for announcement in announcements:\n if len(announcement) > 1024:\n announcement = announcement[:1021] + '...'\n\n embed.add_field(name='⸻\\t\\t\\t⸻\\t\\t\\t⸻\\t\\t\\t⸻\\t\\t\\t⸻',\n value=announcement)\n\n await client.get_channel(619772443116175370).send(embed=embed)\n\n# endregion\n\n\n# region Database Initialization\n# TODO: Include student id, grade, more?\n# https://www.compose.com/articles/using-postgresql-through-sqlalchemy/\n# https://stackoverflow.com/questions/9521020/sqlalchemy-array-of-postgresql-custom-types\n# View database easily with PGAdmin\nengine = sqlalchemy.create_engine(\n 'postgresql://tech:webbie64@localhost:5432/spragueBot.db')\nmetadata = MetaData(engine)\n\nsqlalchemy_utils.functions.drop_database(engine.url)\nsqlalchemy_utils.functions.create_database(engine.url)\n\nmetadata = MetaData(engine)\nmembers = Table('members', metadata,\n Column('first_last', sqlalchemy.types.String, primary_key=True),\n #Column('student_id', sqlalchemy.types.SmallInteger, primary_key=True),\n #Column('grade', sqlalchemy.types.SmallInteger),\n Column('discord_id', sqlalchemy.types.String),\n Column('banned', sqlalchemy.types.Boolean),\n Column('warnings', sqlalchemy.types.ARRAY(CompositeType(\n 'warning', # Include if manually overridden?\n [\n Column('cause', sqlalchemy.types.String),\n Column('offenses', sqlalchemy.types.ARRAY(\n sqlalchemy.String))\n ]\n )))\n )\nstaff = Table('staff', metadata,\n Column('first_last', sqlalchemy.types.String, primary_key=True),\n #Column('student_id', sqlalchemy.types.SmallInteger, primary_key=True),\n #Column('grade', sqlalchemy.types.SmallInteger),\n Column('discord_id', sqlalchemy.types.String),\n Column('roles', sqlalchemy.types.ARRAY(sqlalchemy.types.String))\n )\nverification = Table('verification', metadata,\n Column('message_id', sqlalchemy.types.String,\n primary_key=True),\n Column('channel_id', sqlalchemy.types.String),\n #Column('student_id', sqlalchemy.types.SmallInteger, primary_key=True),\n #Column('grade', sqlalchemy.types.SmallInteger),\n Column('reported_by', sqlalchemy.types.ARRAY(sqlalchemy.types.String)),\n Column('confirmed_by', sqlalchemy.types.String),\n Column('denied_by', sqlalchemy.types.String)\n )\n# metadata.create_all(engine)\n# endregion\n\n\n# region Database Functions\n# TODO: support for searaching for ids?\n\nasync def openDB():\n global sq\n sq = engine.connect()\n\n\nasync def closeDB():\n sq.execute('commit')\n sq.close()\n\n\n#region Member Functions\n\nasync def AddMember(name, id):\n i = text('INSERT IGNROE INTO members (first_last, discord_id) VALUES (:name, :id)')\n await openDB()\n sq.execute(i, name=name, id=id)\n await closeDB()\n\nasync def RemoveMember(indexer, value):\n d = text('DELETE FROM members WHERE :i = :v')\n await openDB()\n sq.execute(d, i=indexer, v=value)\n await closeDB()\n\n#endregion\n\n# region Warning Functions\n\n\nasync def getWarnings(indexer, value):\n s = text('SELECT warnings[:i] FROM members WHERE :ind = :v')\n warnings = []\n await openDB()\n for x in range(3):\n try:\n result = sq.execute(s, i=x, ind=indexer, v=value)\n temp = result.first()[0].split(',', 1)\n cause = temp[0][1:]\n offences = temp[1][2:-3].replace('\\\"', '').split(',')\n warnings.append(Warning(cause, offences))\n except:\n NotImplemented\n\n await closeDB()\n return warnings\n\n\nasync def warningCount(indexer, value):\n s = text('SELECT members, ARRAY_LENGTH(warnings) WHERE :i = :v')\n await openDB()\n count = sq.execute(s, i=indexer, v=value)\n await closeDB()\n return int(count)\n\n\nasync def giveWarning(indexer, value, cause, offences): # TODO: Send message to user\n u = text(\n 'UPDATE members SET warnings = array_append(warnings, (:c, :o)::warning) WHERE :i = :v')\n await openDB()\n sq.execute(u, c=cause, o=offences, i=indexer, v=value)\n await closeDB()\n\n\nasync def removeWarning(indexer, value, cause, offences): # TODO: Send message to user\n u = text(\n 'UPDATE members SET warnings = array_remove(warnings, (:c, :o)::warning) WHERE :i = :v')\n await openDB()\n sq.execute(u, c=cause, o=offences, i=indexer, v=value)\n await closeDB()\n# endregion\n\n# region Staff Functions\n\n\nasync def getStaff(indexer, value):\n s = text('SELECT * FROM staff WHERE :i = :v')\n await openDB()\n staff = sq.execute(s, i=indexer, v=value)\n await closeDB()\n return staff\n\n\nasync def addStaff(name, id, roles): # TODO: Send message to user\n i = text(\n 'INSERT INTO staff (first_last, discord_id, roles) VALUES (:name, :id, (:roles))')\n await openDB()\n sq.execute(i, name=name, id=id, roles=roles)\n await closeDB()\n\n\nasync def removeStaff(indexer, value): # TODO: Send message to user\n d = text('DELETE FROM staff WHERE :i = :v')\n await openDB()\n sq.execute(d, i=indexer, v=value)\n await closeDB()\n# endregion\n\n# region Verification Functions\n\n\nasync def addReport(message, id=None):\n if id == None:\n id = message.content.split(' ')[1]\n msg = message.channel.fetch_message(id)\n\n report = getReport(message, id)\n if report == None:\n i = text(\n 'INSERT IGNORE INTO verification (message_id, channel_id) VALUES (:msg, :cha)')\n await openDB()\n sq.execute(i, msg=msg.id, cha=msg.channel.id)\n await closeDB()\n await sendVerificationEmbed(msg)\n else:\n u = text('UPDATE verification SET reported_by = ARRAY_APPEND(reported_by, :reporter) WHERE message_id = :id')\n await openDB()\n sq.execute(u, reporter=message.author.id, id=msg.id)\n await closeDB()\n await sendVerificationEmbed(msg)\n\n\nasync def getReport(message, id):\n msg = message.channel.fetch_message(id)\n\n s = text('SELECT * FROM verification WHERE message_id = :id')\n await openDB()\n report = sq.execute(s, id=msg.id)\n await closeDB()\n return report\n\n\nasync def verify(indexer, value, id):\n u = text('UPDATE verification SET :i = :v WHERE message_id = :id')\n await openDB()\n sq.execute(u, i=indexer, v=value, id=id)\n await closeDB()\n\n\nasync def sendVerificationEmbed(message):\n embed = discord.Embed(title='Please Verify:',\n description='Case **#%s**' % message.id, color=0xf04923)\n if len(message.attachments) > 1:\n def check(author):\n def inner_check(message):\n return message.author == author and 0 < int(message.content) <= len(message.attachments)\n return inner_check\n\n await message.channel.send('Which attachment? (Decending 1-%i)' % len(message.attachments), delete_after=30)\n try:\n result = await client.wait_for('message', check=check(message.author), timeout=30)\n except:\n await message.channel.send('Error', delete_after=30)\n else:\n sight = await Sight(message, message.attachments[result - 1].proxy_url)\n embed.set_image(url=message.attachments[result - 1].proxy_url)\n embed.add_field(name='Offenses:',\n value=', '.join(sight), inline=True)\n else:\n sight = await Sight(message, message.attachments[0].proxy_url)\n embed.set_image(url=message.attachments[0].proxy_url)\n embed.add_field(\n name='Cause:', value='[Link](%s)' % message.attachments[0].proxy_url, inline=True)\n embed.add_field(name='Offenses:', value=', '.join(sight), inline=True)\n\n embed.set_footer(text='Use %sverify | ✅ to Confirm | ❌ to Deny' % prefix)\n\n await client.get_channel(682637318569721898).send(embed=embed)\n# endregion\n# endregion\n\n\n# region Initialization\n\n# Grab bot token and prefix, sightengine, and tosc file location from json, TODO: Make the prefix changable\nwith open('info.json', 'r') as json_file:\n data = json.load(json_file)\n for j in data['info']:\n token = j['botToken']\n prefix = j['botPrefix']\n SEUser = j['SEUser']\n SESecret = j['SESecret']\n ocrLocation = j['tesseractLocation']\n json_file.close()\n\n# client initialization\nclient = commands.Bot(command_prefix=prefix)\nsight = SightengineClient(SEUser, SESecret)\npytesseract.pytesseract.tesseract_cmd = ocrLocation\n\n# https://digi.bib.uni-mannheim.de/tesseract/tesseract-ocr-w64-setup-v5.0.0-alpha.20190708.exe\n# https://stackoverflow.com/questions/50951955/pytesseract-tesseractnotfound-error-tesseract-is-not-installed-or-its-not-i\n\n# endregion\n\n\n# region Bot Events\n@client.event\nasync def on_ready():\n print('\\nLogged in as:', client.user.name)\n print('ID:', client.user.id)\n print('Discord.py version:', discord.__version__) # using 1.3.1\n print('Python version:', sys.version.split(' ')[0]) # using 3.7.0\n print('SQLAlchemy version:', sqlalchemy.__version__) # using 1.3.13\n print('Ready to use\\n')\n\n\n# Sends new users a message on joining the guild\n# TODO: Test\n# TODO: Check username for profanity\n# TODO: Check avatar with sight engine and require change\n# TODO: Add new users to Database\n@client.event\nasync def on_member_join(member):\n nameProb = predictText(member.name)\n avatarProb = predictImage(member.avatar_url)\n print(nameProb, avatarProb)\n\n embed = discord.Embed(title='Hello `{}`!'.format(\n member.name), type='rich', color=0xf04923)\n embed.set_author(name='Sprague Bot',\n url='https://github.com/Th4tGuy69/Sprague-Bot', icon_url=emojiWave)\n embed.set_footer(text='Remember to make it a great day')\n\n embed.add_field(name='w', value='w')\n\n await member.send(embed=embed)\n\n\n\n@client.event\nasync def on_message(message):\n if message.author == client.user:\n return\n elif message.content.startswith(prefix):\n if 'test' in message.content:\n url = 'https://cdn.discordapp.com/attachments/620167820558204928/675434297775357962/n4VQ3hbwOkofbjhdiqEj_PWILJQ9ssqsCDRuOguC-AufrmYgdaamPE8kxotb52EzoT3ZkkItcvfMIaWzZlpT_yqof2OBocKMu6Dk.png'\n embed = discord.Embed(\n title='Please Verify:', description='Case **#683034905051004999**', color=0xf04923)\n embed.set_image(url=url)\n embed.set_footer(text='✅ to Confirm | ❌ to Deny')\n embed.add_field(\n name='Cause:', value='[Link](%s)' % url, inline=True)\n x = ['Gun', 'Racist']\n embed.add_field(name='Offenses:', value=', '.join(x), inline=True)\n\n await message.channel.send(embed=embed)\n\n # await sentMessage.add_reaction(emoji='✅')\n # await sentMessage.add_reaction(emoji='❌')\n\n def check(reaction, user):\n return user == message.author and str(reaction.emoji) == '✅' or '❌'\n\n try:\n reaction, user = await client.wait_for('reaction_add', timeout=99999, check=check)\n except:\n await message.channel.send('Error')\n else:\n # TODO: change (user == message.author) to check against list of admins/mods/whatever and send to admin chat in server\n if (user == message.author) and (reaction == '✅' or '❌'):\n await message.channel.send(reaction)\n\n elif 'report' in message.content:\n await addReport(message)\n\n elif 'verify ' in message.content:\n if message.author in getStaff('role', 'mod'):\n caseNum = message.content.replace('#', '').split(' ')[1]\n if caseNum != None:\n report = getReport(message, caseNum)\n if report != None:\n await message.add_reaction(emoji='✅')\n await message.add_reaction(emoji='❌')\n\n def check(reaction, user):\n return user == message.author and str(reaction.emoji) == '✅' or '❌'\n\n try:\n reaction, user = await client.wait_for('reaction_add', timeout=30, check=check)\n except:\n await message.channel.send('Error')\n else:\n # TODO: change (user == message.author) to check against list of admins/mods/whatever and send to admin chat in server\n if (user == message.author) and (reaction == '✅' or '❌'):\n if reaction == '✅':\n verify('confirmed_by',\n message.author, caseNum)\n elif reaction == '❌':\n verify('denied_by', message.author, caseNum)\n else:\n await message.channel.send(content='Case #%s not found!' % caseNum)\n\n else:\n await message.channel.send(content='Case number cannot be blank! Check `CHANNEL_NAME` for more info.')\n\n elif 'admin' in message.content:\n # await addStaff('Caden Garrett', '147926148616159233', 'master')\n NotImplemented\n\n attachments = []\n for url in await URL(text):\n attachments.append(url)\n for attach in message.attachments:\n attachments.append(attach.proxy_url)\n\n prob = predictText(message.content)\n if prob > 0.5: # change this value?\n Warn(message.content, '%i%% offensive' % prob, message.author)\n\n for attach in attachments:\n Sight(message, attach)\n# endregion\n\n\n# region Startup\n# Scheduled posting of announcements\nscheduler = AsyncIOScheduler()\nscheduler.add_job(postAnnouncements, trigger='cron',\n day_of_week='mon-fri', hour=7)\nscheduler.start()\n\n\nclient.run(token)\n# endregion\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":20295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"329458176","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpRequest, HttpResponse\nfrom django.core.paginator import Paginator\nfrom .models import *\nfrom .forms import *\n\n\n# Create your views here.\ndef index(request):\n tasks = Task.objects.all()\n paginator = Paginator(tasks, 10)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n form = TaskForm()\n if request.method == 'POST':\n form = TaskForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('/')\n context = {'tasks': tasks, 'form': form, 'page_obj': page_obj}\n return render(request, 'tasks/list.html', context)\n\n\ndef updateTask(request, pk):\n task = Task.objects.get(id=pk)\n #by passing instance=tasl it will show the form with filled task with that id.\n form = TaskForm(instance=task)\n if request.method == 'POST':\n #need to give instance here too otherwise it will create a new task rather than updating the task\n form = TaskForm(request.POST, instance=task)\n if form.is_valid():\n form.save()\n return redirect('/')\n context = {'form': form}\n return render(request, 'tasks/update_task.html', context)\n\n\ndef deleteTask(request, pk):\n task = Task.objects.get(id=pk)\n if request.method == 'POST':\n task.delete()\n return redirect('/')\n context = {'task': task}\n return render(request, 'tasks/delete_task.html', context)\n","sub_path":"tasks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"340225111","text":"# create random data for knn\n\nfrom random import randint\n\nsetNumber = 4\nnumberPoints = 40\nnumberDim = 10\n\ndata_file = open('training-data' + str(setNumber) + '.dat', 'w')\n\nfor i in range(-1, numberPoints):\n\tfor j in range(numberDim):\n\t\tnum = randint(0,2147483640) # num fit in 32bits\n\t\tif i == -1 and j == 0:\n\t\t\tdata_file.write(str(i)+'\\t'+str(num))\n\t\telse:\n\t\t\tif j == 0:\n\t\t\t\tdata_file.write('\\n'+str(i)+'\\t'+str(num))\n\t\t\telse:\n\t\t\t\tdata_file.write('\\t'+str(num))\n\ndata_file.close()\n","sub_path":"dataset/random_data_gen.py","file_name":"random_data_gen.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"347726782","text":"import argparse\r\nimport socket\r\nimport sys\r\nimport os\r\nimport threading\r\n# from time import gmtime, strftime\r\nimport utils\r\nimport time\r\nstart_server = None\r\n\r\n\r\ndef start_server_closure(serverInstance):\r\n\r\n chat_server = serverInstance\r\n\r\n def start_server():\r\n print(\"Listening on port \" + str(chat_server.port))\r\n print(\"Waiting for connections...\\n\")\r\n chat_server.start_listening()\r\n chat_server.server_shutdown()\r\n\r\n return start_server\r\n\r\n\r\nclass DB:\r\n\r\n def __init__(self, db_path):\r\n self.USERS_FILE = db_path + \"/users.txt\"\r\n self.BANNED_USERS_FILE = db_path + \"/banusers.txt\"\r\n self.CHANNELS_FILE = db_path + \"/channels.txt\"\r\n self.BANNER_FILE = db_path + \"/banner.txt\"\r\n\r\n # username -> {username: str, password: str, level: str, banned: bool}\r\n self.users = {}\r\n # str[]\r\n self.banned_users = []\r\n # name -> {name: str, description: str, password: str, channelops: str[]}\r\n self.channels = {}\r\n # str\r\n self.banner = None\r\n\r\n self.refresh_from_files()\r\n\r\n def refresh_from_files(self):\r\n \"\"\"\r\n Loads the DB data with data from the appropriate files\r\n self.banner from the file at BANNER_FILE path\r\n self.users from the file at USERS_FILE path\r\n self.banned_users from the file at BANNED_USERS_FILE path\r\n self.channels from the file at CHANNELS_FILE path\r\n :return:\r\n \"\"\"\r\n # Load banner message from file\r\n try:\r\n with open(self.BANNER_FILE) as banner_file:\r\n self.banner = banner_file.read()\r\n except IOError:\r\n pass\r\n\r\n # Load users from file\r\n for user_line in utils.get_file_lines(self.USERS_FILE):\r\n try:\r\n user_line_splitted = user_line.split(None, 3)\r\n\r\n username = user_line_splitted[0]\r\n\r\n user_password = user_line_splitted[1]\r\n if user_password == '@':\r\n user_password = ''\r\n\r\n user_level = user_line_splitted[2]\r\n if user_level not in [\"user\", \"channelop\", \"sysop\", \"admin\"]:\r\n user_level = \"user\"\r\n\r\n user_is_banned = user_line_splitted[3]\r\n if user_is_banned == \"false\":\r\n user_is_banned = False\r\n elif user_is_banned == \"true\":\r\n user_is_banned = True\r\n else:\r\n user_is_banned = bool(user_is_banned)\r\n\r\n self.users[username] = {\r\n 'username': username,\r\n 'password': user_password,\r\n 'level': user_level,\r\n 'banned': user_is_banned\r\n }\r\n except IndexError:\r\n continue\r\n\r\n # Load banned users from file\r\n self.banned_users = utils.get_file_lines(self.BANNED_USERS_FILE)\r\n\r\n # Load channels from file\r\n for channel_line in utils.get_file_lines(self.CHANNELS_FILE):\r\n try:\r\n channel_line_splitted = channel_line.split(None, 3)\r\n\r\n channel_name = channel_line_splitted[0]\r\n\r\n channel_password = channel_line_splitted[2]\r\n if channel_password == '@':\r\n channel_password = ''\r\n\r\n channel_ops = channel_line_splitted[3]\r\n self.channels[channel_name] = {\r\n 'name': channel_name,\r\n 'description': channel_line_splitted[1],\r\n 'password': channel_password,\r\n 'channelops': [channel_op.strip()\r\n for channel_op in channel_ops.split(\",\")\r\n for channel_op in channel_op.split(None)]\r\n }\r\n except IndexError:\r\n pass\r\n\r\n def persist_to_files(self):\r\n \"\"\"\r\n Persists the DB data to the appropriate files\r\n self.banner to the file at BANNER_FILE path\r\n self.users to the file at USERS_FILE path\r\n self.banned_users to the file at BANNED_USERS_FILE path\r\n self.channels to the file at CHANNELS_FILE path\r\n :return:\r\n \"\"\"\r\n # Persist banner\r\n try:\r\n with open(self.BANNER_FILE, \"w\") as banner_file:\r\n banner_file.write(self.banner)\r\n except IOError:\r\n pass\r\n\r\n # Persist users\r\n users_lines = []\r\n for user in self.users.values():\r\n user_password = user.get(\"password\")\r\n if not user_password:\r\n user_password = \"@\"\r\n\r\n if user.get(\"banned\"):\r\n banned = \"true\"\r\n else:\r\n banned = \"false\"\r\n users_lines.append(\r\n \"%s %s %s %s\" % (\r\n user.get(\"username\", ''),\r\n user_password,\r\n user.get(\"level\", \"user\"),\r\n banned\r\n )\r\n )\r\n utils.save_file_lines(self.USERS_FILE, users_lines)\r\n\r\n # Persist banned users\r\n utils.save_file_lines(self.BANNED_USERS_FILE, self.banned_users)\r\n\r\n # Persist channels\r\n channels_lines = []\r\n for channel in self.channels.values():\r\n channel_password = channel.get(\"password\")\r\n if not channel_password:\r\n channel_password = \"@\"\r\n print(\"-------->\")\r\n print(channel)\r\n channel_ops = \",\".join(channel.get(\"channelops\", []))\r\n print(channel_ops)\r\n channels_lines.append(\r\n \"%s %s %s %s\" % (\r\n channel.get(\"name\"),\r\n channel.get(\"description\"),\r\n channel_password,\r\n channel_ops\r\n )\r\n )\r\n utils.save_file_lines(self.CHANNELS_FILE, channels_lines)\r\n\r\n\r\nclass Server:\r\n\r\n SERVER_CONFIG = {\"BACKLOG\": 15}\r\n\r\n HELP_MESSAGE = \"\"\"\r\n > The list of commands available are:\r\n /quit - Exits the program.\r\n /list - Lists all the users in the chat room.\r\n please refer to https://tools.ietf.org/html/rfc2812 for the parameters of each command\r\n The commands supported by this chat are:\r\n AWAY CONNECT DIE\r\nHELP INFO INVITE ISON\r\nJOIN\r\nKICK\r\nKILL KNOCK LIST MODE NICK NOTICE PART OPER PASS\r\nPING PONG PRIVMSG QUIT RESTART RULES SETNAME SILENCE TIME TOPIC USER USERHOST USERIP USERS VERSION W ALLOPS\r\n \r\nWHO WHOIS\r\n \\n\\n\"\"\".encode('utf8')\r\n\r\n def __init__(self,\r\n db,\r\n host=socket.gethostbyname('localhost'),\r\n port=50000,\r\n allow_reuse_address=True):\r\n self.host = host\r\n self.port = port\r\n self.address = (self.host, self.port)\r\n self.clients = {}\r\n self.client_thread_list = []\r\n\r\n # key: name, value : address\r\n self.client_ips = {}\r\n # key: name, value : username\r\n self.client_usernames = {}\r\n # clients who are away\r\n self.clients_away = {}\r\n\r\n # key: nickname, value: name\r\n self.clients_nicknames = {}\r\n # key : name, value : password\r\n self.clients_passwords = {}\r\n\r\n # users, banned users, channels and banner db\r\n self.db = db\r\n # key: channel_name, value: name[]\r\n self.channel_users = {}\r\n # key : mode, value: name[]\r\n self.mode_of_users = {}\r\n # key : channel name , value : topic\r\n self.channel_topic = {}\r\n\r\n self.online_users = []\r\n\r\n # clients who will be silenced\r\n # key: username of person blocking , value: name[] of people being blocked\r\n self.ignore_list = {}\r\n try:\r\n self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n except socket.error as error_message:\r\n sys.stderr.write(\"Failed to initialize the server. Error - %s\\n\", error_message.strerror)\r\n raise\r\n\r\n if allow_reuse_address:\r\n self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n\r\n try:\r\n self.server_socket.bind(self.address)\r\n except socket.error as error_message:\r\n sys.stderr.write('Failed to bind to (%s, %d). Error - %s\\n', self.host, self.port, error_message.strerror)\r\n raise\r\n\r\n def listen_thread(self, default_greeting=\"\\n> Welcome to our chat app!!! What is your name?\\n\"):\r\n while True:\r\n print(\"Waiting for a client to establish a connection\\n\")\r\n client_socket, client_address = self.server_socket.accept()\r\n print(\"Connection established with IP address {0} and port {1}\\n\".format(client_address[0],\r\n client_address[1]))\r\n client_socket.send(default_greeting.encode('utf8'))\r\n client_thread = threading.Thread(target=self.client_thread, args=(client_socket, client_address))\r\n self.client_thread_list.append(client_thread)\r\n client_thread.start()\r\n\r\n def start_listening(self):\r\n self.server_socket.listen(Server.SERVER_CONFIG[\"BACKLOG\"])\r\n listener_thread = threading.Thread(target=self.listen_thread)\r\n listener_thread.start()\r\n listener_thread.join()\r\n\r\n def server_shutdown(self):\r\n print(\"Shutting down chat server.\\n\")\r\n self.server_socket.shutdown(socket.SHUT_RDWR)\r\n self.server_socket.close()\r\n\r\n def broadcast_message(self, message, name=''):\r\n for client_socket in self.clients:\r\n if self.clients[client_socket] + ': ' != name:\r\n client_socket.send((name + message).encode('utf8'))\r\n else:\r\n client_socket.send(('You: ' + message).encode('utf8'))\r\n\r\n def client_thread(self, client_socket, client_address, size=4096):\r\n name = client_socket.recv(size).decode('utf8')\r\n welcome_message = '> Welcome %s, type /help for a list of helpful commands.\\n\\n' % name\r\n client_socket.send(welcome_message.encode('utf-8'))\r\n chat_message = '\\n> %s has joined the chat!\\n' % name\r\n self.broadcast_message(chat_message)\r\n self.clients[client_socket] = name\r\n self.client_ips[name] = client_address\r\n self.clients_passwords[name] = ''\r\n\r\n while True:\r\n chat_message = client_socket.recv(size).decode('utf8').lower()\r\n print(\"RECEIVED COMMAND: \" + chat_message)\r\n\r\n if chat_message == '/quit':\r\n self.quit(client_socket, client_address, name)\r\n break\r\n elif chat_message == '/users':\r\n self.list_all_users(client_socket, name)\r\n elif chat_message == '/help':\r\n self.help(client_socket)\r\n elif chat_message.startswith('/away'):\r\n self.away(client_socket, chat_message.replace('/away', ''))\r\n elif chat_message.startswith('/connect'):\r\n user_parameters = chat_message.replace('/connect', '', 1).strip().split(' ')\r\n try:\r\n target_server = user_parameters[0]\r\n except IndexError:\r\n client_socket.send('> Required parameter target_server not provided\\n'.encode('utf8'))\r\n continue\r\n try:\r\n target_port = user_parameters[1]\r\n except IndexError:\r\n target_port = 80\r\n self.server_connect(client_socket, target_server, target_port)\r\n elif chat_message == '/die':\r\n self.server_die(client_socket)\r\n elif chat_message.startswith('/info'):\r\n remote_server = chat_message.replace('/info', '', 1).strip()\r\n self.server_information(client_socket, remote_server)\r\n elif chat_message.startswith('/ison'):\r\n nicknames = chat_message.replace('/ison', '', 1).strip().split(' ')\r\n self.ison(client_socket, nicknames)\r\n elif chat_message.startswith('/nick'):\r\n new_nickname = chat_message.replace('/nick', '', 1).strip()\r\n self.nick(client_socket, new_nickname)\r\n elif chat_message.startswith('/pass'):\r\n set_password = chat_message.replace('/pass', '', 1).strip()\r\n self.password(client_socket, set_password)\r\n elif chat_message == '/restart':\r\n self.restart_server()\r\n elif chat_message == '/rules':\r\n self.rules(client_socket)\r\n elif chat_message.startswith('/setname'):\r\n set_the_name = chat_message.replace('/setname', '', 1).strip()\r\n self.set_name(client_socket, set_the_name)\r\n elif chat_message.startswith('/invite'):\r\n parameters = chat_message.replace('/invite', '', 1).strip().split(\" \")\r\n if len(parameters) != 2:\r\n continue\r\n nickname = parameters[0]\r\n channel_name = parameters[1]\r\n self.invite(client_socket, nickname, channel_name)\r\n elif chat_message.startswith('/kick'):\r\n parameters = chat_message.replace('/kick', '', 1).strip().split(\" \", 3)\r\n if len(parameters) <=1 or len(parameters) >= 4:\r\n continue\r\n channels = parameters[0].split(\",\")\r\n print(channels)\r\n users = parameters[1].split(\",\")\r\n print(users)\r\n comment = None\r\n if len(parameters) == 3:\r\n comment = parameters[2]\r\n print(comment)\r\n if len(channels) == 1 and len(users) > 0:\r\n print(users)\r\n for user in users:\r\n print('hi')\r\n self.kick(client_socket, channels[0], user, comment)\r\n elif len(channels) == len(users):\r\n for (channel, user) in zip(channels, users):\r\n self.kick(client_socket, channel, user, comment)\r\n else:\r\n error_message=(\"\"\" in order to kick someone out, there MUST be\r\n either one channel parameter and multiple user parameter, or as many\r\n channel parameters as there are user parameters.\\n\"\"\")\r\n client_socket.send(error_message.encode('utf-8'))\r\n elif chat_message.startswith('/userip'):\r\n nickname = chat_message.replace('/userip', '', 1).strip()\r\n if nickname in self.clients_nicknames: # making sure this nickname exists\r\n self.userip(client_socket, nickname)\r\n else: # nickname does not exist\r\n client_socket.send(\"That nickname does not exist!\\n\".encode('utf8'))\r\n continue\r\n elif chat_message == '/version':\r\n self.version(client_socket)\r\n elif chat_message.startswith('/silence'):\r\n parameters = chat_message.replace('/silence', '', 1).strip().split()\r\n ignore_list = \",\".join(self.ignore_list)\r\n if len(parameters) == 0: # assuming you need a + or a - before the name being silenced\r\n client_socket.send((ignore_list + \"\\n\\n\").encode('utf8'))\r\n else :\r\n self.silence(client_socket, parameters)\r\n elif chat_message.startswith('/join'):\r\n parameters = chat_message.replace('/join', '', 1).strip().split()\r\n '''''\r\n leave_groups = False\r\n if len(parameters) == 3 and parameters[2] == \"0\":\r\n leave_groups = True\r\n elif len(parameters) == 1 and parameters[0] == \"0\":\r\n leave_groups = True\r\n\r\n if leave_groups:\r\n for channel in self.channel_users:\r\n if name in self.channel_users[channel]:\r\n self.channel_users[channel].remove(name)\r\n \r\n if len(parameters) == 2 or len(parameters) == 3:\r\n channels = parameters[0].split(\",\")\r\n passwords = parameters[1].split(\",\")\r\n for (channel, password) in zip(channels, passwords):\r\n if password == \"@\":\r\n password = None\r\n \r\n self.join(client_socket, channel, password)\r\n '''''\r\n if len(parameters) == 1 and parameters[0] != \"0\":\r\n # channels = parameters[0].split(\",\")\r\n channel = parameters[0]\r\n self.join(client_socket, channel)\r\n elif chat_message.startswith('/oper'):\r\n parameters = chat_message.replace('/oper', '', 1).strip().split()\r\n if len(parameters) == 2:\r\n username = parameters[0]\r\n password = parameters[1]\r\n self.oper(client_socket, username, password)\r\n elif chat_message.startswith('/mode'):\r\n parameters = chat_message.replace('/mode', '', 1).strip().split()\r\n if len(parameters) == 3:\r\n nickname = parameters[0]\r\n add_remove = parameters[1]\r\n modes = parameters[2]\r\n self.mode(client_socket, nickname, add_remove, modes)\r\n elif chat_message.startswith('/wallops'):\r\n wallops_message = chat_message.replace('/wallops', '', 1).strip()\r\n self.wallops(client_socket, wallops_message)\r\n elif chat_message.startswith('/topic'):\r\n parameters = chat_message.replace('/topic', '', 1).strip()\r\n new_parameters = parameters.split(\" \", 1)\r\n channel = new_parameters[0]\r\n if len(new_parameters) == 2:\r\n topic_message = new_parameters[1]\r\n self.topic(client_socket, channel, topic_message)\r\n if len(new_parameters) == 1 :\r\n self.topic(client_socket, channel, None)\r\n elif chat_message.startswith('/time'):\r\n parameter = chat_message.replace('/time', '', 1).strip()\r\n self.time(client_socket, parameter)\r\n elif chat_message.startswith('/userhost'):\r\n parameters = chat_message.replace('/userhost', '', 1).strip().split(\" \")\r\n if len(parameters) < 6:\r\n self.userhost(client_socket, parameters)\r\n elif chat_message.startswith('/kill'):\r\n parameters = chat_message.replace('/kill','',1).strip().split(\" \", 1)\r\n nickname = parameters[0]\r\n message = parameters[1]\r\n self.kill(client_socket, nickname, message)\r\n elif chat_message.startswith('/list'):\r\n parameters = chat_message.replace('/list', '', 1).strip().split(\" \")\r\n print(len(parameters))\r\n if parameters[0] == \"\":\r\n self.list(client_socket, '')\r\n else:\r\n channels = parameters[0].split(',')\r\n self.list(client_socket, channels)\r\n\r\n elif chat_message.startswith('/privmsg'):\r\n parameters = chat_message.replace('/privmsg', '', 1).strip().split(\" \")\r\n if len(parameters) != 2:\r\n continue\r\n else:\r\n self.privmsg(client_socket, parameters[0], parameters[1])\r\n elif chat_message.startswith('/notice'):\r\n parameters = chat_message.replace('/notice', '', 1).strip().split(\" \")\r\n if len(parameters) != 2:\r\n continue\r\n self.notice(parameters[0], parameters[1])\r\n elif chat_message.startswith('/knock'):\r\n parameters = chat_message.replace('/knock', '', 1).strip().split(\" \", 1)\r\n if len(parameters) == 2:\r\n self.knock(client_socket, parameters[0], parameters[1])\r\n else:\r\n automated_message = \"{name} requesting an invite to join channel\".format(\r\n name=self.clients[client_socket]\r\n )\r\n self.knock(client_socket, parameters[0], automated_message)\r\n elif chat_message.startswith('/part'):\r\n h = chat_message.replace('/part', '', 1)\r\n parameters = h.strip().split(\" \", 1)\r\n if len(parameters) == 1:\r\n channels = parameters[0].split(\",\")\r\n print(channels)\r\n message = None\r\n self.part(client_socket, channels, message)\r\n elif len(parameters) ==2:\r\n channels = parameters[0].split(\",\")\r\n print(channels)\r\n\r\n message = parameters[1]\r\n print(message)\r\n\r\n # print(channels)\r\n self.part(client_socket, channels, message)\r\n elif chat_message.startswith('/user'):\r\n parameters = chat_message.replace('/user', '', 1).strip().split(\" \", 3)\r\n if len(parameters) != 4:\r\n continue\r\n\r\n username = parameters[0]\r\n real_name = parameters[3]\r\n try:\r\n mode = \"{0:b}\".format(int(parameters[1]))[::-1]\r\n print(mode)\r\n except ValueError:\r\n continue\r\n mode_i = False\r\n mode_w = False\r\n try:\r\n if mode[3] == '1':\r\n mode_i = True\r\n except IndexError:\r\n pass\r\n try:\r\n if mode[2] == '1':\r\n mode_w = True\r\n except IndexError:\r\n pass\r\n\r\n self.user(client_socket, username, real_name, mode_i=mode_i, mode_w=mode_w)\r\n elif chat_message.startswith('/whois'):\r\n parameters = chat_message.replace('/whois', '', 1).strip().split(\" \")\r\n if len(parameters) == 1:\r\n self.whois(client_socket, parameters)\r\n elif chat_message.startswith('/who'):\r\n parameters = chat_message.replace('/who', '', 1).strip().split(\" \")\r\n if len(parameters) == 0:\r\n self.who(client_socket, None, False)\r\n elif len(parameters) == 1:\r\n self.who(client_socket, parameters[0], False)\r\n elif len(parameters) == 2:\r\n if parameters[1] == 'o':\r\n self.who(client_socket, parameters[0], True)\r\n else:\r\n self.who(client_socket, parameters[0], False)\r\n else:\r\n continue\r\n elif chat_message.startswith('/ping'):\r\n parameters = chat_message.replace('/ping', '', 1).strip().split(\" \")\r\n if len(parameters) !=1 :\r\n continue\r\n self.ping(client_socket, parameters[0])\r\n elif chat_message.startswith('/pong'):\r\n parameters = chat_message.replace('/pong', '', 1).strip().split(\" \")\r\n if len(parameters) != 1:\r\n continue\r\n self.pong(client_socket, parameters[0])\r\n\r\n\r\n # elif len(parameters) == 2:\r\n # self.whois(client_socket, parameters[1].split(\",\"))\r\n else:\r\n self.broadcast_message(chat_message + '\\n', name + ': ')\r\n\r\n def quit(self, client_socket, client_address, name=''):\r\n client_socket.send('/quit'.encode('utf8'))\r\n client_socket.close()\r\n del self.clients[client_socket]\r\n self.broadcast_message(('\\n> %s has left the chat room.\\n' % name))\r\n print(\"Connection with IP address {0} has been removed.\\n\".format(client_address[0]))\r\n\r\n def list_all_users(self, client_socket, name=''):\r\n message = \"> The users in the chat room are: \"\r\n users_list = [\"You\" if user == name else user for user in self.clients.values()]\r\n message = message + \", \".join(users_list) + \"\\n\"\r\n client_socket.send(message.encode('utf8'))\r\n\r\n def help(self, client_socket):\r\n client_socket.send(Server.HELP_MESSAGE)\r\n\r\n def away(self, client_socket, away_message=''):\r\n # User has an away message - set away message\r\n if away_message.startswith(' '):\r\n actual_away_message = away_message.replace(' ', '', 1)\r\n if actual_away_message:\r\n self.clients_away[client_socket] = actual_away_message\r\n client_socket.send(\"> Away message was set\\n\\n\".encode('utf8'))\r\n return\r\n\r\n # User has not set an away message - remove away message\r\n del self.clients_away[client_socket]\r\n client_socket.send(\"> Away message was unset\\n\\n\".encode('utf8'))\r\n\r\n def server_connect(self, client_socket, target_server, target_port=None):\r\n try:\r\n # socket created\r\n socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n target_ip_address = socket.gethostbyname(target_server)\r\n socket1.connect((target_ip_address, target_port))\r\n # since the socket connected to the server, a sucess message is sent\r\n success_message = '> Successful connection made to %s:%d\\n' % (target_ip_address, target_port)\r\n client_socket.send(success_message.encode('utf-8'))\r\n except OSError:\r\n # this happens if an error occurs and there is no connection\r\n error_message = '> Cannot make a connection to %s:%d\\n' % (target_server, target_port)\r\n client_socket.send(error_message.encode('utf-8'))\r\n\r\n def server_die(self, client_socket):\r\n # self.broadcast_message('> Server is shutting down.\\n'.encode('utf-8'))\r\n client_socket.send('> Server is shutting down.\\n'.encode('utf-8'))\r\n self.server_shutdown()\r\n\r\n def server_information(self, client_socket, remote_server):\r\n if not remote_server:\r\n server_details = \"\"\"\r\n > The server was implemented as version 1,\r\n for a program for Ortega's Chat assignment\r\n The server's author is Cesia Bulnes\r\n It was compiled in 2018.\r\n \\n\\n\"\"\".encode('utf8')\r\n client_socket.send(server_details)\r\n\r\n def ison(self, client_socket, nicknames):\r\n\r\n for nickname in nicknames:\r\n name = self.clients_nicknames[nickname]\r\n if name in self.clients.values():\r\n if name not in self.online_users:\r\n self.online_users.append(name)\r\n\r\n message = \", \".join(self.online_users) + \"\\n\\n\"\r\n client_socket.send(('\\nISON NICKNAMES currently on IRC:'+ message).encode('utf8'))\r\n\r\n def nick(self, client_socket, new_nickname):\r\n name = self.clients[client_socket]\r\n\r\n # If user had an old nickname, delete it\r\n for (nickname, real_name) in self.clients_nicknames.items():\r\n if name == real_name :\r\n del self.clients_nicknames[nickname]\r\n break\r\n # If someone already had this nickname, notify user\r\n if new_nickname in self.clients_nicknames:\r\n client_socket.send(\"That nickname is already taken!\\n\\n\".encode('utf8'))\r\n return\r\n\r\n self.clients_nicknames[new_nickname] = name\r\n client_socket.send((\"\\nSuccessfully set new nickname!:\\n\\n\" + new_nickname).encode('utf8'))\r\n\r\n def password(self, client_socket, set_password):\r\n real_name = self.clients[client_socket]\r\n if real_name in self.client_usernames.keys():\r\n return\r\n if real_name in self.clients_nicknames.values():\r\n return\r\n\r\n self.clients_passwords[real_name] = set_password\r\n\r\n client_socket.send(\"Successfully set new password!\\n\\n\".encode('utf8'))\r\n\r\n def restart_server(self):\r\n self.server_shutdown()\r\n global start_server\r\n start_server()\r\n\r\n def rules(self, client_socket):\r\n server_rules = \"\"\"\r\n > The rules of the chat are as follows:\r\n Be nice to my grade\r\n \\n\\n\"\"\".encode('utf8')\r\n client_socket.send(server_rules)\r\n\r\n def set_name(self, client_socket, set_the_name):\r\n self.clients[client_socket] = set_the_name\r\n client_socket.send(\"Name is Set\\n\\n\".encode('utf8'))\r\n\r\n def invite(self, client_socket, nickname, channel_name):\r\n # Channel does not exist\r\n if channel_name not in self.channel_users:\r\n client_socket.send(\"That channel does not exist!\\n\\n\".encode('utf8'))\r\n return\r\n\r\n # Channel does exist\r\n try:\r\n real_name = self.clients_nicknames[nickname]\r\n for (recipient_socket, recipient_name) in self.clients.items():\r\n if recipient_name == real_name:\r\n invitation_message = \"\\nYou were invited to join channel %s\" % channel_name\r\n invitation_message = invitation_message + (\",to join simply write /join %s\\n\" % channel_name)\r\n recipient_socket.send(invitation_message.encode('utf8'))\r\n client_socket.send(\"Successfully invited user!\\n\\n\".encode('utf8'))\r\n except KeyError:\r\n client_socket.send(\"User with that nickname cannot be found!\\n\\n\".encode('utf8'))\r\n\r\n def kick(self, client_socket, channel, target_user, comment):\r\n name = self.clients[client_socket]\r\n\r\n if channel not in self.db.channels:\r\n return\r\n\r\n # check if user doing the kicking is an operator\r\n if name not in self.db.channels[channel].get('channelops', []):\r\n client_socket.send(\"You are not an operator, therefore you cannot kick anyone out.\\n\\n\".encode('utf8'))\r\n return\r\n\r\n # check if the target user is in the target channel\r\n if target_user in self.channel_users[channel]:\r\n self.channel_users[channel].remove(target_user)\r\n\r\n for (nickname, real_name) in self.clients_nicknames.items():\r\n if real_name == name:\r\n if comment:\r\n for (user_socket, name_user) in self.clients.items():\r\n if target_user == name_user:\r\n client_socket.send(\"{user} has been kicked\".format(\r\n user=name_user\r\n ).encode('utf8'))\r\n user_socket.send(\"You have been kicked out of channel {channel} by \"\r\n \"{user} because: {comment}\\n\\n\".format(\r\n channel=channel,\r\n user=name,\r\n comment=comment).encode('utf8'))\r\n return\r\n else:\r\n for (user_socket, name_user) in self.clients.items():\r\n if target_user == name_user:\r\n client_socket.send(\"{user} has been kicked\".format(\r\n user=name_user\r\n ).encode('utf8'))\r\n user_socket.send(\"You have been kicked out of channel {channel} by \"\r\n \"{user} because: {kicker_nickname}\\n\\n\".format(\r\n channel=channel,\r\n user=name,\r\n kicker_nickname=nickname).encode('utf8'))\r\n return\r\n\r\n if comment:\r\n for (user_socket, name_user) in self.clients.items():\r\n if target_user == name_user:\r\n client_socket.send(\"{user} has been kicked\".format(\r\n user=name_user\r\n ).encode('utf8'))\r\n user_socket.send(\"You have been kicked out of channel {channel} by \"\r\n \"{user} because: {comment}\\n\\n\".format(\r\n channel=channel,\r\n user=name,\r\n comment=comment).encode('utf8'))\r\n return\r\n else:\r\n for (user_socket, name_user) in self.clients.items():\r\n if target_user == name_user:\r\n client_socket.send(\"{user} has been kicked\".format(\r\n user=name_user\r\n ).encode('utf8'))\r\n user_socket.send(\"You have been kicked out of channel {channel} by \"\r\n \"{user} because: {kicker_nickname}\\n\\n\".format(\r\n channel=channel,\r\n user=name,\r\n kicker_nickname=name).encode('utf8'))\r\n return\r\n\r\n def userip(self, client_socket, nickname):\r\n real_name = self.clients_nicknames[nickname]\r\n ip_address = self.client_ips[real_name]\r\n print(ip_address[0])\r\n client_socket.send((ip_address[0] + '\\n\\n').encode('utf8'))\r\n\r\n def version(self,client_socket):\r\n client_socket.send(\"The version of this chat is version 1.0\\n\\n\".encode('utf8'))\r\n\r\n def silence(self, client_socket, parameters):\r\n name = self.clients[client_socket]\r\n add_or_remove = parameters[0] # + or -\r\n nickname_given = parameters[1]\r\n\r\n if nickname_given in self.clients_nicknames: # nickname of person you're trying to silence\r\n\r\n if name not in self.ignore_list: # if the nickname hasn't been silence\r\n if add_or_remove == '+': # you may silence this person\r\n\r\n self.ignore_list[name] = nickname_given # add this user to the ignore_list\r\n client_socket.send((\"\\n\" + nickname_given + \" was silenced\\n\\n\").encode('utf8'))\r\n\r\n if name in self.ignore_list: # if the nickname has been silenced\r\n if add_or_remove == '-': # you may un-silence this person\r\n print(add_or_remove)\r\n del self.ignore_list[name] # remove this user from the ignore_list\r\n client_socket.send((\"\\n\" + nickname_given + \" was removed from being silenced\\n\\n\").encode('utf8'))\r\n\r\n def join(self, client_socket, channel, password=None):\r\n ''''\r\n channel_password = self.db.channels[channel]['password']\r\n if channel_password and password != channel_password:\r\n client_socket.send(\"Channel requires a password and password specified did not match!\\n\\n\".encode('utf8'))\r\n return\r\n '''\r\n\r\n username_ofperson = self.clients[client_socket]\r\n if channel not in self.channel_users:\r\n self.channel_users[channel] = []\r\n if channel not in self.db.channels:\r\n self.db.channels[channel] = {\r\n \"name\": channel,\r\n \"description\": '',\r\n \"channelops\": []\r\n }\r\n self.db.persist_to_files()\r\n\r\n if username_ofperson not in self.channel_users[channel]:\r\n self.channel_users[channel].append(username_ofperson)\r\n print(self.channel_users[channel])\r\n client_socket.send(\"\\nAdded you to channel {channel}\\n\\n\".format(channel=channel).encode('utf8'))\r\n else:\r\n client_socket.send(\"You're in this channel {channel}\\n\\n\".format(channel=channel).encode('utf8'))\r\n\r\n def oper(self, client_socket, username, password):\r\n name_of_person = self.clients[client_socket]\r\n if self.client_usernames[name_of_person] != username:\r\n return\r\n if (name_of_person, password) in self.clients_passwords.items():\r\n for channel, channel_users in self.channel_users.items(): # key : channel_name, value: [] users\r\n if name_of_person in channel_users:\r\n operator_list = self.db.channels.get(channel, {}).get('channelops', [])\r\n if name_of_person not in operator_list:\r\n operator_list.append(name_of_person)\r\n self.db.channels[channel]['channelops'] = operator_list\r\n\r\n client_socket.send(\"You are now a channel operator of channel {channel}\\n\\n\".format(\r\n channel=channel\r\n ).encode('utf8'))\r\n else:\r\n client_socket.send(\"You are already a channel operator of channel {channel}\\n\\n\".format(\r\n channel=channel\r\n ).encode('utf8'))\r\n\r\n self.db.users[username]['level'] = 'sysop'\r\n self.db.persist_to_files()\r\n\r\n def mode(self, client_socket, nickname, add_remove, modes):\r\n real_name = self.clients[client_socket]\r\n if real_name == self.clients_nicknames[nickname]:\r\n\r\n if modes == 'w' or 'i' or 'O' or 'o' or 'r':\r\n print(modes)\r\n if modes in self.mode_of_users:\r\n users_in_modes = self.mode_of_users[modes]\r\n print(users_in_modes)\r\n if real_name in users_in_modes:\r\n print(real_name)\r\n if add_remove == '-':\r\n if modes == 'o'or modes == 'O':\r\n for channel, channel_dict in self.db.channels.items():\r\n channel_ops = channel_dict.get('channelops', [])\r\n if real_name in channel_ops:\r\n channel_ops.remove(real_name)\r\n channel_dict['channelops'] = channel_ops\r\n self.db.channels[channel] = channel_dict\r\n self.db.persist_to_files()\r\n if modes == 'r':\r\n client_socket.send(\"you cannot - r \\n\".encode('utf8'))\r\n return\r\n users_in_modes.remove(real_name)\r\n client_socket.send(\"your mode has been removed\\n\\n\".encode('utf8'))\r\n elif real_name not in users_in_modes:\r\n if add_remove == '+':\r\n if modes == 'o' or modes == 'O':\r\n client_socket.send(\"please use /oper to set a mode of + o or + O\\n\\n\".encode('utf8'))\r\n else:\r\n users_in_modes.append(real_name)\r\n print(users_in_modes['w'])\r\n client_socket.send(\"your mode has been added\\n\\n\".encode('utf8'))\r\n else:\r\n return\r\n elif modes not in self.mode_of_users:\r\n self.mode_of_users[modes] = []\r\n users_in_modes = self.mode_of_users[modes]\r\n if add_remove == '+':\r\n if modes == 'o' or modes == 'O':\r\n client_socket.send(\"please use /oper to set a mode of + o or + O\\n\\n\".encode('utf8'))\r\n else:\r\n users_in_modes.append(real_name)\r\n print(users_in_modes)\r\n client_socket.send(\"your mode has been added\\n\\n\".encode('utf8'))\r\n else:\r\n client_socket.send(\"You cannot delete yourself from a mode that doesnt exist\\n\\n\".encode('utf8'))\r\n else:\r\n client_socket.send(\"You cannot change someone else's mode\\n\\n\".encode('utf8'))\r\n\r\n def wallops(self, client_socket, wallops_message):\r\n usernames_wallops = self.mode_of_users['w']\r\n print(usernames_wallops)\r\n # usernames_operators = self.mode_of_users['o']\r\n # print(usernames_operators)\r\n # wallops_and_operators = usernames_wallops and usernames_operators\r\n for username in usernames_wallops:\r\n for (user_socket, current_username) in self.clients.items():\r\n if username == current_username:\r\n user_socket.send(('Message to Wallops : '+ wallops_message + '\\n\\n').encode('utf8'))\r\n\r\n client_socket.send('Your message has been sent to users users with modes operators and wallops\\n\\n'.encode('utf8'))\r\n\r\n def topic(self, client_socket, channel, topic_message):\r\n if channel not in self.db.channels:\r\n return\r\n\r\n if topic_message is None:\r\n topic = self.channel_topic.get(channel)\r\n if topic is None:\r\n return\r\n client_socket.send(('the topic in {channel} is {topic}' + '\\n\\n').format(channel=channel,topic=topic).encode(\r\n 'utf8'\r\n ))\r\n else:\r\n self.channel_topic[channel] = topic_message\r\n self.db.channels[channel][\"description\"] = topic_message\r\n self.db.persist_to_files()\r\n\r\n client_socket.send('topic was changed in {channel} to {topic_message}\\n\\n'.format(\r\n channel=channel,\r\n topic_message=topic_message\r\n ).encode('utf8'))\r\n\r\n\r\n def time(self, client_socket, target):\r\n y = time.strftime(\"%I:%M:%S\")\r\n client_socket.send(('time: '+ y + '\\n' ).encode('utf8'))\r\n\r\n def userhost(self,client_socket, nickname_list):\r\n x = len(nickname_list)\r\n print(x)\r\n i=0\r\n while i < x:\r\n for nickname in nickname_list:\r\n if nickname in self.clients_nicknames:\r\n print(nickname)\r\n real_name = self.clients_nicknames[nickname]\r\n print(real_name)\r\n ip = self.client_ips[real_name]\r\n print(ip[0])\r\n ip_address = ip[0]\r\n user_name = self.client_usernames[real_name]\r\n print(user_name)\r\n client_socket.send('The user with the nickname {nickname} ,'\r\n ' has the real name of {real_name} , ip address: {ip_address}, '\r\n 'username: {user_name}\\n\\n'.format(\r\n nickname=nickname, real_name=real_name,\r\n ip_address=ip_address, user_name=user_name).encode('utf8'))\r\n i = i+ 1\r\n\r\n def kill(self, client_socket, nickname, comment):\r\n my_real_name = self.clients[client_socket]\r\n my_username = self.client_usernames.get(my_real_name)\r\n print(my_username)\r\n if self.db.users.get(my_username, '').get('level', '') == 'sysop':\r\n if nickname in self.clients_nicknames:\r\n kill_person_name = self.clients_nicknames[nickname]\r\n for client_socket1 in self.clients:\r\n if self.clients[client_socket1] == kill_person_name:\r\n client_socket1.send('You were killed: {comment}'.format(\r\n comment=comment).encode('utf8'))\r\n client_socket1.close()\r\n del self.clients[client_socket1]\r\n self.broadcast_message(('\\n> %s has been killed from the chat room because %s .\\n' % nickname,\r\n comment))\r\n\r\n def privmsg(self, client_socket, msgtarget, message):\r\n print(msgtarget)\r\n print(self.channel_users.values())\r\n name = self.clients[client_socket]\r\n if msgtarget not in self.channel_users.values():\r\n channel = 'me' + msgtarget\r\n if channel not in self.channel_users:\r\n self.channel_users[channel] = []\r\n if msgtarget not in self.channel_users[channel]:\r\n self.channel_users[channel].append(msgtarget)\r\n\r\n print(self.channel_users[channel])\r\n for (user_socket, user_name) in self.clients.items():\r\n if msgtarget == user_name: # name\r\n user_socket.send((name + ':' + message + \"\\n\\n\").encode('utf8'))\r\n print('done')\r\n return\r\n if msgtarget in self.channel_users.keys():\r\n print(self.channel_users[msgtarget])\r\n users = self.channel_users[msgtarget]\r\n print(users)\r\n for user in users:\r\n for (user_socket, user_name) in self.clients.items():\r\n if user == user_name:\r\n user_socket.send((name + ':' + message + \"\\n\\n\").encode('utf8'))\r\n print('hi')\r\n return\r\n\r\n def notice(self, msgtarget, message):\r\n # msgtarget = channel_name\r\n if self.channel_users[msgtarget] is not None:\r\n print(self.channel_users[msgtarget])\r\n users = self.channel_users[msgtarget]\r\n print(users)\r\n for user in users:\r\n for (user_socket, user_name) in self.clients.items():\r\n if user == user_name:\r\n user_socket.send((message + \"\\n\\n\").encode('utf8'))\r\n print('hi')\r\n return\r\n\r\n def list(self, client_socket, channels):\r\n list_message = \"\"\r\n print(channels )\r\n if channels is '':\r\n print(self.channel_topic.items())\r\n for (channel, topic) in self.channel_topic.items():\r\n list_message = list_message + 'channel: ' + channel + ',' + 'topic: ' + topic + '\\n'\r\n client_socket.send('Channels Information: {list_message}\\n\\n'.format(list_message=list_message).encode('utf8'))\r\n else:\r\n for channel in channels:\r\n if channel in self.channel_topic:\r\n topic = self.channel_topic[channel]\r\n list_message = list_message + 'channel:' + channel + ',' + 'topic:' + topic + '\\n'\r\n client_socket.send('Channels Info: {list_message}\\n\\n'.format(list_message=list_message).encode('utf8'))\r\n\r\n def knock(self, client_socket, channel_target, message):\r\n name = self.clients[client_socket]\r\n if self.channel_users[channel_target] is not None:\r\n print(self.channel_users[channel_target])\r\n users = self.channel_users[channel_target]\r\n print(users)\r\n for user in users:\r\n for (user_socket, user_name) in self.clients.items():\r\n if user == user_name:\r\n user_socket.send(('{name} is requesting to join {channel_target} because : ' + '\"'+ message +\r\n '\"' + \"\\n\\n\")\r\n .format(name=name,channel_target = channel_target).encode('utf8'))\r\n print('hi')\r\n return\r\n '''\r\n if self.db.channels.get(channel_target, None) is not None:\r\n users = self.channel_users[channel_target]\r\n for user in users:\r\n for (user_socket, user_name) in self.clients.items():\r\n if user == user_name:\r\n user_socket.send((message + \"\\n\\n\").encode('utf8'))\r\n client_socket.send(('your requested invitation to %s has been sent\\n\\n' % channel_target).encode(\r\n 'utf8'\r\n ))\r\n return\r\n '''\r\n\r\n def part(self, client_socket, channels, message):\r\n real_name = self.clients[client_socket]\r\n if message is None:\r\n print('message is none')\r\n message = real_name\r\n for (nickname, name) in self.clients_nicknames.items():\r\n if real_name == name:\r\n message = nickname\r\n print(\"hellothere\")\r\n print(channels)\r\n for channel in channels:\r\n print(\"-------->\")\r\n print(channels)\r\n print(channel)\r\n channel_user = self.channel_users[channel]\r\n print(channel_user)\r\n if real_name in channel_user:\r\n channel_user.remove(real_name)\r\n for user in self.channel_users[channel]:\r\n for (user_socket, user_name) in self.clients.items():\r\n if user == user_name:\r\n user_socket.send('User {user} has left channel {channel} with message: {message}\\n\\n'.format(\r\n user=real_name,\r\n channel=channel,\r\n message=message\r\n ).encode('utf8'))\r\n self.channel_users[channel] = channel_user\r\n client_socket.send('You have parted channel {channel}\\n\\n'.format(\r\n channel=channel\r\n ).encode('utf8'))\r\n\r\n def user(self, client_socket, username, real_name, mode_i, mode_w):\r\n print(real_name)\r\n print(self.clients[client_socket])\r\n if real_name == self.clients[client_socket]:\r\n print(real_name)\r\n client_address = self.client_ips[real_name]\r\n print(client_address)\r\n self.client_usernames[real_name] = username\r\n self.db.users[username] = {\r\n \"username\": username,\r\n \"password\": self.clients_passwords[real_name]\r\n }\r\n self.db.persist_to_files()\r\n x = self.clients[client_socket]\r\n print(x)\r\n\r\n if mode_i == 'i':\r\n mode_i_users = self.mode_of_users.get('i', [])\r\n mode_i_users.append(real_name)\r\n self.mode_of_users['i'] = mode_i_users\r\n print(mode_i_users)\r\n if mode_w == 'w':\r\n mode_w_users = self.mode_of_users.get('w', [])\r\n mode_w_users.append(real_name)\r\n self.mode_of_users['w'] = mode_w_users\r\n print(mode_w_users)\r\n client_socket.send('You have successfully been set as a user\\n\\n'.encode('utf8'))\r\n\r\n def who(self, client_socket, name, iso):\r\n\r\n if name is None:\r\n message = \"\"\r\n for (_, some_name) in self.clients.items():\r\n if some_name not in self.mode_of_users.get('i', []):\r\n print(some_name)\r\n message += \"User {user}\\n\".format(user=some_name)\r\n client_socket.send((message + \"\\n\\n\").encode('utf-8'))\r\n return\r\n\r\n for (socket, some_name) in self.clients.items():\r\n if some_name == name:\r\n if iso is True:\r\n for channel, channel_dict in self.db.channels.items():\r\n channel_ops = channel_dict.get('channelops', [])\r\n if name in channel_ops:\r\n\r\n client_socket.send(\"User {user} is an operator\\n\\n\".format(user=name).encode('utf8'))\r\n return\r\n else:\r\n client_socket.send(\"User is not an operator, try again\\n\\n\".encode('utf8'))\r\n return\r\n else:\r\n client_socket.send(\"User {user}\\n\\n\".format(user=name).encode('utf8'))\r\n return\r\n else:\r\n client_socket.send(\"User does not exist\\n\\n\".encode('utf8'))\r\n\r\n def ping(self, client_socket, target):\r\n myname = self.clients[client_socket]\r\n if target in self.online_users:\r\n for (user_socket, name) in self.clients.items():\r\n if target == name:\r\n user_socket.send('{name} : PING \\n\\n'\r\n .format(name=myname).encode('utf8'))\r\n client_socket.send('{name}:PONG\\n'.format(name=target).encode('utf8'))\r\n return\r\n\r\n def pong(self, client_socket, target):\r\n myname = self.clients[client_socket]\r\n if target in self.online_users:\r\n for (user_socket, name) in self.clients.items():\r\n if target == name:\r\n user_socket.send('{name} : PONG \\n\\n'\r\n .format(name=myname).encode('utf8'))\r\n client_socket.send('{name}:PING\\n'.format(name=target).encode('utf8'))\r\n return\r\n\r\n def whois(self, client_socket, nickname_list):\r\n message = \"\"\r\n for nickname in nickname_list:\r\n message += \"Info about {nickname}\\n\".format(nickname=nickname)\r\n if nickname in self.clients_nicknames:\r\n real_name = self.clients_nicknames[nickname]\r\n message += \"Real name: {real_name}\\n\".format(real_name=real_name)\r\n\r\n username = self.client_usernames.get(real_name, None)\r\n if username:\r\n message += \"Username: {username}\\n\".format(username=username)\r\n else:\r\n message += \"No username set\\n\"\r\n\r\n member_of_channels = \"\"\r\n for (channel, user_list) in self.channel_users.items():\r\n if real_name in user_list:\r\n print(channel)\r\n member_of_channels= member_of_channels + channel\r\n print(member_of_channels)\r\n member_of_channels = member_of_channels + \",\"\r\n message += \"Member of channels: {channels}\\n\".format(\r\n channels=member_of_channels\r\n )\r\n message += \"End Info about {nickname}\".format(nickname=nickname)\r\n client_socket.send((message + \"\\n\\n\").encode('utf8'))\r\n\r\n\r\ndef main():\r\n argument_parser = argparse.ArgumentParser(\"IRC Chat Server\")\r\n argument_parser.add_argument(\r\n \"-configuration\",\r\n help=\"Configuration File Path\",\r\n type=str,\r\n default=os.getcwd() + \"/conf/chatserver.conf\"\r\n )\r\n argument_parser.add_argument(\r\n \"-port\",\r\n help=\"Port for the IRC Chat Server\",\r\n type=str,\r\n required=True\r\n )\r\n argument_parser.add_argument(\r\n \"-db\",\r\n help=\"Path for folder containing txt files\",\r\n type=str,\r\n default=None\r\n )\r\n\r\n arguments = argument_parser.parse_args()\r\n config_object = utils.get_config_from_file(getattr(arguments, \"configuration\"))\r\n\r\n # Get the Port and DB Path setting from either the ArgumentParser instance - if it doesn't\r\n # exist there, default to config object\r\n def get_from_args_or_config(arguments, config_object, key):\r\n value = getattr(arguments, key)\r\n if value is None:\r\n if key == \"db\":\r\n key = \"dbpath\"\r\n value = config_object.get(key)\r\n\r\n return value\r\n try:\r\n port = int(get_from_args_or_config(arguments, config_object, \"port\"))\r\n except ValueError:\r\n port = None\r\n if port is None:\r\n print(\"Port is not provided as an argument or config, or is invalid\")\r\n return\r\n db_path = get_from_args_or_config(arguments, config_object, \"db\")\r\n if db_path is None or not os.path.exists(db_path):\r\n print(\"DB path is not provided as an argument or config, or doesn't exist\")\r\n return\r\n\r\n global start_server\r\n start_server = start_server_closure(Server(\r\n port=port,\r\n db=DB(db_path=db_path)\r\n ))\r\n start_server()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"ChatServer.py","file_name":"ChatServer.py","file_ext":"py","file_size_in_byte":56623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"387420289","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n# Copyright 2011, Ryan Inch\n\nimport bpy\n\nfrom bpy.types import (\n PropertyGroup,\n Operator,\n)\n\nfrom bpy.props import StringProperty\n\nlayer_collections = {}\n\ncollection_tree = []\n\nexpanded = []\n\nmax_lvl = 0\nrow_index = 0\n\ndef get_max_lvl():\n return max_lvl\n\ndef update_col_name(self, context):\n if self.name != self.last_name:\n if self.name == '':\n self.name = self.last_name\n return\n\n if self.last_name != '':\n layer_collections[self.last_name][\"ptr\"].collection.name = self.name\n\n update_property_group(context)\n\n self.last_name = self.name\n\nclass CMListCollection(PropertyGroup):\n name: StringProperty(update=update_col_name)\n last_name: StringProperty()\n\n\ndef update_collection_tree(context):\n global max_lvl\n global row_index\n collection_tree.clear()\n layer_collections.clear()\n max_lvl = 0\n row_index = 0\n\n layer_collection = context.view_layer.layer_collection\n init_laycol_list = layer_collection.children\n\n master_laycol = {\"id\": 0,\n \"name\": layer_collection.name,\n \"lvl\": -1,\n \"row_index\": -1,\n \"visible\": True,\n \"has_children\": True,\n \"expanded\": True,\n \"parent\": None,\n \"children\": [],\n \"ptr\": layer_collection\n }\n\n get_all_collections(context, init_laycol_list, master_laycol, master_laycol[\"children\"], visible=True)\n\n for laycol in master_laycol[\"children\"]:\n collection_tree.append(laycol)\n\n\ndef get_all_collections(context, collections, parent, tree, level=0, visible=False):\n global row_index\n global max_lvl\n\n if level > max_lvl:\n max_lvl = level\n\n for item in collections:\n laycol = {\"id\": len(layer_collections) +1,\n \"name\": item.name,\n \"lvl\": level,\n \"row_index\": row_index,\n \"visible\": visible,\n \"has_children\": False,\n \"expanded\": False,\n \"parent\": parent,\n \"children\": [],\n \"ptr\": item\n }\n\n row_index += 1\n\n layer_collections[item.name] = laycol\n tree.append(laycol)\n\n if len(item.children) > 0:\n laycol[\"has_children\"] = True\n\n if item.name in expanded and laycol[\"visible\"]:\n laycol[\"expanded\"] = True\n get_all_collections(context, item.children, laycol, laycol[\"children\"], level+1, visible=True)\n\n else:\n get_all_collections(context, item.children, laycol, laycol[\"children\"], level+1)\n\n\ndef update_property_group(context):\n update_collection_tree(context)\n context.scene.collection_manager.cm_list_collection.clear()\n create_property_group(context, collection_tree)\n\n\ndef create_property_group(context, tree):\n global in_filter\n\n cm = context.scene.collection_manager\n\n for laycol in tree:\n new_cm_listitem = cm.cm_list_collection.add()\n new_cm_listitem.name = laycol[\"name\"]\n\n if laycol[\"has_children\"]:\n create_property_group(context, laycol[\"children\"])\n\n\ndef get_modifiers(event):\n modifiers = []\n\n if event.alt:\n modifiers.append(\"alt\")\n\n if event.ctrl:\n modifiers.append(\"ctrl\")\n\n if event.oskey:\n modifiers.append(\"oskey\")\n\n if event.shift:\n modifiers.append(\"shift\")\n\n return set(modifiers)\n\n\nclass CMSendReport(Operator):\n bl_label = \"Send Report\"\n bl_idname = \"view3d.cm_send_report\"\n\n message: StringProperty()\n\n def draw(self, context):\n layout = self.layout\n\n first = True\n string = \"\"\n\n for num, char in enumerate(self.message):\n if char == \"\\n\":\n if first:\n layout.row().label(text=string, icon='ERROR')\n first = False\n else:\n layout.row().label(text=string, icon='BLANK1')\n\n string = \"\"\n continue\n\n string = string + char\n\n if first:\n layout.row().label(text=string, icon='ERROR')\n else:\n layout.row().label(text=string, icon='BLANK1')\n\n def invoke(self, context, event):\n wm = context.window_manager\n\n max_len = 0\n length = 0\n\n for char in self.message:\n if char == \"\\n\":\n if length > max_len:\n max_len = length\n length = 0\n else:\n length += 1\n\n if length > max_len:\n max_len = length\n\n return wm.invoke_popup(self, width=(30 + (max_len*5.5)))\n\n def execute(self, context):\n self.report({'INFO'}, self.message)\n print(self.message)\n return {'FINISHED'}\n\ndef send_report(message):\n def report():\n window = bpy.context.window_manager.windows[0]\n ctx = {'window': window, 'screen': window.screen, }\n bpy.ops.view3d.cm_send_report(ctx, 'INVOKE_DEFAULT', message=message)\n\n bpy.app.timers.register(report)\n","sub_path":"object_collection_manager/internals.py","file_name":"internals.py","file_ext":"py","file_size_in_byte":5973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"305760469","text":"# Exercise 6: Rewrite your pay computation with time-and-a-half for over-time and create a function called computepay\r\n# which takes two parametres (hours and rate).\r\n\r\n# Enter Hours: 45\r\n# Enter Rate: 10\r\n# Pay: 475.0\r\n\r\ndef computepay(hours,rate):\r\n\thours = input('\\n\\nEnter Hours: ')\r\n\trate = input('\\nEnter Rate: ')\r\n\tif int(hours) > 40:\r\n\t\tPay = (int(hours) * float(rate) - 40 * float(rate)) * 1.5 + 40 * float(rate)\r\n\telse:\t\t\t\r\n\t\tPay = int(hours) * float(rate)\r\n\tprint('----------------\\nPay: ',Pay)\r\n#\treturn Pay\r\nresult = computepay(45,10)\r\n# nd: version two:\r\n# n = computepay(45,10)\r\n# print(n)","sub_path":"ch6_exec_6.py","file_name":"ch6_exec_6.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"391175042","text":"import datetime\nimport os\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\nimport transform\nfrom config import train_data, edge_data, test_data\nfrom data import ImageFolder, ImageFolder_multi_scale\nfrom misc import AvgMeter, check_mkdir\nfrom model import DSE, D_U, initialize_weights, weights_init_kaiming_u, weights_init_kaiming_n, weights_init_xav_u\nfrom torch.backends import cudnn\nfrom torch.utils import model_zoo\nimport torch.nn.functional as functional\nimport torch.nn.functional as F\nfrom test_epoch import test_enc, test_all\n\n\ndef main(args):\n model_enc = DSE()\n initialize_weights(model_enc)\n weights_init_kaiming_n(model_enc.net.feat)\n weights_init_kaiming_u(model_enc.net.feat_1)\n weights_init_xav_u(model_enc.net.feat_2)\n pretrained_dict = torch.load('vgg_weights/vgg16.pth')\n\n model_dict = model_enc.net.base.state_dict()\n for k, v in pretrained_dict.items():\n if k[9:] in model_dict:\n model_dict[k[9:]] = v\n model_enc.net.base.load_state_dict(model_dict)\n model_dec = D_U().cuda().train()\n initialize_weights(model_dec)\n model_enc = model_enc.cuda().train()\n\n ##############################Optim setting###############################\n\n optimizer_enc = optim.Adam([\n {'params': [param for name, param in model_enc.named_parameters() if name[-4:] == 'bias'],\n 'lr': args.lr_dec},\n {'params': [param for name, param in model_enc.named_parameters() if name[-4:] != 'bias'],\n 'lr': args.lr_enc}\n ])\n\n optimizer_dec = optim.Adam([\n {'params': [param for name, param in model_dec.named_parameters() if name[-4:] == 'bias'],\n 'lr': args.lr_dec},\n {'params': [param for name, param in model_dec.named_parameters() if name[-4:] != 'bias'],\n 'lr': args.lr_dec}\n ])\n\n if len(args.snapshot) > 0 and args.Resume:\n print('training resumes from ' + args.snapshot)\n model_enc.load_state_dict(torch.load(os.path.join(ckpt_path, args.exp_name, args.snapshot + '_enc.pth')))\n model_dec.load_state_dict(torch.load(os.path.join(ckpt_path, args.exp_name, args.snapshot + '_dec.pth')))\n\n optimizer_enc.load_state_dict(\n torch.load(os.path.join(ckpt_path, args.exp_name, args.snapshot + '_enc_optim.pth')))\n\n # optimizer_enc.param_groups['lr_enc'] = 2 * args.lr_enc\n optimizer_enc.param_groups[0]['lr_enc'] = args.lr_enc\n\n optimizer_dec.load_state_dict(\n torch.load(os.path.join(ckpt_path, args.exp_name, args.snapshot + '_enc_optim.pth')))\n\n # optimizer_dec.param_groups[0]['lr_dec'] = 2 * args.lr_dec\n optimizer_dec.param_groups[0]['lr_dec'] = args.lr_dec\n\n check_mkdir(ckpt_path)\n check_mkdir(os.path.join(ckpt_path, args.exp_name))\n open(log_path, 'w').write(str(args) + '\\n\\n')\n train(model_enc, model_dec, optimizer_enc, optimizer_dec)\n\n\n#########################################################################\n\ndef train(model_enc, model_dec, optimizer_enc, optimizer_dec):\n best_mae = 100000\n curr_iter = args.last_iter\n flag = True\n loss_enc_1_record, loss1_enc_sal_record, loss1_enc_sal_e_record, loss1_enc_ed_record, loss1_enc_mlm_record = AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter()\n while flag and curr_iter < 500:\n # print(curr_iter,'0000')\n # loss_enc_1_record, loss1_enc_sal_record,loss1_enc_sal_e_record, loss1_enc_ed_record,loss1_enc_mlm_record = AvgMeter(),AvgMeter(),AvgMeter(),AvgMeter(),AvgMeter()\n # total_loss_record,loss2_record, loss3_record, loss4_record, loss5_record, loss6_record, loss7_record, loss8_record = AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter(), AvgMeter()\n for i, data in enumerate(train_loader):\n optimizer_enc.param_groups[0]['lr'] = args.lr_enc * (1 - float(curr_iter) / args.iter_num\n ) ** args.lr_decay\n optimizer_enc.param_groups[1]['lr'] = args.lr_enc * (1 - float(curr_iter) / args.iter_num\n ) ** args.lr_decay\n\n optimizer_dec.param_groups[0]['lr'] = args.lr_dec * (1 - float(curr_iter) / args.iter_num\n ) ** args.lr_decay\n optimizer_dec.param_groups[1]['lr'] = args.lr_dec * (1 - float(curr_iter) / args.iter_num\n ) ** args.lr_decay\n # data\\binarizing\\Variable\n img, target, e_target, ed_img, ed_target = data\n target[target > 0.5] = 1\n target[target != 1] = 0\n e_target[e_target > 0.5] = 1\n e_target[e_target != 1] = 0\n ed_target[ed_target > 0.5] = 1\n ed_target[ed_target != 1] = 0\n batch_size = img.size(0)\n inputs = Variable(img).cuda()\n labels = Variable(target).cuda()\n e_labels = Variable(e_target).cuda()\n ed_inputs = Variable(ed_img).cuda()\n ed_labels = Variable(ed_target).cuda()\n\n optimizer_enc.zero_grad()\n optimizer_dec.zero_grad()\n\n (f_1, f_2, f_3, m, m_1, m_2, e, edges) = model_enc(inputs, ed_inputs)\n ##########loss#############\n\n ###encoder edge loss\n\n D_masks_loss, D_sal_edges_loss, D_edges_loss = cal_DLoss(m, m_1, m_2, e, edges, labels, e_labels, ed_labels)\n\n mlm_loss = cal_MLMLoss(m, m_1, m_2, curr_iter)\n\n loss_enc_1 = 5 * D_masks_loss + 5 * D_sal_edges_loss + D_edges_loss + 2*mlm_loss\n loss_enc_1.backward()\n optimizer_enc.step()\n\n loss_enc_1_record.update(loss_enc_1.item(), batch_size)\n loss1_enc_sal_record.update(D_masks_loss.item(), batch_size)\n loss1_enc_sal_e_record.update(D_sal_edges_loss.item(), batch_size)\n loss1_enc_ed_record.update(D_edges_loss.item(), batch_size)\n loss1_enc_mlm_record.update(mlm_loss.item(), batch_size)\n\n #############log###############\n # print(curr_iter)\n curr_iter += 1\n if curr_iter % 200 == 0:\n log = '[iter %d], [enc total loss %.5f],[loss_sal %.5f],[loss_sal_e %.5f],[loss_ed %.5f],[lr %.13f] ' % \\\n (curr_iter, loss_enc_1_record.avg, loss1_enc_sal_record.avg, loss1_enc_sal_e_record.avg,\n loss1_enc_ed_record.avg, optimizer_enc.param_groups[0]['lr'])\n print(log)\n open(log_path, 'a').write(log + '\\n')\n\n if curr_iter % args.test_num == 0:\n mae = test_enc(test_loader, model_enc)\n print(args.exp_name, '========', curr_iter, '------', float(mae), '----', float(best_mae))\n\n # print(mae)\n if mae < best_mae:\n best_mae = mae\n # torch.save(model_enc.state_dict(), os.path.join(ckpt_path, args.exp_name, '_%d_enc.pth' % curr_iter))\n # torch.save(optimizer_enc.state_dict(),\n # os.path.join(ckpt_path, args.exp_name, '_%d_enc_optim.pth' % curr_iter))\n mae_log = '[iter %d], [best mae %.5f]' % (curr_iter, float(mae))\n print(mae_log)\n open(mae_log_path, 'a').write(mae_log + '\\n')\n if curr_iter > 500:\n break\n if curr_iter > 500:\n break\n\n while True and curr_iter >= 500 and curr_iter < args.iter_num:\n # loss_enc_1_record, loss1_enc_sal_record, loss1_enc_ed_record = AvgMeter(), AvgMeter(), AvgMeter()\n total_loss_record, loss_dec_mask_record, loss_dec_cont_record = AvgMeter(), AvgMeter(), AvgMeter()\n # print(curr_iter,'----')\n for i, data in enumerate(train_loader):\n optimizer_enc.param_groups[0]['lr'] = args.lr_enc * (1 - float(curr_iter) / args.iter_num\n ) ** args.lr_decay\n optimizer_enc.param_groups[1]['lr'] = args.lr_enc * (1 - float(curr_iter) / args.iter_num\n ) ** args.lr_decay\n\n optimizer_dec.param_groups[0]['lr'] = args.lr_dec * (1 - float(curr_iter) / args.iter_num\n ) ** args.lr_decay\n optimizer_dec.param_groups[1]['lr'] = args.lr_dec * (1 - float(curr_iter) / args.iter_num\n ) ** args.lr_decay\n # data\\binarizing\\Variable\n img, target, e_target, ed_img, ed_target = data\n target[target > 0.5] = 1\n target[target != 1] = 0\n e_target[e_target > 0.5] = 1\n e_target[e_target != 1] = 0\n ed_target[ed_target > 0.5] = 1\n ed_target[ed_target != 1] = 0\n batch_size = img.size(0)\n inputs = Variable(img).cuda()\n labels = Variable(target).cuda()\n e_labels = Variable(e_target).cuda()\n ed_inputs = Variable(ed_img).cuda()\n ed_labels = Variable(ed_target).cuda()\n\n optimizer_enc.zero_grad()\n optimizer_dec.zero_grad()\n\n (f_1, f_2, f_3, m, m_1, m_2, e, edges) = model_enc(inputs, ed_inputs)\n\n ##########loss#############\n\n ###encoder edge loss\n mlm_loss = cal_MLMLoss(m, m_1, m_2, curr_iter)\n # m_de, e_de = model_dec(f_1)\n\n # D_masks_loss, D_sal_edges_loss, D_edges_loss = cal_DLoss(m, m_1, m_2, e, edges, labels, e_labels,\n # ed_labels)\n m_de, e_de = model_dec(f_1)\n F_mask_loss, F_cont_loss = cal_DecLoss(m_de, e_de, labels, e_labels)\n\n # mlm_loss = cal_MLMLoss(m,m_1,m_2,curr_iter)\n\n loss_total = 2*mlm_loss + 10 * F_mask_loss + 10* F_cont_loss\n\n loss_total.backward()\n # optimizer_dec.step()\n optimizer_enc.step()\n\n optimizer_dec.zero_grad()\n for j, fea in enumerate(f_1):\n f_1[j] = fea.detach()\n m_dec, e_dec = model_dec(f_1)\n\n # D_masks_loss, D_sal_edges_loss, D_edges_loss = cal_DLoss(m, m_1, m_2, e, edges, labels, e_labels,\n # ed_labels)\n F_mask_loss, F_cont_loss = cal_DecLoss(m_dec, e_dec, labels, e_labels)\n\n # mlm_loss = cal_MLMLoss(m, m_1, m_2, curr_iter)\n\n loss_total = 10 * F_mask_loss + 10 * F_cont_loss\n loss_total.backward()\n # optimizer_dec.step()\n optimizer_dec.step()\n\n # loss_enc_1_record.update(loss_enc_1.item(), batch_size)\n loss1_enc_sal_record.update(D_masks_loss.item(), batch_size)\n loss1_enc_ed_record.update(D_edges_loss.item(), batch_size)\n loss1_enc_mlm_record.update(mlm_loss.item(), batch_size)\n\n total_loss_record.update(loss_total.item(), batch_size)\n loss_dec_mask_record.update(F_mask_loss.item(), batch_size)\n loss_dec_cont_record.update(F_cont_loss.item(), batch_size)\n\n #############log###############\n curr_iter += 1\n # print(curr_iter)\n if curr_iter % 200 == 0:\n log = '[iter %d], [loss_sal %.5f],[loss_ed %.5f],[lr %.13f] ' % \\\n (curr_iter, loss1_enc_sal_record.avg,\n loss1_enc_ed_record.avg, optimizer_enc.param_groups[0]['lr'])\n print(log)\n open(log_path, 'a').write(log + '\\n')\n log = '[iter %d], [ dec total loss %.5f],[loss_sal %.5f],[loss_sal_e %.5f][lr %.13f] ' % \\\n (curr_iter, total_loss_record.avg, loss_dec_mask_record.avg, loss_dec_cont_record.avg,\n optimizer_dec.param_groups[0]['lr'])\n print(log)\n open(log_path, 'a').write(log + '\\n')\n\n if curr_iter % args.test_num == 0:\n mae = test_all(test_loader, model_enc, model_dec)\n print(args.exp_name, '========', curr_iter, '------', float(mae), '----', float(best_mae))\n if mae < best_mae:\n best_mae = mae\n # torch.save(model_enc.state_dict(), os.path.join(ckpt_path, args.exp_name, '_%d_enc.pth' % curr_iter))\n # torch.save(optimizer_enc.state_dict(),\n # os.path.join(ckpt_path, args.exp_name, '_%d_enc_optim.pth' % curr_iter))\n # torch.save(model_dec.state_dict(), os.path.join(ckpt_path, args.exp_name, '_%d_dec.pth' % curr_iter))\n # torch.save(optimizer_dec.state_dict(),\n # os.path.join(ckpt_path, args.exp_name, '_%d_dec_optim.pth' % curr_iter))\n mae_log = '[iter %d], [best mae %.5f]' % (curr_iter, float(mae))\n print(mae_log)\n open(mae_log_path, 'a').write(mae_log + '\\n')\n\n return\n ## #############end###############\n\n\ndef cal_DLoss(m, m_1, m_2, e, edges, labels, sal_e_labels, ed_labels):\n # m,m_1,m_2, e, edges, labels,ed_labels\n\n D_masks_loss = 0\n D_edges_loss = 0\n D_sal_edges_loss = 0\n\n for i in range(6):\n\n if i < 3:\n D_masks_loss = D_masks_loss + F.binary_cross_entropy(m[3 + i], labels) / 3\n D_masks_loss = D_masks_loss + F.binary_cross_entropy(m_1[3 + i], labels) / 3\n D_masks_loss = D_masks_loss + F.binary_cross_entropy(m_2[3 + i], labels) / 3\n\n D_sal_edges_loss = D_sal_edges_loss + F.binary_cross_entropy(e[i], sal_e_labels)\n D_edges_loss = D_edges_loss + F.binary_cross_entropy(edges[i], ed_labels)\n\n if i == 3:\n D_edges_loss = D_edges_loss + 2 * F.binary_cross_entropy(edges[i], ed_labels)\n\n return D_masks_loss, D_sal_edges_loss, D_edges_loss\n\n\ndef cal_MLMLoss(m, m_1, m_2, iter):\n loss = 0\n for i in range(len(m)):\n if iter % 3 == 0:\n loss = loss + criterion_mse(m[i], m_1[i].detach()) + criterion_mse(m[i], m_2[i].detach())\n elif iter % 3 == 1:\n loss = criterion_mse(m_1[i], m[i].detach()) + criterion_mse(m_1[i], m_2[i].detach())\n elif iter % 3 == 2:\n loss = criterion_mse(m_2[i], m[i].detach()) + criterion_mse(m_2[i], m[i].detach())\n return loss / len(m) / 10/10\n\n\ndef cal_DecLoss(masks, e_m, l, e_l):\n ###interwined ouput m total three preds\n e_loss = 0\n m_loss = 10 * F.binary_cross_entropy(masks[2], l)\n\n m_loss = m_loss + F.binary_cross_entropy(masks[0], l)\n m_loss = m_loss + F.binary_cross_entropy(masks[1], l)\n # pre_ms_l_256 = F.binary_cross_entropy(masks[2], label_batch)\n\n ###interwined ouput e total two preds\n for i in range(2):\n e_loss = e_loss + F.binary_cross_entropy(e_m[i], e_l)\n e_loss = e_loss + F.binary_cross_entropy(e_m[i], e_l)\n return m_loss, e_loss\n\n\nif __name__ == '__main__':\n # args.exp_name = 'model_mlmsnet'\n # args = {\n # 'iter_num': 200000,\n # 'train_batch_size': 1,\n # 'test_batch_size': 1,\n # 'last_iter': 0,\n # 'lr_enc': 5e-4,\n # 'lr_dec': 1e-3,\n # 'lr_decay': 0.9,\n # 'weight_decay': 0.0005,\n # 'momentum': 0.9,\n # 'snapshot': '',\n # 'test_num': 1000\n # }\n import argparse\n\n parser = argparse.ArgumentParser()\n # train\n parser.add_argument('--exp_name', default='v23_enc8e5dec1e4', type=str)\n parser.add_argument('--Training', default=True, type=bool, help='Training or not')\n\n parser.add_argument('--Resume', default=False, type=bool)\n parser.add_argument('--iter_num', default=400000, type=int)\n parser.add_argument('--train_batch_size', default=5, type=int)\n parser.add_argument('--test_batch_size', default=5, type=int)\n parser.add_argument('--last_iter', default=0, type=int)\n parser.add_argument('--lr_enc', default=8e-5, type=float, help='learning rate')\n parser.add_argument('--lr_dec', default=1e-4, type=float, help='epochs')\n parser.add_argument('--weight_decay', default=0.0005, type=float, help='batch_size')\n parser.add_argument('--lr_decay', default=0.9, type=float)\n parser.add_argument('--momentum', default=0.9, type=int, help='the step 1 for adjusting lr')\n parser.add_argument('--test_num', default=500, type=int, help='the step 2 for adjusting lr')\n parser.add_argument('--snapshot', default='0', type=str, help='Trainging set')\n\n # test\n parser.add_argument('--Testing', default=False, type=bool, help='Testing or not')\n parser.add_argument('--save_test_path_root', default='preds/', type=str, help='save saliency maps path')\n parser.add_argument('--test_paths', type=str, default='DUTS/DUTS-TE+ECSSD')\n\n # evaluation\n parser.add_argument('--Evaluation', default=False, type=bool, help='Evaluation or not')\n parser.add_argument('--methods', type=str, default='RGB_VST', help='evaluated method name')\n parser.add_argument('--save_dir', type=str, default='./', help='path for saving result.txt')\n\n args = parser.parse_args()\n\n # vis = visdom.Visdom(env='train')\n cudnn.benchmark = True\n torch.manual_seed(2018)\n\n ##########################hyperparameters###############################\n ckpt_path = './model'\n\n ##########################data augmentation###############################\n transform = transform.Compose([\n transform.RandomCrop(256, 256), # change to resize\n transform.Gaussian_noise_Contrast_Light(),\n transform.RandomHorizontallyFlip(),\n transform.RandomRotate(10)\n ])\n img_transform = transforms.Compose([\n transforms.ColorJitter(0.1, 0.1, 0.1),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ])\n target_transform = transforms.ToTensor()\n ##########################################################################\n train_set = ImageFolder_multi_scale(train_data, edge_data, transform, img_transform, target_transform)\n train_loader = DataLoader(train_set, batch_size=args.test_batch_size, num_workers=0, shuffle=True)\n\n test_set = ImageFolder_multi_scale(test_data, edge_data, transform, img_transform, target_transform)\n test_loader = DataLoader(test_set, batch_size=args.test_batch_size, num_workers=0, shuffle=True)\n # for i,data in enu(test_loader)\n ###multi-scale-train\n # train_set = ImageFolder_multi_scale(train_data, transform, img_transform, target_transform)\n # train_loader = DataLoader(train_set, collate_fn=train_set.collate, batch_size=args['train_batch_size'], num_workers=12, shuffle=True, drop_last=True)\n\n criterion = nn.BCEWithLogitsLoss()\n criterion_BCE = nn.BCELoss()\n criterion_mse = nn.MSELoss()\n\n log_path = os.path.join(ckpt_path, args.exp_name, str(datetime.datetime.now()) + '.txt')\n mae_log_path = os.path.join(ckpt_path, args.exp_name, str(datetime.datetime.now()) + '_mae.txt')\n if args.Training:\n main(args)\n # if args.Testing:\n # base_testing.test_net(args)\n # if args.Evaluation:\n # main.evaluate(args)\n","sub_path":"train_mlm.py","file_name":"train_mlm.py","file_ext":"py","file_size_in_byte":19440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"218900660","text":"import requests\r\nimport tkinter\r\nfrom tkinter import *\r\ndef info():\r\n Label2=Label(win,text='')\r\n city=entry.get()\r\n api_address=\"http://api.openweathermap.org/data/2.5/weather?appid=3defd2c9a687fd9ebf60c5534fd71a33&q=\"\r\n url=api_address+city\r\n json_data=requests.get(url).json()\r\n formatted_data=json_data['weather'][0]['description']\r\n v.set(formatted_data)\r\n data=int(json_data['main']['temp'])-273\r\n k.set(str(data)+\" Celcius\")\r\n \r\n\r\nwin=tkinter.Tk()\r\nwin.geometry('500x500')\r\nLabel1=Label(win,text=\"Enter the city\",font=('verdana',15))\r\nLabel1.pack(pady=30)\r\nentry=Entry(win,font=('verdana',25))\r\nentry.pack(ipadx=10,ipady=10)\r\nb1=Button(win,text='Click',width=20,command=info)\r\nb1.pack(padx=15,ipady=15,pady=30)\r\nv = StringVar()\r\nLabel2=Label(win,font=('verdana',15), textvariable=v).pack()\r\nk=StringVar()\r\nLabel3=Label(win,font=('verdana',15), textvariable=k).pack()\r\nwin.mainloop()\r\n","sub_path":"Weather Apip_Gui.py","file_name":"Weather Apip_Gui.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"443319644","text":"from flask import Flask, render_template, request, redirect, url_for, session\nfrom flask_sqlalchemy import SQLAlchemy\nfrom forms.ProductsForm import ProductsForm\nfrom forms.StoreForm import StoreForm\nfrom forms.ProductsFormEdit import ProductsFormEdit\nfrom forms.RecommendationForm import RecommendationForm\nfrom forms.CharacteristicForm import CharacteristicForm\nfrom forms.StoreFormEdit import StoreFormEdit\nfrom forms.RecommendationFormEdit import RecommendationFormEdit\nfrom forms.CharacteristicFormEdit import CharacteristicFormEdit\nfrom forms.RegistrationForm import RegistrationForm\nfrom forms.LoginForm import LoginForm\nfrom forms.SearchForm import CreateQuery\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import StandardScaler\n\nfrom sqlalchemy.sql import func\nimport plotly\nimport plotly.graph_objs as go\nimport pandas as pd\nfrom sklearn.cluster import KMeans\nimport numpy as np\nfrom neupy import algorithms\n\nimport json\n\n\napp = Flask(__name__)\napp.secret_key = 'key'\n\nENV = 'prod'\n\nif ENV == 'dev':\n app.debug = True\n app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:blackjack21@localhost/Vadim_Pits'\nelse:\n app.debug = False\n app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://ofqdxhaxghbqqj:7f571b6b061e1b78a2f0d42af68cb78740ab37209da105584ba82bfad83e50fa@ec2-174-129-33-25.compute-1.amazonaws.com:5432/dflccpekfv3rhp'\n\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\nlist_product = []\n\n\nclass Products (db.Model):\n __tablename__ = 'products'\n product_id = db.Column(db.Integer, primary_key=True)\n product_name = db.Column(db.String(20))\n product_model = db.Column(db.String(20))\n\n products_store_fk = db.relationship(\"Store\", secondary=\"products_store\")\n products_characteristic_fk = db.relationship(\"Characteristic\", secondary=\"characteristic_products\")\n recommendation_id = db.Column(db.Integer, db.ForeignKey('recommendation.recommendation_id'))\n\n\nclass Store(db.Model):\n __tablename__ = 'store'\n store_name = db.Column(db.String(20), primary_key=True)\n\n store_fk = db.relationship(\"Products\", secondary=\"products_store\")\n\n\nclass Products_Store(db.Model):\n __tablename__ = 'products_store'\n left_name = db.Column(db.Integer, db.ForeignKey('products.product_id'), primary_key=True)\n right_name = db.Column(db.String(20), db.ForeignKey('store.store_name'), primary_key=True)\n\n\nclass Recommendation(db.Model):\n __tablename__ = 'recommendation'\n recommendation_id = db.Column(db.Integer, primary_key=True)\n recommendation_price = db.Column(db.Integer)\n recommendation_name = db.Column(db.String(20))\n recommendation_model = db.Column(db.String(20))\n\n recommendation_products = db.relationship(\"Products\")\n\n\nclass Characteristic(db.Model):\n __tablename__ = 'characteristic'\n characteristic_id = db.Column(db.Integer, primary_key=True)\n characteristic_specification = db.Column(db.String(40))\n characteristic_price = db.Column(db.Integer)\n\n characteristic_fk = db.relationship(\"Products\", secondary=\"characteristic_products\")\n\n\nclass Characteristic_Products(db.Model):\n __tablename__ = 'characteristic_products'\n left_name = db.Column(db.Integer, db.ForeignKey('characteristic.characteristic_id'), primary_key=True)\n right_name = db.Column(db.Integer, db.ForeignKey('products.product_id'), primary_key=True)\n\n\nclass User(db.Model):\n __tablename__ = 'user'\n\n user_email = db.Column(db.String(20), primary_key=True)\n user_password = db.Column(db.String(30), nullable=False)\n\n\n# создание всех таблиц\n# db.create_all()\n#\n# очистрка всех таблиц\n#\ndb.session.query(Characteristic_Products).delete()\ndb.session.query(Products_Store).delete()\ndb.session.query(Characteristic).delete()\ndb.session.query(Products).delete()\ndb.session.query(Recommendation).delete()\ndb.session.query(Store).delete()\ndb.session.query(User).delete()\n\n\n# создане объектов\n\nLexus = Products(product_id=1,\n product_name='Lexus',\n product_model='LX350'\n )\n\nBMW = Products(product_id=2,\n product_name='BMW',\n product_model='X5'\n )\n\nAudi = Products(product_id=3,\n product_name='Audi',\n product_model='A8'\n )\n\nZAZ = Products(product_id=4,\n product_name='ZAZ',\n product_model='Vida'\n )\n\nMazda = Products(product_id=5,\n product_name='Mazda',\n product_model='Model 6'\n )\n\nR_Lexus = Recommendation(recommendation_id=1,\n recommendation_price=30000,\n recommendation_name='Lexus',\n recommendation_model='LX350')\n\nR_BMW = Recommendation(recommendation_id=2,\n recommendation_price=20000,\n recommendation_name='BMW',\n recommendation_model='X5'\n )\n\nR_Audi = Recommendation(recommendation_id=3,\n recommendation_price=40000,\n recommendation_name='Audi',\n recommendation_model='A8'\n )\n\nR_ZAZ = Recommendation(recommendation_id=4,\n recommendation_price=4000,\n recommendation_name='ZAZ',\n recommendation_model='Vida'\n )\n\nR_Mazda = Recommendation(recommendation_id=5,\n recommendation_price=10000,\n recommendation_name='Mazda',\n recommendation_model='Model 6'\n )\n\nChar_1 = Characteristic(characteristic_id=1,\n characteristic_specification='White',\n characteristic_price=30000\n )\n\nChar_2 = Characteristic(characteristic_id=2,\n characteristic_specification='Black',\n characteristic_price=20000\n )\n\nChar_3 = Characteristic(characteristic_id=3,\n characteristic_specification='Gold',\n characteristic_price=40000\n )\n\nChar_4 = Characteristic(characteristic_id=4,\n characteristic_specification='Pink',\n characteristic_price=4000\n )\n\nChar_5 = Characteristic(characteristic_id=5,\n characteristic_specification='Grey',\n characteristic_price=10000\n )\n\nSt_name_1 = Store(store_name='Ukraine')\n\nSt_name_2 = Store(store_name='USA')\n\nSt_name_3 = Store(store_name='Germany')\n\nSt_name_4 = Store(store_name='Russia')\n\nSt_name_5 = Store(store_name='Japan')\n\n\nBob = User(\n user_email='bob@gmail.com',\n user_password='777777'\n)\n\nBoba = User(\n user_email='boba@gmail.com',\n user_password='111111'\n)\nBoban = User(\n user_email='boban@gmail.com',\n user_password='222222'\n)\n\nR_Lexus.recommendation_products.append(Lexus)\nR_BMW.recommendation_products.append(BMW)\nR_Audi.recommendation_products.append(Audi)\nR_ZAZ.recommendation_products.append(ZAZ)\nR_Mazda.recommendation_products.append(Mazda)\n\nLexus.products_store_fk.append(St_name_1)\nBMW.products_store_fk.append(St_name_2)\nAudi.products_store_fk.append(St_name_3)\nZAZ.products_store_fk.append(St_name_4)\nMazda.products_store_fk.append(St_name_5)\n\nLexus.products_characteristic_fk.append(Char_1)\nBMW.products_characteristic_fk.append(Char_2)\nAudi.products_characteristic_fk.append(Char_3)\nZAZ.products_characteristic_fk.append(Char_4)\nMazda.products_characteristic_fk.append(Char_5)\n\ndb.session.add_all([Lexus, BMW, Audi, ZAZ, Mazda,\n R_Lexus, R_BMW, R_Audi, R_ZAZ, R_Mazda,\n Char_1, Char_2, Char_3, Char_4, Char_5,\n St_name_1, St_name_2, St_name_3, St_name_4, St_name_5,\n Bob, Boba, Boban\n ])\n\ndb.session.commit()\n\ndef dropSession():\n session['user_email'] = ''\n session['role'] = 'unlogged'\n\ndef newSession(email, pw):\n session['user_email'] = email\n if pw == '777777':\n session['role'] = 'admin'\n else:\n session['role'] = 'user'\n\n@app.route('/')\ndef root():\n if not session['user_email']:\n return redirect('/login')\n return render_template('index.html')\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n form = LoginForm()\n\n if request.method == 'POST':\n if form.validate():\n try:\n res = db.session.query(User).filter(User.user_email == form.user_email.data).one()\n except:\n form.user_email.errors = ['user doesnt exist']\n return render_template('login.html', form=form)\n if res.user_password == form.user_password.data:\n newSession(res.user_email, res.user_password)\n return redirect('/')\n else:\n form.user_password.errors = ['wrong password']\n return render_template('login.html', form=form)\n else:\n return render_template('login.html', form=form)\n else:\n return render_template('login.html', form=form)\n\n\n@app.route('/logout')\ndef logout():\n dropSession()\n return redirect('/login')\n\n\n@app.route('/registration', methods=['GET', 'POST'])\ndef registration():\n form = RegistrationForm()\n if request.method == 'POST':\n if form.validate():\n new_user = User(\n user_email=form.user_email.data,\n user_password=form.user_confirm_password.data\n )\n db.session.add(new_user)\n db.session.commit()\n newSession(new_user.user_email, new_user.user_password)\n return render_template('index.html')\n else:\n return render_template('registration.html', form=form)\n\n return render_template('registration.html', form=form)\n\n\n@app.route('/products', methods=['GET'])\ndef all_products():\n if session['role'] == 'admin':\n result = db.session.query(Products).all()\n return render_template('all_products.html', result=result)\n else:\n return redirect('/')\n\n\n@app.route('/store', methods=['GET'])\ndef all_store():\n if session['role'] == 'admin':\n result = db.session.query(Store).all()\n return render_template('all_store.html', result=result)\n else:\n return redirect('/')\n\n\n@app.route('/recommendation', methods=['GET'])\ndef all_recommendation():\n if session['role'] == 'admin':\n result = db.session.query(Recommendation).all()\n return render_template('all_recommendation.html', result=result)\n else:\n return redirect('/')\n\n\n@app.route('/characteristic', methods=['GET'])\ndef all_characteristic():\n if session['role'] == 'admin':\n result = db.session.query(Characteristic).all()\n return render_template('all_characteristic.html', result=result)\n else:\n return redirect('/')\n\n\n@app.route('/create_product', methods=['POST', 'GET'])\ndef create_product():\n form = ProductsForm()\n\n if request.method == 'POST':\n if form.validate():\n new_product = Products(\n product_id=form.product_id.data,\n product_name=form.product_name.data,\n product_model=form.product_model.data,\n )\n try:\n db.session.add(new_product)\n db.session.commit()\n return redirect('/products')\n except:\n form.product_id.errors = ['this ID already exists']\n return render_template('create_product.html', form=form, form_name=\"New product\",\n action=\"new_product\")\n else:\n if not form.validate():\n return render_template('create_product.html', form=form, form_name=\"New product\",\n action=\"new_product\")\n\n elif request.method == 'GET':\n return render_template('create_product.html', form=form)\n\n\n@app.route('/delete_product/<int:id>', methods=['GET', 'POST'])\ndef delete_product(id):\n result = db.session.query(Products).filter(Products.product_id == id).one()\n\n db.session.delete(result)\n db.session.commit()\n\n return redirect('/products')\n\n\n@app.route('/create_store', methods=['POST', 'GET'])\ndef create_store():\n form = StoreForm()\n\n if request.method == 'POST':\n if form.validate():\n new_store = Store(\n store_name=form.store_name.data,\n )\n try:\n db.session.add(new_store)\n db.session.commit()\n return redirect('/store')\n except:\n form.store_name.errors = ['this name already exists']\n return render_template('create_store.html', form=form, form_name=\"New store\",\n action=\"new_store\")\n else:\n if not form.validate():\n return render_template('create_store.html', form=form, form_name=\"New store\",\n action=\"new_store\")\n elif request.method == 'GET':\n return render_template('create_store.html', form=form)\n\n\n@app.route('/delete_store/<string:name>', methods=['GET', 'POST'])\ndef delete_store(name):\n result = db.session.query(Store).filter(Store.store_name == name).one()\n\n db.session.delete(result)\n db.session.commit()\n\n return redirect('/store')\n\n\n@app.route('/create_recommendation', methods=['POST', 'GET'])\ndef create_recommendation():\n form = RecommendationForm()\n\n if request.method == 'POST':\n if form.validate():\n new_recommendation = Recommendation(\n recommendation_id=form.recommendation_id.data,\n recommendation_name=form.recommendation_name.data,\n recommendation_model=form.recommendation_model.data,\n recommendation_price=form.recommendation_price.data,\n )\n try:\n db.session.add(new_recommendation)\n db.session.commit()\n return redirect('/recommendation')\n except:\n form.recommendation_id.errors = ['this ID already exists']\n return render_template('create_recommendation.html', form=form, form_name=\"New recommendation\",\n action=\"new_recommendation\")\n else:\n if not form.validate():\n return render_template('create_recommendation.html', form=form, form_name=\"New recommendation\",\n action=\"new_recommendation\")\n elif request.method == 'GET':\n return render_template('create_recommendation.html', form=form)\n\n\n@app.route('/delete_recommendation/<string:r_id>', methods=['GET', 'POST'])\ndef delete_recommendation(r_id):\n result = db.session.query(Recommendation).filter(Recommendation.recommendation_id == int(r_id)).one()\n\n db.session.delete(result)\n db.session.commit()\n\n return redirect('/recommendation')\n\n\n@app.route('/create_characteristic', methods=['POST', 'GET'])\ndef create_characteristic():\n form = CharacteristicForm()\n\n if request.method == 'POST':\n if form.validate():\n new_characteristic = Characteristic(\n characteristic_id=form.characteristic_id.data,\n characteristic_price=form.characteristic_price.data,\n characteristic_specification=form.characteristic_specification.data,\n )\n try:\n db.session.add(new_characteristic)\n db.session.commit()\n return redirect('/characteristic')\n except:\n form.characteristic_id.errors = ['this ID already exists']\n return render_template('create_characteristic.html', form=form, form_name=\"New characteristic\",\n action=\"new_characteristic\")\n else:\n if not form.validate():\n return render_template('create_characteristic.html', form=form, form_name=\"New characteristic\",\n action=\"new_characteristic\")\n elif request.method == 'GET':\n return render_template('create_characteristic.html', form=form)\n\n\n\n@app.route('/delete_characteristic/<int:c_id>', methods=['GET', 'POST'])\ndef delete_characteristic(c_id):\n result = db.session.query(Characteristic).filter(Characteristic.characteristic_id == c_id).one()\n\n db.session.delete(result)\n db.session.commit()\n\n return redirect('/characteristic')\n\n\n@app.route('/edit_product/<int:id>', methods=['GET', 'POST'])\ndef edit_product(id):\n form = ProductsFormEdit()\n result = db.session.query(Products).filter(Products.product_id == id).one()\n\n if request.method == 'GET':\n\n form.product_id.data = result.product_id\n form.product_name.data = result.product_name\n form.product_model.data = result.product_model\n\n\n return render_template('edit_product.html', form=form, form_name=id)\n elif request.method == 'POST':\n if form.validate():\n result.product_id = form.product_id.data\n result.product_name = form.product_name.data\n result.product_model = form.product_model.data,\n\n db.session.commit()\n return redirect('/products')\n else:\n return render_template('edit_product.html', form=form, form_name=id)\n\n\n@app.route('/edit_store/<string:name>', methods=['GET', 'POST'])\ndef edit_store(name):\n form = StoreFormEdit()\n result = db.session.query(Store).filter(Store.store_name == name).one()\n\n if request.method == 'GET':\n\n form.store_name.data = result.store_name\n\n\n return render_template('edit_store.html', form=form, form_name=name)\n elif request.method == 'POST':\n if form.validate():\n result.store_name = form.store_name.data\n db.session.commit()\n return redirect('/store')\n else: return render_template('edit_store.html', form=form, form_name=name)\n\n\n@app.route('/edit_recommendation/<int:r_id>', methods=['GET', 'POST'])\ndef edit_recommendation(r_id):\n form = RecommendationFormEdit()\n result = db.session.query(Recommendation).filter(Recommendation.recommendation_id == r_id).one()\n\n if request.method == 'GET':\n\n form.recommendation_id.data = result.recommendation_id\n form.recommendation_price.data = result.recommendation_price\n form.recommendation_name.data = result.recommendation_name\n form.recommendation_model.data = result.recommendation_model\n\n return render_template('edit_recommendation.html', form=form, form_name='Edit Recommendation')\n elif request.method == 'POST':\n if form.validate():\n\n result.recommendation_id = form.recommendation_id.data\n result.recommendation_price = form.recommendation_price.data\n result.recommendation_name = form.recommendation_name.data\n result.recommendation_model = form.recommendation_model.data\n db.session.commit()\n return redirect('/recommendation')\n else:\n return render_template('edit_recommendation.html', form=form, form_name='Edit Recommendation')\n\n\n@app.route('/edit_characteristic/<int:c_id>', methods=['GET', 'POST'])\ndef edit_characteristic(c_id):\n form = CharacteristicFormEdit()\n result = db.session.query(Characteristic).filter(Characteristic.characteristic_id == c_id).one()\n\n if request.method == 'GET':\n\n form.characteristic_id.data = result.characteristic_id\n form.characteristic_specification.data = result.characteristic_specification\n form.characteristic_price.data = result.characteristic_price\n\n return render_template('edit_characteristic.html', form=form, form_name='Edit Characteristic')\n elif request.method == 'POST':\n\n if form.validate():\n result.characteristic_id = form.characteristic_id.data\n result.characteristic_specification = form.characteristic_specification.data\n result.characteristic_price = form.characteristic_price.data,\n\n db.session.commit()\n return redirect('/characteristic')\n else:\n return render_template('edit_characteristic.html', form=form, form_name='Edit Characteristic')\n\n@app.route('/search', methods=['GET', 'POST'])\ndef search():\n form = CreateQuery()\n if request.method == 'POST':\n if not form.validate():\n return render_template('Search.html', form=form, form_name=\"Search\", action=\"search\")\n else:\n list_product.clear()\n for id, name, model in db.session.query(Products.product_id, Products.product_name, Products.product_model):\n if name == form.product_name.data and model == form.product_model.data:\n list_product.append(id)\n\n return redirect(url_for('searchList'))\n\n return render_template('Search.html', form=form, form_name=\"Search\", action=\"search\")\n\n\n@app.route('/search/result')\ndef searchList():\n res = []\n try:\n for i in list_product:\n product_name, product_model, characteristic_price, characteristic_specification = db.session \\\n .query(Products.product_name, Products.product_model, Characteristic.characteristic_price, Characteristic.characteristic_specification) \\\n .join(Products, Characteristic.characteristic_id == Products.product_id) \\\n .filter(Products.product_id == i).one()\n res.append(\n {\"name\": product_name, \"model\": product_model, \"price\": characteristic_price, \"specification\": characteristic_specification})\n except:\n print(\"no data\")\n print(list_product)\n\n return render_template('Search_list.html', name=\"result\", results=res, action=\"/search/result\")\n\n\n@app.route('/claster', methods=['GET', 'POST'])\ndef claster():\n df = pd.DataFrame()\n\n for product_name, characteristic_price in db.session.query(Products.product_name, Characteristic.characteristic_price).join(Characteristic, Products.product_id == Characteristic.characteristic_id):\n print(product_name, characteristic_price)\n df = df.append({\"product_name\": product_name, \"characteristic_price\": characteristic_price}, ignore_index=True)\n\n X = pd.get_dummies(data=df)\n print(X)\n count_clasters = len(df['characteristic_price'].unique())\n # print(count_clasters)\n kmeans = KMeans(n_clusters=count_clasters, random_state=0).fit(X)\n # print(kmeans)\n test_str = [10000, 'ZAZ']\n count_columns = len(X.columns)\n test_list = [0] * count_columns\n test_list[0] = 10000\n test_list[-1] = 1\n # print(test_list)\n # print(kmeans.labels_)\n # print(kmeans.predict(np.array([test_list])))\n\n return render_template('claster.html', row= kmeans.predict(np.array([test_list]))[0], count_claster = count_clasters, test_str=test_str)\n\n\n@app.route('/corelation', methods=['GET', 'POST'])\ndef correlation():\n df = pd.DataFrame()\n for name, count_rec, avg_price in db.session.query(Recommendation.recommendation_name, func.count(Recommendation.recommendation_name), func.avg(Recommendation.recommendation_price)\n ).group_by(Recommendation.recommendation_name):\n print(name, count_rec, avg_price)\n df = df.append({\"count_rec\": float(count_rec), \"avg_price\": float(avg_price)}, ignore_index=True)\n\n scaler = StandardScaler()\n scaler.fit(df[[\"count_rec\"]])\n train_X = scaler.transform(df[[\"count_rec\"]])\n print(train_X,df[[\"avg_price\"]])\n reg = LinearRegression().fit(train_X, df[[\"avg_price\"]])\n\n test_array = [[3]]\n test = scaler.transform(test_array)\n result = reg.predict(test)\n\n query1 = db.session.query(Recommendation.recommendation_name, func.count(Recommendation.recommendation_name), func.avg(Recommendation.recommendation_price)\n ).group_by(Recommendation.recommendation_name).all()\n name, count_pr, count_fl = zip(*query1)\n scatter = go.Scatter(\n x=count_pr,\n y=count_fl,\n mode='markers',\n marker_color='rgba(255, 0, 0, 100)',\n name=\"data\"\n )\n x_line = np.linspace(0, 10)\n y_line = x_line * reg.coef_[0, 0] + reg.intercept_[0]\n line = go.Scatter(\n x=x_line,\n y=y_line,\n mode='lines',\n marker_color='rgba(0, 0, 255, 100)',\n name=\"regretion\"\n )\n data = [scatter, line]\n graphsJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)\n return render_template('corelation.html', row=int(round(result[0, 0])), test_data=test_array[0][0],\n coef=reg.coef_[0],\n coef1=reg.intercept_, graphsJSON=graphsJSON)\n\n@app.route('/clasification', methods=['GET', 'POST'])\ndef clasification():\n df = pd.DataFrame()\n for name, model, price in db.session.query(Products.product_name, Products.product_model, Recommendation.recommendation_price)\\\n .join(Recommendation, Recommendation.recommendation_id == Products.recommendation_id):\n print(name, model, price)\n df = df.append({\"name\": name, \"model\": model, \"price\": float(price)}, ignore_index=True)\n # db.session.close()\n\n mean_p = df['price'].mean()\n df.loc[df['price'] < mean_p, 'quality'] = 0\n df.loc[df['price'] >= mean_p, 'quality'] = 1\n\n X = pd.get_dummies(data=df[['name', 'model']])\n print(df)\n print(X)\n pnn = algorithms.PNN(std=10, verbose=False)\n pnn.train(X, df['quality'])\n test_str = ['BMW', 'X5']\n count_columns = len(X.columns)\n test_list = [0] * count_columns\n test_list[1] = 1\n test_list[-1] = 1\n print(test_list)\n y_predicted = pnn.predict([test_list])\n result = \"Ні\"\n if y_predicted - 1 < 0.0000001:\n result = \"Так\"\n\n return render_template('clasification.html', y_predicted=result, test_data=test_list, test_str = test_str)\n\n@app.route('/dashboard', methods=['GET', 'POST'])\ndef dashboard():\n query1 = (\n db.session.query(\n Products.product_name,\n func.count(Recommendation.recommendation_model).label('recommendation_model')\n ).join(Recommendation, Products.recommendation_id == Recommendation.recommendation_id).\n group_by(Products.product_name)\n ).all()\n\n print(query1)\n\n query2 = (\n db.session.query(\n Products.product_model,\n func.count(Recommendation.recommendation_price).label('recommendation_price')\n ).join(Recommendation, Products.recommendation_id == Recommendation.recommendation_id).\n group_by(Products.product_model)\n ).all()\n\n print(query2)\n\n product_name, recommendation_id = zip(*query1)\n bar = go.Bar(\n x=product_name,\n y=recommendation_id\n )\n\n product_model, recommendation_price = zip(*query2)\n pie = go.Pie(\n labels=product_model,\n values=recommendation_price\n )\n\n data = {\n \"bar\": [bar],\n \"pie\": [pie]\n }\n graphs_json = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)\n\n return render_template('dashboard.html', graphsJSON=graphs_json)\n\n\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":27447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"321267904","text":"# Copyright 1999-2020 Alibaba Group Holding Ltd.\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 logging\n\nimport psutil\n\nfrom ...actors import FunctionActor\nfrom ...config import options\nfrom ...errors import StorageFull, StorageDataExists, SerializationFailed\nfrom ...serialize import dataserializer\nfrom ...utils import lazy_import, calc_size_by_str\n\ntry:\n import pyarrow\n\n try:\n from pyarrow.serialization import SerializationCallbackError\n except ImportError:\n from pyarrow.lib import SerializationCallbackError\nexcept ImportError: # pragma: no cover\n pyarrow = None\n SerializationCallbackError = None\n\nplasma = lazy_import('pyarrow.plasma', globals=globals(), rename='plasma')\n\nlogger = logging.getLogger(__name__)\nPAGE_SIZE = 64 * 1024\n\n\nclass PlasmaErrors:\n def __getattr__(self, item):\n import pyarrow.lib\n\n ret = getattr(plasma, item, None)\n if ret is None: # pragma: no cover\n if item == 'PlasmaObjectNotFound':\n ret = getattr(plasma, 'PlasmaObjectNonexistent', None) \\\n or getattr(pyarrow.lib, 'PlasmaObjectNonexistent')\n elif item == 'PlasmaStoreFull':\n ret = getattr(pyarrow.lib, item)\n\n if ret is not None:\n setattr(self, item, ret)\n return ret\n\n\nplasma_errors = PlasmaErrors()\n\n\nclass PlasmaKeyMapActor(FunctionActor):\n @classmethod\n def default_uid(cls):\n return 'w:0:' + cls.__name__\n\n def __init__(self):\n super().__init__()\n self._mapping = dict()\n\n def put(self, session_id, chunk_key, obj_id):\n session_chunk_key = (session_id, chunk_key)\n if session_chunk_key in self._mapping:\n raise StorageDataExists(session_chunk_key)\n self._mapping[session_chunk_key] = obj_id\n\n def get(self, session_id, chunk_key):\n return self._mapping.get((session_id, chunk_key))\n\n def delete(self, session_id, chunk_key):\n try:\n del self._mapping[(session_id, chunk_key)]\n except KeyError:\n pass\n\n def batch_delete(self, session_id, chunk_keys):\n for k in chunk_keys:\n self.delete(session_id, k)\n\n\nclass PlasmaSharedStore(object):\n \"\"\"\n Wrapper of plasma client for Mars objects\n \"\"\"\n def __init__(self, plasma_client, mapper_ref):\n from ...serialize.dataserializer import mars_serialize_context\n\n self._plasma_client = plasma_client\n self._size_limit = None\n self._serialize_context = mars_serialize_context()\n\n self._mapper_ref = mapper_ref\n self._pool = mapper_ref.ctx.threadpool(1)\n\n self._plasma_dir = options.worker.plasma_dir\n self._plasma_limit = calc_size_by_str(\n options.worker.plasma_limit, psutil.disk_usage(self._plasma_dir).total)\n\n def get_actual_capacity(self, store_limit):\n \"\"\"\n Get actual capacity of plasma store\n :return: actual storage size in bytes\n \"\"\"\n try:\n store_limit = min(store_limit, self._plasma_client.store_capacity())\n except AttributeError: # pragma: no cover\n pass\n\n if self._size_limit is None:\n left_size = store_limit\n alloc_fraction = 1\n while True:\n allocate_size = int(left_size * alloc_fraction / PAGE_SIZE) * PAGE_SIZE\n try:\n obj_id = plasma.ObjectID.from_random()\n buf = [self._plasma_client.create(obj_id, allocate_size)]\n self._plasma_client.seal(obj_id)\n del buf[:]\n break\n except plasma_errors.PlasmaStoreFull:\n alloc_fraction *= 0.99\n finally:\n self._plasma_client.evict(allocate_size)\n self._size_limit = allocate_size\n return self._size_limit\n\n def _new_object_id(self, session_id, data_key):\n \"\"\"\n Calc unique object id for chunks\n \"\"\"\n while True:\n new_id = plasma.ObjectID.from_random()\n if not self._plasma_client.contains(new_id):\n break\n self._mapper_ref.put(session_id, data_key, new_id)\n return new_id\n\n def _get_object_id(self, session_id, data_key):\n obj_id = self._mapper_ref.get(session_id, data_key)\n if obj_id is None:\n raise KeyError((session_id, data_key))\n return obj_id\n\n def _check_plasma_limit(self, size):\n if self._plasma_limit is not None:\n used_size = psutil.disk_usage(self._plasma_dir).used\n if used_size + size > self._plasma_limit:\n raise plasma_errors.PlasmaStoreFull\n\n def create(self, session_id, data_key, size):\n obj_id = self._new_object_id(session_id, data_key)\n try:\n self._check_plasma_limit(size)\n\n self._plasma_client.evict(size)\n buffer = self._plasma_client.create(obj_id, size)\n return buffer\n except plasma_errors.PlasmaStoreFull:\n exc_type = plasma_errors.PlasmaStoreFull\n self._mapper_ref.delete(session_id, data_key)\n logger.warning('Data %s(%d) failed to store to plasma due to StorageFull',\n data_key, size)\n except: # noqa: E722\n self._mapper_ref.delete(session_id, data_key)\n raise\n\n if exc_type is plasma_errors.PlasmaStoreFull:\n raise StorageFull(request_size=size, capacity=self._size_limit, affected_keys=[data_key])\n\n def seal(self, session_id, data_key):\n obj_id = self._get_object_id(session_id, data_key)\n try:\n self._plasma_client.seal(obj_id)\n except plasma_errors.PlasmaObjectNotFound:\n self._mapper_ref.delete(session_id, data_key)\n raise KeyError((session_id, data_key))\n\n def get(self, session_id, data_key):\n \"\"\"\n Get deserialized Mars object from plasma store\n \"\"\"\n obj_id = self._get_object_id(session_id, data_key)\n obj = self._plasma_client.get(obj_id, serialization_context=self._serialize_context, timeout_ms=10)\n if obj is plasma.ObjectNotAvailable:\n self._mapper_ref.delete(session_id, data_key)\n raise KeyError((session_id, data_key))\n return obj\n\n def get_buffer(self, session_id, data_key):\n \"\"\"\n Get raw buffer from plasma store\n \"\"\"\n obj_id = self._get_object_id(session_id, data_key)\n [buf] = self._plasma_client.get_buffers([obj_id], timeout_ms=10)\n if buf is None:\n self._mapper_ref.delete(session_id, data_key)\n raise KeyError((session_id, data_key))\n return buf\n\n def get_actual_size(self, session_id, data_key):\n \"\"\"\n Get actual size of Mars object from plasma store\n \"\"\"\n buf = None\n try:\n obj_id = self._get_object_id(session_id, data_key)\n [buf] = self._plasma_client.get_buffers([obj_id], timeout_ms=10)\n if buf is None:\n self._mapper_ref.delete(session_id, data_key)\n raise KeyError((session_id, data_key))\n return buf.size\n finally:\n del buf\n\n def put(self, session_id, data_key, value):\n \"\"\"\n Put a Mars object into plasma store\n :param session_id: session id\n :param data_key: chunk key\n :param value: Mars object to be put\n \"\"\"\n data_size = None\n\n try:\n obj_id = self._new_object_id(session_id, data_key)\n except StorageDataExists:\n obj_id = self._get_object_id(session_id, data_key)\n if self._plasma_client.contains(obj_id):\n logger.debug('Data %s already exists, returning existing', data_key)\n [buffer] = self._plasma_client.get_buffers([obj_id], timeout_ms=10)\n del value\n return buffer\n else:\n logger.warning('Data %s registered but no data found, reconstructed', data_key)\n self._mapper_ref.delete(session_id, data_key)\n obj_id = self._new_object_id(session_id, data_key)\n\n try:\n try:\n serialized = dataserializer.serialize(value)\n except SerializationCallbackError:\n self._mapper_ref.delete(session_id, data_key)\n raise SerializationFailed(obj=value) from None\n\n del value\n\n data_size = serialized.total_bytes\n self._check_plasma_limit(data_size)\n\n try:\n buffer = self._plasma_client.create(obj_id, serialized.total_bytes)\n stream = pyarrow.FixedSizeBufferWriter(buffer)\n stream.set_memcopy_threads(6)\n self._pool.submit(serialized.write_to, stream).result()\n self._plasma_client.seal(obj_id)\n finally:\n del serialized\n return buffer\n except plasma_errors.PlasmaStoreFull:\n self._mapper_ref.delete(session_id, data_key)\n logger.warning('Data %s(%d) failed to store to plasma due to StorageFull',\n data_key, data_size)\n exc = plasma_errors.PlasmaStoreFull\n except: # noqa: E722\n self._mapper_ref.delete(session_id, data_key)\n raise\n\n if exc is plasma_errors.PlasmaStoreFull:\n raise StorageFull(request_size=data_size, capacity=self._size_limit,\n affected_keys=[data_key])\n\n def contains(self, session_id, data_key):\n \"\"\"\n Check if given chunk key exists in current plasma store\n \"\"\"\n try:\n obj_id = self._get_object_id(session_id, data_key)\n if self._plasma_client.contains(obj_id):\n return True\n else:\n self._mapper_ref.delete(session_id, data_key)\n return False\n except KeyError:\n return False\n\n def delete(self, session_id, data_key):\n self._mapper_ref.delete(session_id, data_key)\n\n def batch_delete(self, session_id, data_keys):\n self._mapper_ref.batch_delete(session_id, data_keys)\n","sub_path":"mars/worker/storage/sharedstore.py","file_name":"sharedstore.py","file_ext":"py","file_size_in_byte":10742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"133249329","text":"import daemon\nimport sys\nimport os\nimport signal\n\ndef shutdown(signum, frame): # signum and frame are mandatory\n sys.exit(0)\n\nwith daemon.DaemonContext(\n chroot_directory=None,\n working_directory='/home/miband2server/tfm-pypimi',\n pidfile=lockfile.FileLock('/var/run/mb2d.pid'),\n signal_map={\n signal.SIGTERM: shutdown,\n signal.SIGTSTP: shutdown\n }):\n print(os.getcwd())\n","sub_path":"helpers/daemon-test.py","file_name":"daemon-test.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"131383775","text":"import os\nimport time\nimport random\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n# import scipy.ndimage\n# from sklearn.metrics import f1_score\n# import pydicom as dicom\n# import nrrd\n\nimport torch\nimport torch.nn as nn\n# import torch.nn.functional as F\n# import torchvision.datasets as dsets\n# import torchvision.transforms as transforms\n# from torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom torch.optim import Adam, lr_scheduler\n# from torchsummary import summary\n\nfrom utils.shlynur_print_time import print_time\nfrom utils.shlynur_create_brats_data import load_brats_data_3d\nfrom utils.shlynur_load_prostate_data import load_prostate_images_and_labels_3d\nfrom utils.shlynur_class_dice import class_dice_3d_prostate\nfrom utils.older_utils_functions import class_dice_2d\nfrom utils.shlynur_get_dataset import GetProstateDataset, GetBratsDataset\nfrom utils.shlynur_unet_models import UNet3D, Reversible3D\n# from utils.shlynur_loss_functions import cross_entropy3d # , brats_dice_loss, brats_dice_loss_original_4\nfrom utils.shlynur_convergence_check import convergence_check_auto_cnn, prediction_converter, \\\n identify_incorrect_pixels, mask_creator, accuracy_check_auto_inter_cnn\nfrom utils.shlynur_save_load_checkpoint import save_checkpoint, load_checkpoint\n\nimport warnings\nwarnings.filterwarnings('ignore', '.*output shape of zoom.*')\n\n# This program changes the starting epoch for the models. Needed to update the starting epoch if the model does not\n# finish training before the queue submission ends.\n# Set first the hyper-parameters of the model (lines 52-71).\n# Then specify older starting epochs, the model name and its location (lines 91-97).\n\nseed = 48\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nrandom.seed(seed)\ntorch.manual_seed(seed)\nnp.random.seed(seed)\n\n# # # # # # # # # # # # # # # #\n# Change these parameters!!!! #\n# # # # # # # # # # # # # # # #\nbool_prostate_data = True\n# model_type = 'gustav'\nnum_filters_auto_cnn = 32\nnum_filters_inter_cnn = 32\nnum_epochs_auto_cnn = 500\nnum_epochs_inter_cnn = 50\nbatch_size = 1\nlearning_rate = 3e-4\nbool_binary_testing = False\nbool_loss_summation = False\nif bool_binary_testing:\n num_classes = 2\nelse:\n num_classes = 3 if bool_prostate_data else 5\nchannels_auto = 1 if bool_prostate_data else 4\nchannels_inter = channels_auto + num_classes + 1\nif bool_loss_summation:\n channels_inter += 2\npadding = (1, 1, 1) if bool_prostate_data else (0, 0, 0)\nmax_pooling_d = 1 if bool_prostate_data else 2\n\n# Create the default models.\ncnn_auto = UNet3D(bool_prostate_data=bool_prostate_data, in_channels=channels_auto,\n number_of_classes=num_classes, number_of_filters=num_filters_auto_cnn,\n kernel_size=(3, 3, 3), padding=padding, max_pooling_d=max_pooling_d).cuda()\ncnn_inter = UNet3D(bool_prostate_data=bool_prostate_data, in_channels=channels_inter,\n number_of_classes=num_classes, number_of_filters=num_filters_inter_cnn,\n kernel_size=(3, 3, 3), padding=padding, max_pooling_d=max_pooling_d).cuda()\n\n# Create the default optimizers and learning rate schedulers.\noptimizer_auto = Adam(params=cnn_auto.parameters(), lr=learning_rate)\nscheduler_auto = lr_scheduler.ReduceLROnPlateau(optimizer=optimizer_auto, mode='min', factor=0.99,\n patience=100, verbose=True)\noptimizer_inter = Adam(params=cnn_inter.parameters(), lr=learning_rate)\nscheduler_inter = lr_scheduler.ReduceLROnPlateau(optimizer=optimizer_inter, mode='min', factor=0.99,\n patience=10, verbose=True)\n\n# Set the current (older) epoch numbers for each model.\ncurrent_epochs = (48, 48, 48, 48)\nmodel_path_name = 'inter_cnn_3D_model_gustav_epochs_50_filters_32_lr_0.0003_dataug_True.pt'\noperating_system = 'linux'\nif operating_system == 'linux':\n base_path = '/scratch_net/giggo/shlynur/msc/polybox/M.Sc.2019/code/shlynur_unet_testing/3d_results/'\nelse:\n base_path = r'D:\\ETH_Projects\\polybox\\M.Sc.2019\\code\\shlynur_unet_testing\\3d_results'\n\n# if False, will only load and display the current starting epoch.\n# If True, will load and update the starting epoch parameter of the .pt file.\nupdate_model = False\n\nfor i in range(1, len(current_epochs) + 1):\n model_path = os.path.join(\n base_path, 'prostate_split_{}_iterations_10_20_mode_3d_num_scribbles_10'.format(i), 'models')\n os.chdir(path=model_path)\n print(\"GUSTAV'S SPLIT #{} at {}\".format(i, model_path))\n current_epoch = current_epochs[i-1] - 1\n\n cnn_inter, optimizer_inter, scheduler_inter, starting_epoch_inter_cnn, inter_class_scores = load_checkpoint(\n model=cnn_inter, optimizer=optimizer_inter, scheduler=scheduler_inter, file_folder=model_path,\n filename=model_path_name)\n\n print(\"Starting epoch: {}\".format(starting_epoch_inter_cnn))\n print(\"Current scores: {}\".format(inter_class_scores))\n print(\"Current epoch: {}\".format(current_epoch))\n\n if update_model:\n save_checkpoint(model=cnn_inter, optimizer=optimizer_inter, scheduler=scheduler_inter, epoch=current_epoch,\n val_score=inter_class_scores, model_name=os.path.join(model_path, model_path_name))\n\n cnn_inter, optimizer_inter, scheduler_inter, starting_epoch_inter_cnn, inter_class_scores = load_checkpoint(\n model=cnn_inter, optimizer=optimizer_inter, scheduler=scheduler_inter, file_folder=model_path,\n filename=model_path_name)\n\n print(\"Still Starting epoch: {}\".format(starting_epoch_inter_cnn))\n print(\"Still Current scores: {}\".format(inter_class_scores))\n print(\"New Current epoch: {}\".format(current_epoch))\n","sub_path":"change_single_model.py","file_name":"change_single_model.py","file_ext":"py","file_size_in_byte":5755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"650803068","text":"class Solution(object):\n def rotate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: None Do not return anything, modify nums in-place instead.\n \"\"\"\n # Don't even bother with negs.\n if nums < 0:\n return\n\n # I think this op is O(n)\n temp = list(nums)\n\n # This op is O(N) as well\n for i in range(0, len(nums)):\n nums[(i + k) % len(temp)] = temp[i]\n\nt1 = [1,2,3,4,5,6,7]\nk1 = 3\ns = Solution()\ns.rotate(t1,k1)\nprint(t1)","sub_path":"python/189-rotate-array/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"30405376","text":"from conway import *\n\n#Paul Callahan found, in November 1997, two 10-cell patterns with infinite growth\n# Infinite growth\n# http://www.argentum.freeserve.co.uk/lex_i.htm\n\noffset = 30\n\nstate = \"\"\"\n..............\n.......O.OOO..\n.......O....O.\n.......O.O.O..\n........O..O..\n..............\n\"\"\"\n\nif __name__ == \"__main__\":\n# play_and_render(state, SCALES['CMAJOR'], cycles = 200, offset = offset)\n play_state(state, SCALES['CMAJOR'], cycles = 200, offset = offset)\n pygame.midi.quit()\n","sub_path":"bunnies.py","file_name":"bunnies.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"351262091","text":"# Importing scraping packages:\r\nimport bs4\r\nimport requests\r\n# Importing data managment packages:\r\nimport pandas as pd\r\nimport datetime\r\n\r\n'''\r\nScript contains a set of objects meant to represent the RE listings data scraped\r\nfrom various public websites.\r\n\r\nThe main function of these objects will be as a means of integerating the scraped\r\ndata into the listings database via database connection objects and methods.\r\n'''\r\n\r\nclass Kijiji(object):\r\n \"\"\"\r\n This object is mean to represent the data scraped from the canadian listings\r\n website Kijiji.ca.\r\n\r\n The object will contain various methods for selecting\r\n specific instances of data scraped from the site however the objects focus\r\n will be on itterating through the listings website's various pages and\r\n extracting all listings data into a large dataframe given a Kijiji url as a\r\n starting point.\r\n\r\n Parameters\r\n ----------\r\n init_url : str\r\n This url will serve as the starting point for the web scraping methods in\r\n this object. Using this url as a starting point it will itterate through\r\n the number of pages specificed by the page variable, constructing a\r\n large dataframe of individual listings\r\n\r\n page : int\r\n An integer that specifies the number of pages the web scraping methods\r\n will itterate through in constructing the main dataframe.\r\n\r\n \"\"\"\r\n\r\n def __init__(self, init_url, page):\r\n\r\n # Declaring instance variables:\r\n self.inital_url = init_url\r\n self.page = page\r\n\r\n # Instance of main listings dataframe:\r\n self.data = self.build_main_dataframe()\r\n\r\n def build_main_dataframe(self):\r\n '''This main method of the Kijiji object uses several other Kijiji object\r\n methods to construct the main dataframe of listings scraped from\r\n the inital Kijiji.ca url.\r\n\r\n Returns\r\n -------\r\n main_listings_dataframe : pandas dataframe\r\n The main dataframe that contains all the listings data scraped\r\n from Kijiji.ca\r\n '''\r\n\r\n # Creating main_listings_dataframe according to schema:\r\n main_listings_dataframe = pd.DataFrame(columns=['Address', 'Price', 'Date',\r\n 'Bedrooms', 'Bathrooms', 'Size'])\r\n\r\n # Internally deffining url:\r\n url = self.inital_url\r\n\r\n # Itteration that loops through the number of listings pages specificed\r\n # by the page number, starting at the inital url and constructing the\r\n # main dataframe:\r\n for page_numer in range(self.page):\r\n\r\n # converting the page specified by url to a dataframe:\r\n page_dataframe = Kijiji.page_to_dataframe(url)\r\n\r\n # Appending current page_dataframe to main_dataframe:\r\n main_listings_dataframe = main_listings_dataframe.append(page_dataframe)\r\n\r\n # re-deffining url variable to the url to the next listings page:\r\n url = Kijiji.get_next_url(url)\r\n\r\n\r\n return main_listings_dataframe\r\n\r\n\r\n def page_to_dataframe(url):\r\n '''This method parses a Kijiji.ca RE listings page and converts all\r\n listings shown on the page to a pandas dataframe\r\n\r\n Parameters\r\n ----------\r\n url : str\r\n This is the Kijiji.ca listings url that will be parsed and converted\r\n to a dataframe.\r\n\r\n Returns\r\n -------\r\n page_dataframe : pandas dataframe\r\n The dataframe containing all the RE listings found on the Kijiji.ca\r\n page\r\n\r\n '''\r\n\r\n # Acessing webpage and parsing the html:\r\n res = requests.get(url)\r\n soup = bs4.BeautifulSoup(res.text, 'lxml')\r\n\r\n # Creating a dataframe that will store all listings data for the page:\r\n page_dataframe = pd.DataFrame(columns=['Address', 'Price', 'Date',\r\n 'Bedrooms', 'Bathrooms', 'Size'])\r\n\r\n\r\n # extracting list of listings div tags: <div class = 'search-item regular-ad'>\r\n listings = soup.findAll('div', {'class': 'search-item regular-ad'})\r\n\r\n\r\n # itteration that converts ever listings to a series and constructs dataframe:\r\n for listing in listings:\r\n\r\n # parse each individual listing for the listing's href and date:\r\n # <a class = 'title'>\r\n listing_href = listing.findAll('a',{'class': 'title'})[0]['href']\r\n # building url to main listings page:\r\n listing_url = 'https://www.kijiji.ca' + listing_href\r\n\r\n\r\n # parsing for listings date <div class = 'location'>\r\n listings_date = listing.findAll('div', {'class': 'location'})[0].span.text\r\n # date string formatting:\r\n listings_date = listings_date.replace('<', '').replace(' ', '')\r\n # Converting listings date to a datetime object:\r\n try:\r\n Date = datetime.datetime.strptime(listings_date, '%d/%m/%Y')\r\n except:\r\n Date = datetime.datetime.now().date()\r\n\r\n\r\n # Extracting the data from the listings url:\r\n listings_data = Kijiji.href_parser(listing_url)\r\n\r\n # Overwriting 'NaN' date value with extracted listings_date value:\r\n listings_data['Date'] = Date\r\n\r\n\r\n # Constructing page_dataframe with each listing found on the page:\r\n page_dataframe = page_dataframe.append(listings_data, ignore_index=True)\r\n\r\n\r\n return page_dataframe\r\n\r\n def href_parser(href):\r\n '''This method takes the href link found on a Kijiji.ca main listings\r\n page and parses the webpage for an individual listing to extract and\r\n return a pandas series containing the basic data of each listings.\r\n\r\n Parameters\r\n ----------\r\n href : str\r\n This is the href link that links to an individual listings main\r\n webpage\r\n\r\n Returns\r\n -------\r\n listing : pandas series\r\n This is a series that contains the listings data for an individual\r\n listing\r\n '''\r\n # Accessing and parsing the webpage:\r\n res = requests.get(href)\r\n soup = bs4.BeautifulSoup(res.text, 'lxml')\r\n\r\n # Parsing the html for the listigns data:\r\n\r\n # Address: <span itemprop = 'address'>\r\n Address = soup.findAll('span', {'itemprop': 'address'})[0].text\r\n\r\n\r\n # Price: <span class = 'currentPrice-2842943473'>\r\n Price = soup.findAll('span', {'class':\r\n 'currentPrice-2842943473'})[0].text\r\n\r\n # Converting price string to appropriate format:\r\n Price = Price.replace('$', '').replace(',', '')\r\n\r\n\r\n # Number of Beds, Bathrooms and Square Feet:\r\n attribute_tags = soup.findAll('dt', {'class': 'attributeLabel-240934283'})\r\n attribute_values = soup.findAll('dd', {'class': 'attributeValue-2574930263'})\r\n\r\n # Creating a dictionary that will store the various attributes independent\r\n # of there listing order on the website:\r\n attributes_dict = {}\r\n\r\n # Itterative loop appending attribute data to attributes_dict:\r\n counter = 0 # Counter to track attribute_values in loop\r\n for attribute in attribute_tags:\r\n\r\n attribute_instance = {attribute.text : attribute_values[counter].text}\r\n\r\n counter = counter + 1\r\n\r\n # adding values to main dict:\r\n attributes_dict.update(attribute_instance)\r\n\r\n\r\n # Extracting attributes from built attributes dict:\r\n try:\r\n Bedrooms = attributes_dict['Bedrooms']\r\n except:\r\n Bedrooms = 'NULL'\r\n\r\n try:\r\n Bathrooms = attributes_dict['Bathrooms']\r\n except:\r\n Bathrooms = 'NULL'\r\n\r\n try:\r\n Size = attributes_dict['Size (sqft)'].replace(',', '')\r\n except:\r\n Size = 'NULL'\r\n\r\n # Declaring date_posed as a dummy variable to be overwritten later in the\r\n # data model:\r\n Date = 'NaN'\r\n\r\n\r\n # Creating series:\r\n listing = pd.Series([Address, Price, Date, Bedrooms, Bathrooms, Size],\r\n index = ['Address', 'Price', 'Date', 'Bedrooms', 'Bathrooms', 'Size'])\r\n\r\n return listing\r\n\r\n def get_next_url(url):\r\n '''This method parses a Kijiji.ca RE listings page and extracts and\r\n returns the url to the next Kijiji listings page\r\n\r\n Parameters\r\n ----------\r\n url : str\r\n This is the Kijiji.ca url that will be paresed and the 'next url'\r\n extracted\r\n\r\n Returns\r\n -------\r\n next_url : str\r\n This is the url to the next Kijiji.ca RE listings page\r\n '''\r\n\r\n # Accessing webpage and parsing html:\r\n res = requests.get(url)\r\n soup = bs4.BeautifulSoup(res.text, 'lxml')\r\n\r\n # Extracting the next url from the html: <a title = 'Next'>\r\n next_href = soup.findAll('a', {'title': 'Next'})[0]['href']\r\n\r\n # Building full url from href link:\r\n next_url = 'https://www.kijiji.ca' + next_href\r\n\r\n return next_url\r\n","sub_path":"Online Real Estate Data Models/Kijiji_Listings_Data_Model.py","file_name":"Kijiji_Listings_Data_Model.py","file_ext":"py","file_size_in_byte":9116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"290771286","text":"from testing import *\nfrom testing.tests import *\nfrom testing.assertions import *\nfrom testing.util import *\n\n\nwith cumulative(skip_after_fail=True):\n always_true = named_lambda('always_true', lambda x: True)\n always_false = named_lambda('always_false', lambda x: False)\n is_odd = named_lambda('is_odd', lambda x: x % 2 != 0)\n is_int = named_lambda('is_int', lambda x: type(x) == int)\n\n get_type = named_lambda('get_type', lambda x: type(x).__name__)\n \n\n\n with tested_function_name('count'), all_or_nothing():\n count = reftest()\n\n count([], always_true)\n count([1], always_true)\n count([1, 2, 3], always_true)\n count([], always_false)\n count([1], always_false)\n count([1, 2, 3], always_false)\n count([1, 2, 3], is_odd)\n count([1, 2, 3, 4, 5], is_odd)\n count([1, 2, 3, 4, 5], is_int)\n count(['x', 1, '4', 2], is_int)\n\n with tested_function_name('find_first'), all_or_nothing():\n find_first = reftest()\n\n find_first([], always_true, 1)\n find_first([], always_true, None)\n find_first([], always_true, 'default')\n find_first([1], always_true, 1)\n find_first([1, 2], always_true, 1)\n find_first([1, 2, 3], always_true, 1)\n find_first([1], always_false, 7)\n find_first([1, 2], always_false, 4)\n find_first([1, 2, 3], always_false, 99)\n\n with tested_function_name('group_by_key'), all_or_nothing():\n group_by_key = reftest()\n\n group_by_key([], get_type)\n group_by_key([1], get_type)\n group_by_key([1, 2], get_type)\n group_by_key(['x'], get_type)\n group_by_key([1, 'x'], get_type)\n group_by_key([1, 'x', [1,2], {1,2}], get_type)\n group_by_key([1, 2, 3, 4, 5], is_odd)\n\n with tested_function_name('filter'), all_or_nothing():\n filter = reftest()\n\n filter([], always_true)\n filter([1], always_true)\n filter([1, 2], always_true)\n filter([1, 2, 3], always_true)\n filter([], always_false)\n filter([1], always_false)\n filter([1, 2], always_false)\n filter([1, 2, 3], always_false)\n filter([1, 2, 3, 4, 5], is_odd)\n filter([1, 'x', {4}, 9], is_int)\n\n with tested_function_name('all'), all_or_nothing():\n all = reftest()\n\n all([], always_true)\n all([1], always_true)\n all([1, 2], always_true)\n all([1, 2, 3], always_true)\n all([], always_false)\n all([1], always_false)\n all([1, 2], always_false)\n all([1, 2, 3], always_false)\n all([1, 2, 3, 4, 5], is_odd)\n all([1, 3, 5], is_odd)\n all([1, 'x', {4}, 9], is_int)\n all([1, 4, 9], is_int)\n\n with tested_function_name('any'), all_or_nothing():\n any = reftest()\n\n any([], always_true)\n any([1], always_true)\n any([1, 2], always_true)\n any([1, 2, 3], always_true)\n any([], always_false)\n any([1], always_false)\n any([1, 2], always_false)\n any([1, 2, 3], always_false)\n any([1, 2, 3, 4, 5], is_odd)\n any([1, 3, 5], is_odd)\n any([2, 4, 6], is_odd)\n any([1, 'x', {4}, 9], is_int)\n any(['x', {4}, '9'], is_int)\n any([1, 4, 9], is_int)\n \n with tested_function_name('memoize'), all_or_nothing():\n @test('memoize returns values of wrapped function')\n def _():\n def wrappee(x):\n return x\n\n wrapped = tested_function(wrappee)\n\n for x in range(1, 10):\n must_be_equal(wrappee(x), wrapped(x))\n \n @test('memoize calls function only once per input')\n def _():\n x = 0\n\n def wrappee(a):\n nonlocal x\n x += 1\n return x\n\n wrapped = tested_function(wrappee)\n\n must_be_equal(0, x)\n must_be_equal(1, wrapped(1))\n must_be_equal(1, x)\n must_be_equal(1, wrapped(1))\n must_be_equal(1, x)\n must_be_equal(2, wrapped(5))\n must_be_equal(2, x)\n must_be_equal(2, wrapped(5))\n must_be_equal(2, x)\n must_be_equal(1, wrapped(1))\n must_be_equal(3, wrapped(2))\n\n\n with tested_function_name('create_change_detector'), all_or_nothing():\n @test('create_change_detector does as advertized')\n def _():\n f = tested_function()\n\n must_be_truthy(f(0))\n must_be_falsey(f(0))\n must_be_truthy(f(1))\n must_be_falsey(f(1))\n must_be_truthy(f(0))\n must_be_truthy(f(1))\n","sub_path":"exercises/lambdas/higher-order-functions/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"26340088","text":"\"\"\"\n* @author: Divyesh Patel\n* @email: pateldivyesh009@gmail.com \n* @date: 25/05/20\n* @decription: Write a Python program to read a file line by line and store it into a list.\n\"\"\"\n\nalist = list()\n\nwith open('data.txt') as fhandle:\n for each in fhandle:\n alist.append(each.strip())\n\nprint(alist)\n","sub_path":"dp_w3resource_solutions/file-io/5_read_file_line_by_line_and_store_in_list.py","file_name":"5_read_file_line_by_line_and_store_in_list.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"632740065","text":"import base64, pickle\nfrom django_redis import get_redis_connection\n\n\ndef merge_cart_cookie_to_redis(request, user, response):\n \"\"\"登录时合并购物车\"\"\"\n # 获取cookie购物车数据\n cart_str = request.COOKIES.get('carts')\n # 判断是否有cookie购物车数据,如果没有直接return\n if cart_str is None:\n return\n cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))\n \"\"\"\n {\n 1: {'count': 1, 'selected': True}\n }\n \"\"\"\n # 创建redis连接对象\n redis_conn = get_redis_connection('carts')\n pl = redis_conn.pipeline()\n # 遍历cookie大字典\n for sku_id, sku_dict in cart_dict.items():\n # {sku_id: count}\n # 将cookie中的sku_id count 向redis的hash去存\n pl.hset('cart_%s' % user.id, sku_id, sku_dict['count'])\n # 如果当前cookie中的商品是勾选就把勾选商品sku_id向set集合添加\n if sku_dict['selected']:\n pl.sadd('selected_%s' % user.id, sku_id)\n else:\n # 如果没有勾选就从redis中移除\n pl.srem('selected_%s' % user.id, sku_id)\n pl.execute()\n\n # 清空cookie购物车数据\n response.delete_cookie('carts')\n # return response","sub_path":"meiduo_mall/meiduo_mall/apps/carts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"168497740","text":"# - This class defines selenium helper methods\n\nfrom selenium.webdriver.firefox import webdriver\nfrom selenium.webdriver.remote.webelement import WebElement\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.common.exceptions import StaleElementReferenceException\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as ec\n\nimport time\nimport logging\nfrom elticket import helper_config\n\n\n# Required for Chrome only:\n# Checks if a field element is in focus in order to send input text to the\n# correct field\ndef retry_element_is_focused(driver: webdriver.WebDriver, element):\n i = 0\n config = helper_config.get_config()\n wait_until_confirm_selection = config.getfloat(config.sections()[1],\n 'wait_until_confirm_selection')\n\n while not element == driver.switch_to.active_element:\n element.click()\n time.sleep(wait_until_confirm_selection + i)\n i += 0.1\n\n\ndef fill_in_element(driver: webdriver.WebDriver, by: By, locator, content,\n confirm=False):\n config = helper_config.get_config()\n wait_until_confirm_selection = config.getfloat(config.sections()[1],\n 'wait_until_confirm_selection')\n\n # from selenium.webdriver.support.wait import WebDriverWait\n try:\n if retry_element_is_visible(driver, by, locator):\n WebDriverWait(driver, 10).until(\n ec.element_to_be_clickable((by, locator)))\n element = driver.find_element_by_id(locator)\n if retry_element_can_be_filled(driver, By.ID, locator, content):\n if confirm:\n time.sleep(wait_until_confirm_selection)\n element.send_keys(Keys.RETURN)\n logging.info(\"Entered information in %s\" % str(locator))\n\n except NoSuchElementException:\n logging.error(\"Cannot find the element %s\" % str(locator))\n except StaleElementReferenceException:\n logging.error(\"Element %s is not available\" % str(locator))\n\n\ndef retry_element_is_visible(driver: webdriver.WebDriver, by: By, locator):\n result = False\n attempts = 1\n try:\n while attempts < 3 and result is False:\n element = WebDriverWait(driver, 20).until(\n ec.presence_of_element_located((by, locator)))\n if element is not False:\n result = True\n attempts += 1\n except NoSuchElementException and NoSuchElementException:\n pass\n return result\n\n\ndef retry_element_can_be_filled(driver: webdriver.WebDriver, by: By, locator,\n content):\n \"\"\"\n :param driver: Driver for the browser\n :type driver: webdriver\n :param by: Locator type for the element\n :type by: selenium.webdriver.common.by.By\n :param locator: Element value for the locator type\n :type locator: str\n :param content: Content to write into the element\n :type content: str\n :return: Return the outcome of the action\n :rtype: bool\n \"\"\"\n result = False\n attempts = 1\n while attempts < 3 and result is False:\n try:\n element = driver.find_element(by, locator)\n # element.click()\n element.send_keys(Keys.DELETE)\n element.send_keys(content)\n # element.clear()\n result = True\n except StaleElementReferenceException:\n pass\n time.sleep(0.5)\n attempts += 1\n return result\n\n\ndef retry_find_and_click(element: WebElement):\n result = False\n attempts = 1\n while attempts < 3 and result is False:\n try:\n element.click()\n result = True\n except StaleElementReferenceException:\n pass\n attempts += 1\n time.sleep(0.5)\n return result\n\n\ndef switch_to_iframe(driver: webdriver.WebDriver, iframe_id) -> None:\n retry_element_is_visible(driver, By.ID, iframe_id)\n\n try:\n driver.switch_to.frame(driver.find_element_by_id(iframe_id))\n except NoSuchElementException:\n logging.error(\"Cannot find the specified iFrame\")\n finally:\n return None\n\n\ndef exit_iframe(driver: webdriver.WebDriver):\n driver.switch_to.default_content()\n\n\ndef wait_until_firefox_is_closed(driver: webdriver.WebDriver) -> None:\n browser_is_open = True\n while browser_is_open:\n try:\n driver.get_window_size()\n time.sleep(1)\n except WebDriverException:\n browser_is_open = False\n\n\nclass PageIsFullyLoaded(object):\n def __init__(self):\n pass\n\n def __call__(self, driver):\n try:\n status = driver.execute_script(\"return document.readyState\")\n return status == \"complete\"\n except WebDriverException as e:\n raise e\n\n\ndef retry_current_page_is_fully_loaded(driver: webdriver.WebDriver) -> None:\n WebDriverWait(driver, 20).until(PageIsFullyLoaded())\n\n\n\n\n","sub_path":"elticket/helper_selenium.py","file_name":"helper_selenium.py","file_ext":"py","file_size_in_byte":5162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"353387635","text":"from flask import Flask, session, escape, redirect, url_for, json, jsonify, render_template, request\n\nfrom db.AdminExperience import AdminExperience\nfrom db.AdminUser import AdminUser\nfrom db.AdminMachineLearning import AdminMachineLearning\nfrom logica.Rating import Rating\nfrom logica.Review import Review\nfrom logica.User import User\nfrom logica.Recomendation import Recomendation\n\napp = Flask(__name__, template_folder='../front_end', static_folder='../front_end') #nuevo objeto\n\n# Set the secret key to some random bytes. Keep this really secret!\napp.secret_key = 'the_wheel_of_time'\n\ndef login_user(username):\n session['username'] = username\n return redirect(url_for(\"index\"))\n\n@app.route('/', methods=['GET'])\ndef landing():\n if 'username' in session.keys():\n username = session['username']\n adminUser = AdminUser()\n hasReviews = adminUser.getByUsername(username).hasReviews() \n return render_template(\"landing.html\", hasReviews = hasReviews, username=username)\n return render_template(\"landing.html\")\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n error = None\n if request.method == 'POST':\n username = request.form.getlist('user')[0]\n password = request.form.getlist('password')[0]\n adminUser = AdminUser()\n user = adminUser.getByUsername(username)\n if type(user) == User:\n user = adminUser.getByUsernameAndPassword(username, password)\n if type(user) == User:\n return login_user(username)\n else:\n error = \"¡Has introducido una contraseña incorrecta!\"\n else:\n error = \"¡Este nombre de usuario no existe!\"\n # the code below is executed if the request method\n # was GET or the credentials were invalid\n if 'username' in session.keys():\n return redirect(url_for(\"review\")) \n return render_template('login.html', error=error)\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n error = None\n if request.method == 'POST':\n username = request.form.getlist('user')[0]\n password = request.form.getlist('password')[0]\n adminUser = AdminUser()\n user = adminUser.getByUsername(username)\n if type(user) != User:\n user = User(username, password)\n adminUser.addUser(user)\n return login_user(username)\n else:\n error = \"¡Este nombre de usuario ya existe!\"\n # the code below is executed if the request method\n # was GET or the credentials were invalid\n if 'username' in session.keys():\n return redirect(url_for(\"review\")) \n return render_template('register.html', error = error)\n\n@app.route('/index')\ndef index():\n if 'username' not in session.keys():\n return redirect(url_for(\"login\"))\n username = session[\"username\"]\n \n adminUser = AdminUser()\n hasReviews = adminUser.getByUsername(username).hasReviews()\n if hasReviews:\n return redirect(url_for(\"recomendate\"))\n else:\n return redirect(url_for(\"review\"))\n\n@app.route('/logout')\ndef logout():\n # Elimina el username de session si está ahí\n message = \"Has cerrado la sesión correctamente.\"\n session.pop('username', None)\n return render_template('landing.html', message = message)\n\n@app.route(\"/review\", methods=[\"GET\", \"POST\"])\ndef review():\n if 'username' not in session.keys():\n return render_template('landing.html')\n adminExperience = AdminExperience()\n username = session[\"username\"]\n adminUser = AdminUser()\n if request.method == 'POST': \n experience_name = request.form.getlist('experience')[0]\n rating_value = float(request.form.getlist('rating')[0])\n experience = adminExperience.getByName(experience_name)\n rating = Rating(rating_value)\n if experience == None:\n return 420\n # if rating_value > Rating.getMax() or rating_value < Rating.getMin():\n # return 421\n\n user = adminUser.getByUsername(username)\n review = Review(experience, rating)\n user.addReview(review)\n\n adminUser.updateUser(user)\n\n adminExperience.closeConnection()\n adminUser.closeConnection()\n\n # Redirigimos a recomendar\n return redirect(url_for(\"recomendate\"))\n else:\n experiences = []\n types = []\n hasReviews = adminUser.getByUsername(username).hasReviews()\n for experience in adminExperience.getAll():\n experiences.append(experience.toJSON())\n type = experience.getType()\n if type not in types:\n types.append(type)\n return render_template('review.html', hasReviews=hasReviews, username=username, experiences = experiences, types = types)\n\n@app.route(\"/recomendate\", methods=[\"GET\"])\ndef recomendate():\n if 'username' not in session.keys():\n return render_template('landing.html')\n\n username = session[\"username\"]\n adminUser = AdminUser()\n user = adminUser.getByUsername(username)\n\n #adminML = AdminMachineLearning()\n #correlations = adminML.getMachineLearning()\n\n #correlations.recomendate(user)\n recomendations = []\n\n if user.hasReviews():\n for recomendation in user.getRecomendations():\n recomendations.append(recomendation.toJSON())\n \n\n #adminML.closeConnection()\n adminUser.closeConnection()\n\n return render_template('recomendacion.html', recomendations = recomendations, username=username)\n else:\n return render_template('landing.html')\n\n@app.route(\"/quienessomos\", methods=[\"GET\"])\ndef quienessomos():\n if 'username' not in session.keys():\n return render_template('landing.html')\n\n username = session[\"username\"]\n adminUser = AdminUser()\n user = adminUser.getByUsername(username)\n\n #adminML = AdminMachineLearning()\n #correlations = adminML.getMachineLearning()\n \n\n #adminML.closeConnection()\n adminUser.closeConnection()\n\n return render_template('quienessomos.html', username=username)\n \napp.run()# se encarga de ejecutar el servidor 5000","sub_path":"back_end/servidor.py","file_name":"servidor.py","file_ext":"py","file_size_in_byte":6115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"455703616","text":"from mqtt_client import device_interface as Client\r\nfrom mqtt_client import _load_python_file\r\n\r\nclient = Client(\"12333\")\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n paths = \"C:\\\\Users\\\\sl1729\\\\Documents\\\\Xilinx_summer_school_project\\\\face_s_server_project\\\\test_add_action2.py\"\r\n print(type(client))\r\n client.__init__(\"12333\")\r\n print(dir(client))\r\n module = client.load_python_module(paths)\r\n client2 = getattr(module, \"client\")\r\n print(client2 == client)\r\n\r\n # for func in dir(module):\r\n # if func.startswith(\"_\"):\r\n # continue\r\n # func = getattr(module, func)\r\n # if callable(func):\r\n # func()\r\n print(client.action)","sub_path":"test_add_action.py","file_name":"test_add_action.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"515129891","text":"\"\"\"This file is a Harris spider created on top of the ATSSpider\nscrapy crawl harris -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://harris.com/careers/jobs/\"\n\nsample url:\n http://harris.com/careers/jobs/\n\"\"\"\n\nfrom urlparse import urljoin\nfrom re import compile\n\nfrom scrapy.http import FormRequest, Request\nfrom scrapy.selector import Selector\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, HtmlFormatter, Replace\n\n\nclass Harris(ATSSpider):\n\n name = 'harris'\n count_re = compile(r\"(\\d+) Found\")\n joblist_url = \"https://harriscorp.authoria.net/joblist.html\"\n\n def start_requests(self):\n yield FormRequest(\n self.joblist_url,\n formdata={\n 'ERFormPage': 'joblist.html',\n 'searchbutton': 'Search',\n 'ERFormID': 'newjoblist',\n }\n )\n\n def parse(self, response):\n sel = Selector(response)\n if not self.expected_job_count_set:\n job_count = sel.xpath(\n '//span[@class=\"listheading\"][contains(text(), \"Found\")]'\n ).re(self.count_re)\n if job_count:\n self.expected_job_count = job_count\n\n jobs = sel.xpath(\n '//td[@class=\"listheadingbackground\"]/table//tr[td/span/a[contains(@href, \"viewjob\")]]'\n )\n for job in jobs:\n job_url = job.xpath('./td/span/a/@href').extract()\n if job_url:\n job_url = Replace(';jsessionid=(.*?)\\?', '?')(job_url[0])\n job_url = urljoin(response.url, job_url[0])\n meta = {\n 'title': job.xpath('./td/span/a/text()').extract(),\n 'ref_num': job.xpath('./td[span/a]/@id').extract(),\n 'loc': job.xpath('./td[4]/span/text()').extract(),\n 'url': job_url,\n }\n yield Request(\n job_url, callback=self.parse_job_callback(), meta=meta\n )\n\n next_url = sel.xpath('//a[@title=\"Next Page\"]/@href').extract()\n if next_url:\n next_url = urljoin(response.url, next_url[0])\n yield Request(next_url, callback=self.parse)\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n loader.add_value('url', response.meta.get('url'))\n loader.add_value('title', response.meta.get('title'))\n loader.add_value('location', response.meta.get('loc'))\n loader.add_value(\n 'referencenumber', response.meta.get('ref_num'),\n Prefix('%s-' % self.name)\n )\n loader.add_xpath(\n 'description',\n '//tr[td/span[@class=\"sectionbody\"]//*[contains(text(), \"Job Title\") or contains(text(), \"Job Description:\")]]',\n HtmlFormatter()\n )\n loader.add_xpath(\n 'jobtype',\n '//td[span[text()=\"Job Type\"]]/following-sibling::td/span/text()'\n )\n loader.add_xpath(\n 'educationrequirements',\n '//td[span[text()=\"Education\"]]/following-sibling::td/span/text()'\n )\n loader.add_xpath(\n 'jobcategory',\n '//td[span[text()=\"Expertise\"]]/following-sibling::td/span/text()'\n )\n if not loader.get_output_value('description'):\n loader.add_xpath(\n 'description',\n '//span[@class=\"pagesubheading2\"][contains(text(), \"Description:\")]/../../following-sibling::tr[1]'\n )\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/harris.py","file_name":"harris.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"477622363","text":"#!/usr/bin/env python\n\n#\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file\n# except in compliance with the License. A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\"\n# BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under the License.\n#\n\nimport os\nimport sys\nimport argparse\nfrom awscfnctl import CfnControl\nfrom argparse import RawTextHelpFormatter\n\nprogname = 'cfnctl'\n\n\ndef arg_parse():\n\n parser = argparse.ArgumentParser(prog=progname,\n description='Launch and manage CloudFormation templates from the command line',\n formatter_class=RawTextHelpFormatter\n )\n parser._optionals.title = \"arguments\"\n\n parser.add_argument('cfn_action', type=str,\n help=\"REQUIRED: Action: build|create|list|delete\\n\"\n \" build Builds the CFN parameter file (-t required)\\n\"\n \" create Creates a new stack (-n and [-t|-f] required)\\n\"\n \" list List all stacks (-d provides extra detail)\\n\"\n \" delete Deletes a stack (-n is required)\"\n )\n parser.add_argument('-r', dest='region', required=False, help=\"Region name\")\n parser.add_argument('-n', dest='stack_name', required=False, help=\"Stack name\")\n parser.add_argument('-t', dest='template', required=False, help='CFN Template from local file or S3 URL')\n parser.add_argument('-f', dest='param_file', required=False,\n help=\"Template parameter file\")\n parser.add_argument('-d', dest='ls_all_stack_info', required=False, help='List details on all stacks',\n action='store_true')\n parser.add_argument('-b', dest='bucket', required=False, help='Bucket to upload template to')\n parser.add_argument('-nr', dest='no_rollback', required=False, help='Do not rollback', action='store_true')\n parser.add_argument('-p', dest='aws_profile', required=False, help='AWS Profile')\n parser.add_argument('-y', dest='no_prompt', required=False, help='On interactive question, force yes',\n action='store_true')\n parser.add_argument('-v', dest='verbose_param_file', required=False, help='Verbose config file',\n action='store_true')\n\n if len(sys.argv[1:]) == 0:\n parser.print_help()\n parser.exit()\n\n return parser.parse_args()\n\n\ndef main():\n\n rc = 0\n args = arg_parse()\n rollback = 'ROLLBACK'\n\n create_stack = False\n del_stack = False\n ls_stacks = False\n build_param_file = False\n\n cfn_action = args.cfn_action\n if cfn_action == \"create\":\n create_stack = True\n elif cfn_action == \"delete\":\n del_stack = True\n elif cfn_action == \"list\":\n ls_stacks = True\n elif cfn_action == \"build\":\n build_param_file = True\n else:\n print('Action has to be \"build|create|list|delete\"')\n sys.exit(1)\n\n bucket = args.bucket\n param_file = args.param_file\n ls_all_stack_info = args.ls_all_stack_info\n region = args.region\n stack_name = args.stack_name\n template = args.template\n no_prompt = args.no_prompt\n verbose_param_file = args.verbose_param_file\n\n errmsg_cr = \"Creating a stack requires 'create' action, stack name (-n), and for new stacks \" \\\n \"the template (-t) flag or for configured stacks, the -f flag for parameters file, \" \\\n \"which includes the template location\"\n\n aws_profile = 'NULL'\n if args.aws_profile:\n aws_profile = args.aws_profile\n print('Using profile {0}'.format(aws_profile))\n\n if args.no_rollback:\n rollback = 'DO_NOTHING'\n\n client = CfnControl(region=region, aws_profile=aws_profile, cfn_action=cfn_action)\n\n if ls_all_stack_info or ls_stacks:\n if ls_all_stack_info and ls_stacks:\n print(\"Gathering all info on CFN stacks...\")\n stacks = client.ls_stacks(show_deleted=False)\n for stack, i in sorted(stacks.items()):\n if len(stack) > 37:\n stack = stack[:37] + \">\"\n print('{0:<42.40} {1:<21.19} {2:<30.28} {3:<.30}'.format(stack, str(i[0]), i[1], i[2]))\n elif ls_stacks:\n print(\"Listing stacks...\")\n stacks = client.ls_stacks(show_deleted=False)\n for stack, i in sorted(stacks.items()):\n print(' {}'.format(stack))\n elif create_stack:\n if stack_name and param_file and not template:\n response = \"\"\n try:\n response = client.cr_stack(stack_name, param_file, verbose=verbose_param_file, set_rollback=rollback)\n except Exception as cr_stack_err:\n print(\"Got response: {0}\".format(response))\n raise ValueError(cr_stack_err)\n\n elif template and stack_name:\n\n if not client.url_check(template):\n if not os.path.isfile(template):\n errmsg = 'File \"{}\" does not exists'.format(template)\n raise ValueError(errmsg)\n try:\n if param_file:\n param_file = param_file\n print(\"Parameters file specified at CLI: {}\".format(param_file))\n\n response = client.cr_stack(stack_name, param_file, verbose=verbose_param_file, set_rollback=rollback,\n template=template)\n #return response\n return\n\n except Exception as cr_stack_err:\n if \"Member must have length less than or equal to 51200\" in str(cr_stack_err):\n if bucket:\n print(\"Uploading {0} to bucket {1} and creating stack\".format(template, bucket))\n response = \"\"\n try:\n template_url = client.upload_to_bucket(template, bucket, template)\n response = client.cr_stack(stack_name, param_file, verbose=verbose_param_file,\n set_rollback=rollback, template=template_url)\n except Exception as upload_to_bucket_err:\n print(\"Got response: {0}\".format(response))\n raise ValueError(upload_to_bucket_err)\n else:\n errmsg = \"The template has too many bytes (>51,200), use the -b flag with a bucket name, or \" \\\n \"upload the template to an s3 bucket and specify the bucket URL with the -t flag \"\n raise ValueError(errmsg)\n else:\n raise ValueError(cr_stack_err)\n elif template and not stack_name:\n raise ValueError(errmsg_cr)\n elif not template and stack_name:\n raise ValueError(errmsg_cr)\n elif not template and not stack_name:\n raise ValueError(errmsg_cr)\n elif del_stack:\n if not stack_name:\n errmsg = \"Must specify a stack to delete (-n)\"\n raise ValueError(errmsg)\n client.del_stack(stack_name, no_prompt=no_prompt)\n elif build_param_file:\n client.build_cfn_param('default', template, cli_template=template)\n elif param_file or stack_name:\n raise ValueError(errmsg_cr)\n else:\n print(\"No actions requested - shouldn't have got this far.\")\n return 0\n\n return rc\n\n\nif __name__ == \"__main__\":\n try:\n sys.exit(main())\n except KeyboardInterrupt:\n print('\\nReceived Keyboard interrupt.')\n print('Exiting...')\n except SystemExit:\n print('Exiting...')\n except ValueError as e:\n print('ERROR: {0}'.format(e))\n except Exception as e:\n print('ERROR: {0}'.format(e))\n","sub_path":"aws-cfn-control/awscfnctl/cfnctl.py","file_name":"cfnctl.py","file_ext":"py","file_size_in_byte":8204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"535317420","text":"\nimport data_generator as dg\nimport model as m\nimport tensorflow as tf\n\nfrom tensorflow.keras.optimizers import Adam\nimport tensorflow.keras as keras\n\nhdf5_path = '/media/norbi/DATA/autonomus_database/deepdrive/linux_recordings/2018-01-18__05-14-48PM'\n\n\n# def map_fn(image, label):\n# '''Preprocess raw data to trainable input. '''\n# x = tf.reshape(tf.cast(image, tf.float32), (28, 28, 1))\n# y = tf.one_hot(tf.cast(label, tf.uint8), _NUM_CLASSES)\n# return x, y\n\ndef run():\n files = dg.get_hdf5_file_names(hdf5_path)\n training_files = files[:-1]\n evaluate_files = []\n evaluate_files.append(files[-1])\n ds = tf.data.Dataset.from_generator(\n dg.generator(training_files), (tf.int8, tf.float32), (tf.TensorShape([66, 200, 3]), tf.TensorShape([])))\n\n # dataset = dataset.map(map_fn)\n ds = ds.batch(46)\n ds = ds.repeat()\n\n ds = ds.prefetch(buffer_size=tf.contrib.data.AUTOTUNE)\n\n model = m.create_model()\n adam = Adam(lr=1e-4, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\n model.compile(optimizer=\"adam\", loss=\"mse\")\n iterator = ds.make_one_shot_iterator()\n\n # print(iterator.get_next())\n\n tbCallback = keras.callbacks.TensorBoard(log_dir='./Graph', histogram_freq=0,\n write_graph=True, write_images=True)\n\n tbCallback.set_model(model)\n cp_callback = tf.keras.callbacks.ModelCheckpoint('checkpoints/cp.ckpt',\n save_weights_only=True,\n verbose=1)\n\n # validation\n print(evaluate_files)\n dt = tf.data.Dataset.from_generator(\n dg.generator(training_files), (tf.int8, tf.float32), (tf.TensorShape([66, 200, 3]), tf.TensorShape([])))\n dt = dt.batch(1)\n dt = dt.repeat()\n\n dt = dt.prefetch(buffer_size=tf.contrib.data.AUTOTUNE)\n model.fit(iterator, steps_per_epoch=1000, validation_data=dt.make_one_shot_iterator(), validation_steps=1000, epochs=15, verbose=1, callbacks=[tbCallback, cp_callback])\n # model.fit_generator(datagen.flow(X_train, y_train, batch_size=BATCH_SIZE),\n # samples_per_epoch=NB_SAMPLES, nb_epoch=NB_EPOCH,\n # validation_data=(X_val, y_val))\n\n\nif __name__ == \"__main__\":\n # files = dg.get_hdf5_file_names(hdf5_path)\n # print(dg.generator(files).calculate_all_picture())\n run()\n","sub_path":"nvidiaDave2/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"249703056","text":"import requests\nfrom bs4 import BeautifulSoup\n\n\nclass MarketWatch:\n base_url = 'https://www.marketwatch.com/tools/screener'\n\n @staticmethod\n def vol_to_float(vol):\n if 'K' in vol:\n vol = float(vol[:-1]) * 1000\n elif 'M' in vol:\n vol = float(vol[:-1]) * 1000000\n else:\n vol = float(vol.replace(',', ''))\n return vol\n\n\n def pre_market(self):\n html = requests.get(f'{self.base_url}/premarket').text\n soup = BeautifulSoup(html, 'html.parser')\n categories = soup.find_all('div', {'class': 'group--elements'})\n categories_matches = {\n 'Leaders': 'gainers',\n 'Laggards': 'loosers',\n 'Most Active': 'most_actives',\n }\n results = {}\n \n for category in categories:\n title = category.find('h2', {'class': 'title'}).text.strip()\n results[categories_matches[title]] = []\n\n for stock in category.find('tbody').find_all('tr', {'class': 'table__row'}):\n cells = stock.find_all('td')\n results[categories_matches[title]].append({\n 'symbol': cells[0].text.strip(),\n 'pre_price': MarketWatch.vol_to_float(cells[2].text.strip()[1:]),\n 'pre_volume': MarketWatch.vol_to_float(cells[3].text.strip()),\n 'pre_change': float(cells[4].text.strip()),\n 'pre_change_perc': float(cells[5]\n .find('li', {'class': 'content__item'})\n .text.strip()[:-1])\n })\n\n return results","sub_path":"alpaca_paper/screeners.py","file_name":"screeners.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"498215107","text":"import _plotly_utils.basevalidators\n\n\nclass HistnormValidator(_plotly_utils.basevalidators.EnumeratedValidator):\n def __init__(self, plotly_name=\"histnorm\", parent_name=\"histogram\", **kwargs):\n super(HistnormValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n edit_type=kwargs.pop(\"edit_type\", \"calc\"),\n values=kwargs.pop(\n \"values\",\n [\"\", \"percent\", \"probability\", \"density\", \"probability density\"],\n ),\n **kwargs,\n )\n","sub_path":"packages/python/plotly/plotly/validators/histogram/_histnorm.py","file_name":"_histnorm.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"115531688","text":"from django.utils.translation import ugettext_lazy as _\nfrom django.utils import timezone\nfrom django.conf import settings\nimport requests\n\nfrom dsmr_notification.models.settings import NotificationSetting, StatusNotificationSetting\nfrom dsmr_stats.models.statistics import DayStatistics\nfrom dsmr_datalogger.models.reading import DsmrReading\nfrom dsmr_frontend.models.message import Notification\nimport dsmr_consumption.services\nimport dsmr_backend.services\n\n\ndef notify_pre_check():\n \"\"\" Checks whether we should notify \"\"\"\n notification_settings = NotificationSetting.get_solo()\n\n if notification_settings.notification_service is None:\n return False\n\n # Dummy message?\n if notification_settings.next_notification is None:\n send_notification(\n message='DSMR-reader notification test.',\n title='DSMR-reader Test Notification'\n )\n NotificationSetting.objects.update(next_notification=timezone.now())\n return True\n\n # Ready to go, but not time yet.\n if notification_settings.next_notification is not None and timezone.now() < notification_settings.next_notification:\n return False\n\n return True\n\n\ndef create_consumption_message(day, stats):\n \"\"\" Create the action notification message \"\"\"\n capabilities = dsmr_backend.services.get_capabilities()\n day_date = (day - timezone.timedelta(hours=1)).strftime(\"%d-%m-%Y\")\n message = _('Your daily usage statistics for {}\\n').format(day_date)\n\n if capabilities['electricity']:\n electricity_merged = dsmr_consumption.services.round_decimal(stats.electricity_merged)\n message += _('Electricity consumed: {} kWh\\n').format(electricity_merged)\n\n if capabilities['electricity_returned']:\n electricity_returned_merged = dsmr_consumption.services.round_decimal(stats.electricity_returned_merged)\n message += _('Electricity returned: {} kWh\\n').format(electricity_returned_merged)\n\n if capabilities['gas']:\n gas = dsmr_consumption.services.round_decimal(stats.gas)\n message += _('Gas consumed: {} m3\\n').format(gas)\n\n message += _('Total cost: € {}').format(dsmr_consumption.services.round_decimal(stats.total_cost))\n return message\n\n\ndef send_notification(message, title):\n \"\"\" Sends notification using the preferred service \"\"\"\n notification_settings = NotificationSetting.get_solo()\n\n DATA_FORMAT = {\n NotificationSetting.NOTIFICATION_PUSHOVER: {\n 'url': NotificationSetting.PUSHOVER_API_URL,\n 'data': {\n 'token': notification_settings.pushover_api_key,\n 'user': notification_settings.pushover_user_key,\n 'priority': '-1',\n 'title': title,\n 'message': message\n }\n },\n NotificationSetting.NOTIFICATION_PROWL: {\n 'url': NotificationSetting.PROWL_API_URL,\n 'data': {\n 'apikey': notification_settings.prowl_api_key,\n 'priority': '-2',\n 'application': 'DSMR-Reader',\n 'event': title,\n 'description': message\n }\n },\n }\n\n response = requests.post(\n **DATA_FORMAT[notification_settings.notification_service]\n )\n\n if response.status_code == 200:\n return\n\n # Invalid request, do not retry.\n if str(response.status_code).startswith('4'):\n print(' - Notification API returned client error, wiping settings...')\n NotificationSetting.objects.update(\n notification_service=None,\n pushover_api_key=None,\n pushover_user_key=None,\n prowl_api_key=None,\n next_notification=None\n )\n Notification.objects.create(\n message='Notification API error, settings are reset. Error: {}'.format(response.text),\n redirect_to='admin:dsmr_notification_notificationsetting_changelist'\n )\n\n # Server error, delay a bit.\n elif str(response.status_code).startswith('5'):\n print(' - Notification API returned server error, retrying later...')\n NotificationSetting.objects.update(\n next_notification=timezone.now() + timezone.timedelta(minutes=5)\n )\n\n raise AssertionError('Notify API call failed: {0} (HTTP {1})'.format(response.text, response.status_code))\n\n\ndef set_next_notification():\n \"\"\" Set the next moment for notifications to be allowed again \"\"\"\n tomorrow = timezone.now() + timezone.timedelta(hours=24)\n NotificationSetting.objects.update(\n next_notification=timezone.make_aware(timezone.datetime(\n year=tomorrow.year,\n month=tomorrow.month,\n day=tomorrow.day,\n hour=2,\n ))\n )\n\n\ndef notify():\n \"\"\" Sends notifications about daily energy usage \"\"\"\n if not notify_pre_check():\n return\n\n # Just post the latest reading of the day before.\n today = timezone.localtime(timezone.now())\n midnight = timezone.make_aware(timezone.datetime(\n year=today.year,\n month=today.month,\n day=today.day,\n hour=0,\n ))\n\n try:\n stats = DayStatistics.objects.get(\n day=(midnight - timezone.timedelta(hours=1))\n )\n except DayStatistics.DoesNotExist:\n return # Try again in a next run\n\n # For backend logging in Supervisor.\n print(' - Creating new notification containing daily usage.')\n\n message = create_consumption_message(midnight, stats)\n send_notification(message, str(_('Daily usage notification')))\n set_next_notification()\n\n\ndef check_status():\n \"\"\" Checks the status of the application. \"\"\"\n status_settings = StatusNotificationSetting.get_solo()\n notification_settings = NotificationSetting.get_solo()\n\n if notification_settings.notification_service is None or \\\n not dsmr_backend.services.is_timestamp_passed(timestamp=status_settings.next_check):\n return\n\n if not DsmrReading.objects.exists():\n return StatusNotificationSetting.objects.update(\n next_check=timezone.now() + timezone.timedelta(minutes=5)\n )\n\n # Check for recent data.\n has_recent_reading = DsmrReading.objects.filter(\n timestamp__gt=timezone.now() - timezone.timedelta(minutes=settings.DSMRREADER_STATUS_READING_OFFSET_MINUTES)\n ).exists()\n\n if has_recent_reading:\n return StatusNotificationSetting.objects.update(\n next_check=timezone.now() + timezone.timedelta(minutes=5)\n )\n\n # Alert!\n print(' - Sending notification about datalogger lagging behind...')\n send_notification(\n str(_('It has been over an hour since the last reading received. Please check your datalogger.')),\n str(_('Datalogger check'))\n )\n\n StatusNotificationSetting.objects.update(\n next_check=timezone.now() + timezone.timedelta(hours=settings.DSMRREADER_STATUS_NOTIFICATION_COOLDOWN_HOURS)\n )\n","sub_path":"dsmr_notification/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":6939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"37162191","text":"\"\"\"\n练习1:在控制台中录入商品信息(名称及单价)\n 如果输入空字符串,则停止录入\n 将所有信息逐行打印\n\"\"\"\ndict_prod = {}\n# while True:\n# nom = input(\"请输入商品信息: \")\n# if nom == \"\":\n# break\n# prix = input(\"请输入商品单价: \")\n# dict_prod[nom] = prix\n# for k, v in dict_prod.items():\n# print(\"商品名:\"+k, \"单价:\"+v)\n\n# 练习2:录入学生信息(姓名,性别,年龄,成绩)\n\"\"\"\n# 字典内嵌字典\n{\n \"卢杰一\":{\"sex\": man,\"age\": 21,\"score\": 12}\n}\n\"\"\"\ndict_stud = {}\nwhile True:\n nom = input(\"请输入学生姓名: \")\n if nom == \"\":\n break\n genre = input(\"请输入性别: \")\n age = input(\"请输入年龄: \")\n note = input(\"请输入成绩: \")\n dict_stud[nom] = {\"sex\": genre, \"age\": age,\"score\": note}\nfor k, v in dict_stud.items():\n print(\"name: \"+k, \"性别:\"+v[\"sex\"],\n \"年龄:\"+v[\"age\"],\n \"成绩: \"+v[\"score\"])\n\n","sub_path":"day06/exo01.py","file_name":"exo01.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"467132966","text":"# Copyright (C) 2019 The Raphielscape Company LLC.\n#\n# Licensed under the Raphielscape Public License, Version 1.b (the \"License\");\n# you may not use this file except in compliance with the License.\n#\n\nfrom userbot import LOGGER, LOGGER_GROUP, HELPER, bot\nfrom userbot.events import register\n\n\n@register(outgoing=True, pattern=\"^\\.saved$\")\nasync def notes_active(svd):\n if not svd.text[0].isalpha() and svd.text[0] not in (\"/\", \"#\", \"@\", \"!\"):\n try:\n from userbot.modules.sql_helper.notes_sql import get_notes\n except:\n await svd.edit(\"`Running on Non-SQL mode!`\")\n return\n\n notes = get_notes(svd.chat_id)\n message = '`There are no saved notes in this chat`'\n if notes:\n message = \"Messages saved in this chat: \\n\\n\"\n for note in notes:\n message = message + \"🔹 \" + note.keyword + \"\\n\"\n await svd.edit(message)\n\n\n@register(outgoing=True, pattern=\"^\\.clear (\\w*)\")\nasync def remove_notes(clr):\n if not clr.text[0].isalpha() and clr.text[0] not in (\"/\", \"#\", \"@\", \"!\"):\n try:\n from userbot.modules.sql_helper.notes_sql import rm_note\n except:\n await clr.edit(\"`Running on Non-SQL mode!`\")\n return\n notename = clr.pattern_match.group(1)\n rm_note(clr.chat_id, notename)\n await clr.edit(\"```Note removed successfully```\")\n\n\n@register(outgoing=True, pattern=\"^\\.save (\\w*)\")\nasync def add_filter(fltr):\n if not fltr.text[0].isalpha():\n try:\n from userbot.modules.sql_helper.notes_sql import add_note\n except:\n await fltr.edit(\"`Running on Non-SQL mode!`\")\n return\n notename = fltr.pattern_match.group(1)\n string = fltr.text.partition(notename)[2]\n if fltr.reply_to_msg_id:\n rep_msg = await fltr.get_reply_message()\n string = rep_msg.text\n add_note(str(fltr.chat_id), notename, string)\n await fltr.edit(\n \"`Note added successfully. Use` #{} `to get it`\".format(notename)\n )\n\n\n@register(pattern=\"#\\w*\")\nasync def incom_note(getnt):\n try:\n if not (await getnt.get_sender()).bot:\n try:\n from userbot.modules.sql_helper.notes_sql import get_notes\n except:\n return\n notename = getnt.text[1:]\n notes = get_notes(getnt.chat_id)\n for note in notes:\n if notename == note.keyword:\n await getnt.reply(note.reply)\n return\n except:\n pass\n\n\n@register(outgoing=True, pattern=\"^\\.rmnotes$\")\nasync def purge_notes(prg):\n try:\n from userbot.modules.sql_helper.notes_sql import rm_all_notes\n except:\n await prg.edit(\"`Running on Non-SQL mode!`\")\n return\n if not prg.text[0].isalpha():\n await prg.edit(\"```Purging all notes.```\")\n rm_all_notes(str(prg.chat_id))\n if LOGGER:\n await prg.client.send_message(\n LOGGER_GROUP, \"I cleaned all notes at \" + str(prg.chat_id)\n )\n\nHELPER.update({\n \"#<notename>\": \"get the note with this notename.\"\n})\nHELPER.update({\n \".save <notename> <notedata>\": \"saves notedata as a note with name notename\"\n})\nHELPER.update({\n \".clear <notename>\": \"clear note with this name.\"\n})","sub_path":"userbot/modules/notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"440918540","text":"\"\"\"\nThis examples presents a multiple shooting optimization\nof a state-space model.\n\nObjective: energy minimization.\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport logging\nimport mshoot\nfrom examples.models import statespace\nfrom resources.ou44 import ou44_data\n\n# Set up logging\nlogging.basicConfig(filename='test.log', filemode='w', level='DEBUG')\n\n# Setup\n# =================\n\n# MPC model definition\nclass SSModel(mshoot.mshoot.SimModel):\n def __init__(self, ss):\n \"\"\"\n Constructor is optional.\n \"\"\"\n self.ss = ss\n\n def simulate(self, udf, x0):\n \"\"\"\n Method required by SimModel.\n\n :param udf: DataFrame, inputs\n :param x0: vector, initial state\n :return: ydf (outputs, DataFrame), xdf (states, DataFrame)\n \"\"\"\n t = udf.index.values\n t_shift = t - t[0]\n u = udf.values\n tout, yout, xout = self.ss.output(u, t_shift, X0=x0)\n ydf = pd.DataFrame(index=t, data=yout,\n columns=['Tr', 'Ti', 'Te', 'qhvac'])\n xdf = pd.DataFrame(index=t, data=xout,\n columns=['Tr', 'Ti', 'Te'])\n return ydf, xdf\n\n# Read inputs: period [h], dt [min]\ndata = ou44_data.get_inputs(period=12, dt=90)\ndata = data.reset_index()\ndata.index = (data['datetime'] - data['datetime'][0]).dt.total_seconds()\n\ninp = data[['Tout', 'Hglo', 'qhvac', 'nocc']]\n\n# Bounds\nTb = data[['datetime', 'nocc']].copy()\nTb['Tr_lo'] = np.where((Tb['datetime'].dt.hour >= 5)\n & (Tb['datetime'].dt.hour <= 7), 21., 16.)\n\nTr_lo = Tb['Tr_lo'].values\n\n# Instantiate control and emulation models\nssmodel = statespace.get_model()\nctrmod = SSModel(ssmodel)\n\n# Define problem\n# =================\n\n# Define cost function\ndef cfun(xdf, ydf):\n \"\"\"\n :param ydf: DataFrame, model states\n :param ydf: DataFrame, model outputs\n :return: float\n \"\"\"\n qhvac = ydf['qhvac']\n n = qhvac.size\n c = np.square(qhvac).sum() / n\n return c\n\n# Instantiate multiple shooting MPC\nmpc = mshoot.MShoot(cfun=cfun)\nx0 = [16., 16., 16.]\nsteps = inp.index.size\n\nuguess = np.full((steps - 1, 1), 9999.)\n\n# Define free input and state bounds\nubounds = [\n (0., 4000.) # qhvac\n]\n\nxbounds = [\n (Tr_lo, 25.), # Room temperature\n (0., 50.), # Internal thermal mass\n (0., 50.) # External thermal mass\n]\n\n# Optimize\nudf, xdf = mpc.optimize(\n model=ctrmod,\n inp=inp,\n free=['qhvac'],\n ubounds=ubounds,\n xbounds=xbounds,\n x0=x0,\n uguess=uguess,\n ynominal=[20., 20., 20., 4000.],\n join=1\n)\n\n# Plot results\n# ============\nxdf.index /= 3600.\nudf.index /= 3600.\nTb.index /= 3600.\n\nfig, ax = plt.subplots(2, 1, sharex=True)\nax[0].plot(xdf['x0'], label=r'$T_i$', marker='o')\nax[0].plot(Tb['Tr_lo'], 'k--', label=r'$T_{sp}$')\nax[0].legend()\nax[0].set_ylabel(r'$T$ [$^\\circ$C]')\nax[1].plot(udf['qhvac'], label=r'$q_{hvac}$', marker='o')\nax[1].set_xlabel('Time [h]')\nax[1].legend()\nax[1].set_ylabel(r'$q$ [W]')\n\nplt.show()\n","sub_path":"examples/mshoot_statespace_1.py","file_name":"mshoot_statespace_1.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"364201790","text":"import numpy as np\nimport json\nimport os\nfrom shutil import copyfile, copytree, Error, move, rmtree\nfrom PIL import Image\nfrom multiprocessing import Pool\n\nbase_fold = '/dresden/gpu2/tl6012/data/ASL/'\nann_fold = base_fold + 'manual_signs_label_969/'\nrgb_fold = os.path.join(base_fold, 'high_resolution_data/utt_frame')\n\ndef load_txt(file_path):\n file = open(file_path)\n result = []\n\n for line in file:\n result.append(line.split()[0])\n return result\n\n\ndef load_json(file):\n with open(file) as json_file:\n data = json.load(json_file)\n return data\n\ndef segment_labels(Yi):\n idxs = [0] + (np.nonzero(np.diff(Yi))[0] + 1).tolist() + [len(Yi)]\n Yi_split = np.array([Yi[idxs[i]] for i in range(len(idxs) - 1)])\n return Yi_split\n\n\ndef segment_intervals(Yi):\n idxs = [0] + (np.nonzero(np.diff(Yi))[0] + 1).tolist() + [len(Yi)]\n intervals = [(idxs[i], idxs[i + 1]) for i in range(len(idxs) - 1)]\n return intervals\n\n\ndef parse_ann(uid):\n ann_path = ann_fold + \"{}.json\".format(uid)\n ann_data = load_json(ann_path)['label']\n\n return ann_data\n\n\ndef copy_one(uid):\n # parse anno\n ann = parse_ann(uid)\n\n # get segmentation-level annation\n ann = list(ann.values())\n intervals = segment_intervals(ann)\n lab = segment_labels(ann)\n ind = np.nonzero(lab)[0]\n lab = lab[ind]\n ann = [intervals[i] for i in ind] # a list of (start_frame, end_frame) tuple\n segment = {}\n\n for seg, l in zip(ann, lab):\n if not uid in segment.keys():\n segment[uid] = [[seg[0], seg[1]-1, l]]\n else:\n segment[uid].append([seg[0], seg[1]-1, l])\n\n if l in idx2cls.keys():\n save_dir = os.path.join(save_root, idx2cls[l],uid+'_'+str(seg[0]))\n print('save to ', save_dir)\n os.makedirs(save_dir, exist_ok=True)\n\n\n\n for frame in range(seg[0], seg[1]):\n # rgb\n src = os.path.join(rgb_fold, uid, str(frame)+'.png')\n dst = os.path.join(save_dir, str(frame)+'.png')\n copyfile(src, dst)\n\n\n # of\n # if os.path.exists(os.path.join(of_fold, uid, 'flow_x_'+str(frame)+'.jpg')):\n # flow_x = np.array(Image.open(os.path.join(of_fold, uid, 'flow_x_'+str(frame)+'.jpg')))\n # else:\n # continue\n #\n # if os.path.exists(os.path.join(of_fold, uid, 'flow_y_'+str(frame)+'.jpg')):\n # flow_y = np.array(Image.open(os.path.join(of_fold, uid, 'flow_y_'+str(frame)+'.jpg')))\n #\n # blank_img = np.zeros(np.array(flow_x).shape, 'uint16')\n # new_flow = np.stack((flow_x, flow_y, blank_img), axis=2)\n # new_flow_img = Image.fromarray(new_flow.astype(np.uint8))\n # new_flow_img.save(os.path.join(save_dir, 'frame'+str(frame)+'.jpg'))\n\n\nif __name__ == '__main__':\n idx2cls = {}\n with open('vocabulary.txt', 'r') as filehandle:\n vocabulary = filehandle.read().splitlines()\n for i, v in enumerate(vocabulary):\n vocab = v.split(\"'\")\n if '/' in vocab[1]:\n vocab[1] = vocab[1].replace('/', 'or') # replace '/' in sign label\n idx2cls[i+1] = vocab[1]\n save_root = '/dresden/gpu2/tl6012/data/ASL/isolated_signs/'\n os.makedirs(save_root, exist_ok=True)\n data_split = os.listdir(rgb_fold)\n\n max_lab = 0\n #copy_one(data_split[0])\n\n process_num = 8\n\n p = Pool(process_num)\n p.map(copy_one, data_split)\n print('finished')","sub_path":"GenerateClassificationFolders.py","file_name":"GenerateClassificationFolders.py","file_ext":"py","file_size_in_byte":3410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"105079169","text":"# Copyright 2004-2008 Roman Yakovenko.\r\n# Distributed under the Boost Software License, Version 1.0. (See\r\n# accompanying file LICENSE_1_0.txt or copy at\r\n# http://www.boost.org/LICENSE_1_0.txt)\r\n\r\nimport os\r\nimport sys\r\nimport unittest\r\nimport fundamental_tester_base\r\n\r\nclass tester_t(fundamental_tester_base.fundamental_tester_base_t):\r\n EXTENSION_NAME = 'overloads_macro'\r\n\r\n def __init__( self, *args ):\r\n fundamental_tester_base.fundamental_tester_base_t.__init__(\r\n self\r\n , tester_t.EXTENSION_NAME\r\n , *args )\r\n\r\n def customize(self, mb ):\r\n calc = mb.class_( 'calculator_t' )\r\n calc.always_expose_using_scope = True\r\n calc.member_functions( 'add' ).set_use_overload_macro( True )\r\n add_doubles = calc.member_function( 'add', arg_types=['double', 'double'] )\r\n add_doubles.set_use_overload_macro( False )\r\n\r\n mb.free_functions( 'add' ).set_use_overload_macro( True )\r\n add_doubles = mb.free_function( 'add', arg_types=['double', 'double'] )\r\n add_doubles.set_use_overload_macro( False )\r\n\r\n\r\n def run_tests(self, module):\r\n calc = module.calculator_t()\r\n self.failUnless( 3 == calc.add( 1, 2 ) )\r\n self.failUnless( 9 == calc.add( 3, 2, 3 ) )\r\n self.failUnless( 3 == calc.add( 1.5, 1.5 ) )\r\n self.failUnless( 3 == module.add( 1, 2 ) )\r\n self.failUnless( 9 == module.add( 3, 2, 3 ) )\r\n self.failUnless( 3 == module.add( 1.5, 1.5 ) )\r\n\r\n\r\ndef create_suite():\r\n suite = unittest.TestSuite()\r\n suite.addTest( unittest.makeSuite(tester_t))\r\n return suite\r\n\r\ndef run_suite():\r\n unittest.TextTestRunner(verbosity=2).run( create_suite() )\r\n\r\nif __name__ == \"__main__\":\r\n run_suite()\r\n","sub_path":"tags/pyplusplus_dev_0.9.5/unittests/overloads_macro_tester.py","file_name":"overloads_macro_tester.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"555419789","text":"import tasks\nimport util\n\nfrom bs4 import BeautifulSoup\nimport datetime\nimport numpy as np\nimport pandas as pd\nimport re\nimport requests\n\n\ndef run_flow():\n dim_artist_df = pd.DataFrame()\n dim_event_df = pd.DataFrame()\n fact_event_prices_df = pd.DataFrame()\n fact_event_artists_df = pd.DataFrame()\n temp_artist_followers_df = pd.DataFrame()\n\n # Activity 1: Get week to search from User\n user_week = tasks.get_user_week()\n\n # Activity 2: Scrape Weekly Event Listing Page\n week_listings_html = tasks.get_event_listings_html(user_week)\n temp_dim_event_df = tasks.get_event_ids(week_listings_html)\n\n # Activity 3: Scrape each Event Page\n for index, row in temp_dim_event_df.iterrows():\n print('Getting event details for: {}'.format(row['event_id']))\n\n dim_artist_rows_df, fact_event_artists_rows_df, dim_event_rows_df,\\\n fact_event_prices_rows_df = _get_event_page_data(row['event_id'])\n\n dim_artist_df = dim_artist_df.append(dim_artist_rows_df, ignore_index=True)\n fact_event_artists_df = fact_event_artists_df.append(fact_event_artists_rows_df, ignore_index=True)\n dim_event_df = dim_event_df.append(dim_event_rows_df, ignore_index=True)\n fact_event_prices_df = fact_event_prices_df.append(fact_event_prices_rows_df, ignore_index=True)\n\n # Activity 4: Scrape each Artist Page\n dim_artist_df.drop_duplicates()\n\n for index, row in dim_artist_df.iterrows():\n print('Getting artist details for: {}'.format(row['artist_name']))\n temp_artist_followers_row_dict = _get_artist_page_data(row)\n temp_artist_followers_df = temp_artist_followers_df.append(temp_artist_followers_row_dict, ignore_index=True)\n\n # Activity 4a: join fact_event_artists with artist followers\n fact_event_artists_df = fact_event_artists_df.join(temp_artist_followers_df.set_index('artist_id'), on='artist_id')\n\n return dim_artist_df, fact_event_artists_df, dim_event_df, fact_event_prices_df\n\n\ndef _get_event_page_data(event_id):\n dim_event_row_df = pd.DataFrame()\n dim_artist_rows_df = pd.DataFrame()\n fact_event_prices_rows_df = pd.DataFrame()\n fact_event_artists_rows_df = pd.DataFrame()\n\n event_id_dict = {\n 'event_id': event_id,\n }\n\n # text_to_file\n event_url = util.build_url(event_id)\n event_html = util.get_html(event_url)\n\n text_file = open('{}.txt'.format(event_id[-7:]), 'w')\n text_file.write(event_html.prettify())\n\n temp_artist_df = tasks.get_artists(event_html, dim_artist_rows_df)\n\n # Sub-Activity 1: build dim_artist_rows_df fact_event_prices_rows_df\n if len(temp_artist_df) != 0:\n for index, row in temp_artist_df.iterrows():\n artist_url = util.build_url(row['artist_id'])\n artist_rows_dict = {\n 'artist_id': row['artist_id'],\n 'artist_name': row['artist_name'],\n 'artist_url': artist_url\n }\n dim_artist_rows_df = dim_artist_rows_df.append(artist_rows_dict, ignore_index=True)\n\n # Sub-Activity 2: build fact_event_artists_df\n fact_event_artists_rows_df['artist_id'] = temp_artist_df['artist_id']\n fact_event_artists_rows_df['event_id'] = event_id\n\n # # Sub-Activity 3: build dim_event_row_df\n dim_event_row_df = dim_event_row_df.append(event_id_dict, ignore_index=True)\n dim_event_row_df['event_url'] = event_url\n tasks.get_event_venue(event_html, dim_event_row_df)\n tasks.get_event_date(event_html, dim_event_row_df)\n tasks.get_event_times(event_html, dim_event_row_df)\n tasks.get_is_ra_pick(event_html, dim_event_row_df)\n\n # Sub-Activity 4: build fact_event_prices_rows_df\n fact_event_prices_rows_df = fact_event_prices_rows_df.append(event_id_dict, ignore_index=True)\n fact_event_prices_rows_df = tasks.get_event_prices(event_html, fact_event_prices_rows_df)\n\n if len(fact_event_prices_rows_df.columns) == 1:\n fact_event_prices_rows_df['status'] = np.nan\n fact_event_prices_rows_df['price'] = np.nan\n fact_event_prices_rows_df['is_third_party'] = True\n\n else:\n fact_event_prices_rows_df['is_third_party'] = False\n\n return dim_artist_rows_df, fact_event_artists_rows_df, dim_event_row_df, fact_event_prices_rows_df\n\n\ndef _get_artist_page_data(artist_row):\n\n artist_html = util.get_html(artist_row['artist_url'])\n artist_followers = tasks.get_artist_followers(artist_html, artist_row['artist_id'])\n\n text_file = open('{}.txt'.format(artist_row['artist_id'][4:]), 'w')\n text_file.write(artist_html.prettify())\n\n artist_followers_dict = {\n 'artist_id': artist_row['artist_id'],\n 'artist_followers': artist_followers\n }\n\n return artist_followers_dict\n\n\n\nif __name__ == '__main__':\n print(run_flow())\n","sub_path":"flow.py","file_name":"flow.py","file_ext":"py","file_size_in_byte":4772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"310196183","text":"## plot a heatmap with the top 100 instance features across all SV types.\n\nimport sys\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import RandomForestClassifier\nimport random\nfrom scipy import stats\nfrom statsmodels.sandbox.stats.multicomp import multipletests\nimport os\nimport os.path\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib.colors import ListedColormap\n\ndef generateHeatmap(cancerTypes, svTypes = ['DEL', 'DUP', 'INV', 'ITX']):\n\n\t#get the significances for each cancer type\n\tpValuesPerCancerType = dict()\n\tfor cancerType in cancerTypes:\n\t\tprint('cancer type: ', cancerType)\n\t\t#first get the instances and their ranking across all SV types\n\t\timportances, instances = getFeatureImportances(svTypes, cancerType)\n\t\t#then compute the significances of the top 100 to random 100 instances\n\n\t\tpValues, zScores = computeFeatureSignificances(importances, instances, 100)\n\t\tpValuesPerCancerType[cancerType] = [pValues, zScores]\n\n\t#then make a heatmap plot of the significances.\n\tplotHeatmap(pValuesPerCancerType)\n\ndef plotHeatmap(pValuesPerCancerType):\n\n\t#re-format the p-values to a binary style for plotting\n\tsignificanceMatrix = []\n\tfor cancerType in pValuesPerCancerType:\n\t\tsignificances = []\n\t\tpValues = pValuesPerCancerType[cancerType][0]\n\t\tzScores = pValuesPerCancerType[cancerType][1]\n\n\t\t#below this we call it 'very' significant.\n\t\tsignCutoff = 1e-5\n\t\tfor pValueInd in range(0, len(pValues)):\n\t\t\tpValue = pValues[pValueInd]\n\t\t\tif pValue < 0.05 and zScores[pValueInd] > 0:\n\n\t\t\t\tif pValue < signCutoff:\n\t\t\t\t\tsignificances.append(2)\n\t\t\t\telse:\n\t\t\t\t\tsignificances.append(1)\n\t\t\telif pValue < 0.05 and zScores[pValueInd] < 0:\n\n\t\t\t\tif pValue < signCutoff:\n\t\t\t\t\tsignificances.append(-2)\n\t\t\t\telse:\n\t\t\t\t\tsignificances.append(-1)\n\n\t\t\telse:\n\t\t\t\tsignificances.append(0)\n\n\t\tsignificanceMatrix.append(significances)\n\n\tsignificanceMatrix = np.array(significanceMatrix)\n\n\tfig =plt.figure(figsize=(15,10))\n\t\n\tdata = pd.DataFrame(significanceMatrix) #exclude translocations, these are not there for germline.\n\tg=sns.heatmap(data,annot=False,square=True, linewidths=0.5,\n\t\t\t\t cmap=ListedColormap(['#0055d4ff', '#0055d47d', '#f7f6f6ff', '#c8373780', '#c83737ff']),\n\t\t\t\t yticklabels=list(pValuesPerCancerType.keys()))\n\n\tg.set_yticklabels(g.get_yticklabels(), horizontalalignment='right',fontsize='small')\n\tplt.xticks(np.arange(0, len(pValues))+0.5, ['Gains', 'Losses', 'cpg', 'tf', 'hic', 'ctcf', 'dnaseI', 'h3k9me3', 'h3k4me3', 'h3k27ac', 'h3k27me3', 'h3k4me1', 'h3k36me3',\n\t\t\t'CTCF', 'CTCF+Enhancer', 'CTCF+Promoter', 'Enhancer', 'Heterochromatin', 'Poised_Promoter', 'Promoter', 'Repeat', 'Repressed', 'Transcribed', 'rnaPol',\n\t\t\t'enhancer_s', 'ctcf_s', 'rnaPol_s', 'h3k9me3_s', 'h3k4me3_s', 'h3k27ac_s', 'h3k27me3_s', 'h3k4me1_s', 'h3k26me3_s', 'enhancerType', 'eQTLType', 'superEnhancerType',\n\t\t\t'instCount'], rotation=45, horizontalalignment='right')\n\n\tplt.tight_layout()\n\n\n\tplt.savefig('featureImportanceHeatmap.svg')\n\tplt.show()\n\n\t\ndef computeFeatureSignificances(importances, instances, top):\n\n\t#rank the importances by score\n\tindices = np.argsort(importances)[::-1]\n\n\t#then get the top instances\n\ttopInstances = instances[indices[0:top]]\n\n\t#compute the percentages in these top X instances\n\tavgInstances = np.sum(topInstances, axis=0)\n\ttotalInstances = avgInstances / topInstances.shape[0]\n\n\t#then compare to 100 random instances to see if it is significant.\n\t#per feature, have a distribution\n\tnullDistributions = dict()\n\trandom.seed(785)\n\tfor i in range(0,top):\n\n\t\tif i == 0:\n\t\t\tfor featureInd in range(0, len(totalInstances)):\n\t\t\t\tnullDistributions[featureInd] = []\n\n\t\t#sample as much random instances as in our filtered instances\n\t\trandomIndices = random.sample(range(0,instances.shape[0]), topInstances.shape[0])\n\n\t\trandomTopInstances = instances[randomIndices]\n\n\t\t#compute the percentages in these top X instances\n\t\tavgRandomInstances = np.sum(randomTopInstances, axis=0)\n\n\t\ttotalRandomInstances = avgRandomInstances / randomTopInstances.shape[0]\n\n\t\tfor featureInd in range(0, len(totalRandomInstances)):\n\t\t\tnullDistributions[featureInd].append(totalRandomInstances[featureInd])\n\n\t#for each feature, compute a z-score\n\tfeaturePValues = []\n\tfeatureZScores = []\n\tfor featureInd in range(0, len(nullDistributions)):\n\n\t\tif np.std(nullDistributions[featureInd]) == 0:\n\t\t\tz = 0\n\t\t\tpValue = 1\n\t\t\tfeatureZScores.append(z)\n\t\t\tfeaturePValues.append(pValue)\n\t\t\tcontinue\n\n\t\tz = (totalInstances[featureInd] - np.mean(nullDistributions[featureInd])) / float(np.std(nullDistributions[featureInd]))\n\t\tpValue = stats.norm.sf(abs(z))*2\n\n\t\tfeatureZScores.append(z)\n\t\tfeaturePValues.append(pValue)\n\n\t#do MTC on the p-values\n\n\treject, pAdjusted, _, _ = multipletests(featurePValues, method='bonferroni')\n\n\n\tprint(pAdjusted)\n\treturn pAdjusted, featureZScores\n\ndef getFeatureImportances(svTypes, cancerType):\n\n\t#set the directory to look in for this cancer type\n\toutDir = sys.argv[1] + '/' + cancerType\n\t\n\t#gather the top 100 instances across all SV types\n\t#also return the instances themselves to get the features\n\tallInstances = []\n\tallImportances = []\n\n\tfor svType in svTypes:\n\t\t#define the classifiers to use (from optimization)\n\t\t#would be nicer if these are in 1 file somewhere, since they are also used in another script\n\n\t\tif svType == 'DEL':\n\t\t\tclf = RandomForestClassifier(random_state=785, n_estimators= 600, min_samples_split=5, min_samples_leaf=1, max_features='auto', max_depth=80, bootstrap=True)\n\t\t\ttitle = 'deletions'\n\t\telif svType == 'DUP':\n\t\t\tclf = RandomForestClassifier(random_state=785, n_estimators= 600, min_samples_split=5, min_samples_leaf=1, max_features='auto', max_depth=80, bootstrap=True)\n\t\t\ttitle = 'duplications'\n\t\telif svType == 'INV':\n\t\t\tclf = RandomForestClassifier(random_state=785, n_estimators= 200, min_samples_split=5, min_samples_leaf=4, max_features='auto', max_depth=10, bootstrap=True)\n\t\t\ttitle = 'inversions'\n\t\telif svType == 'ITX':\n\t\t\tclf = RandomForestClassifier(random_state=785, n_estimators= 1000, min_samples_split=5, min_samples_leaf=1, max_features='auto', max_depth=80, bootstrap=True)\n\t\t\ttitle = 'translocations'\n\t\telse:\n\t\t\tprint('SV type not supported')\n\t\t\texit(1)\n\n\t\t#load the similarity matrix of this SV type\n\t\tdataPath = outDir + '/multipleInstanceLearning/similarityMatrices/'\n\t\t\n\t\t\n\t\t#check for sv types for which we have no SVs\n\t\tif not os.path.isfile(dataPath + '/similarityMatrix_' + svType + '.npy'):\n\t\t\tcontinue\n\t\t\n\t\tsimilarityMatrix = np.load(dataPath + '/similarityMatrix_' + svType + '.npy', encoding='latin1', allow_pickle=True)\n\t\tbagLabels = np.load(dataPath + '/bagLabelsSubsampled_' + svType + '.npy', encoding='latin1', allow_pickle=True)\n\t\tinstances = np.load(dataPath + '/instancesSubsampled_' + svType + '.npy', encoding='latin1', allow_pickle=True)\n\t\tbagPairLabels = np.load(dataPath + '/bagPairLabelsSubsampled_' + svType + '.npy', encoding='latin1', allow_pickle=True)\n\t\tbagMap = np.load(dataPath + '/bagMap_' + svType + '.npy', encoding='latin1', allow_pickle=True).item()\n\t\tfilteredFeatures = np.loadtxt(dataPath + '/lowVarianceIdx_' + svType + '.txt')\n\n\t\t#train the classifier on the full dataset\n\t\tclf.fit(similarityMatrix, bagLabels)\n\t\tprint('Classifier performance on all data: ', clf.score(similarityMatrix, bagLabels))\n\t\t#get the feature importances\n\t\timportances = list(clf.feature_importances_)\n\t\t\n\t\tallImportances += importances\n\t\t\n\t\t#because low index features are removed, add them back here if necessary\n\t\t#to retain an overview of all used features\n\t\tfixedInstances = []\n\t\tfor instance in instances:\n\t\t\tfinalLength = len(instance) + len(filteredFeatures)\n\t\t\tinstanceMal = np.zeros(finalLength)\n\t\t\taddedFeatures = 0\n\t\t\tfor featureInd in range(0, finalLength):\n\n\t\t\t\tif featureInd in filteredFeatures:\n\t\t\t\t\tinstanceMal[featureInd] = 0\n\t\t\t\t\taddedFeatures += 1\n\t\t\t\telse:\n\t\t\t\t\tinstanceMal[featureInd] = instance[featureInd-addedFeatures]\n\n\t\t\tfixedInstances.append(instanceMal)\n\n\t\tallInstances += fixedInstances\n\n\tallImportances = np.array(allImportances)\n\tallInstances = np.array(allInstances)\n\treturn allImportances, allInstances\n\ncancerTypes = ['HMF_Breast', 'HMF_Ovary', 'HMF_Liver', 'HMF_Lung', 'HMF_Colorectal',\n\t\t\t\t 'HMF_UrinaryTract', 'HMF_Prostate', 'HMF_Esophagus', 'HMF_Skin',\n\t\t\t\t 'HMF_Pancreas', 'HMF_Uterus', 'HMF_Kidney', 'HMF_NervousSystem']\n\ngenerateHeatmap(cancerTypes)\n\n\t\t","sub_path":"src/multipleInstanceLearning/plotFeatureImportancesHeatmap.py","file_name":"plotFeatureImportancesHeatmap.py","file_ext":"py","file_size_in_byte":8303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"163756201","text":"\"\"\"\nDjango settings for {{ project_name }} project on Heroku. For more info, see:\nhttps://github.com/heroku/heroku-django-template-upeu\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/2.0/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/2.0/ref/settings/\n\"\"\"\n\nimport os\nimport dj_database_url\nfrom django.urls import reverse_lazy\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nPROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = \"{{ secret_key }}\"\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\n# Application definition\n\nINSTALLED_APPS = [\n #'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n # Disable Django's own staticfiles handling in favour of WhiteNoise, for\n # greater consistency between gunicorn and `./manage.py runserver`. See:\n # http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development\n 'whitenoise.runserver_nostatic',\n 'django.contrib.staticfiles',\n\n 'social_django',\n 'core', # if AUTH_USER_MODEL = 'core.User' and SOCIAL_AUTH_USER_MODEL = 'core.User'\n 'accounts',\n 'django.contrib.admin',\n 'bootstrap3',\n\n 'django.contrib.admindocs',\n 'oauth2_provider',\n 'rest_framework',\n 'corsheaders',\n\n # Add your apps here.\n\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = '{{ project_name }}.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'social_django.context_processors.backends',\n 'social_django.context_processors.login_redirect',\n ],\n 'debug': DEBUG,\n },\n },\n]\n\nWSGI_APPLICATION = '{{ project_name }}.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/2.0/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\n\nDATABASESx = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': 'd6rvmpj68r6l4n',\n 'USER': 'vouyocdcjggiwt',\n 'PASSWORD': 'a59df75e117f358691a9e2b460c2d41fc9d2371286e840791a9cafb8219b6463',\n 'HOST': 'ec2-54-221-204-213.compute-1.amazonaws.com',\n 'PORT': '5432',\n }\n}\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n\n]\n\n# Internationalization\n# https://docs.djangoproject.com/en/2.0/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n# Change 'default' database configuration with $DATABASE_URL.\nDATABASES['default'].update(dj_database_url.config(conn_max_age=500))\n\n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n# Allow all host headers\nALLOWED_HOSTS = ['*']\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/2.0/howto/static-files/\n\nSTATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')\nSTATIC_URL = '/static/'\n\n# Extra places for collectstatic to find static files.\nSTATICFILES_DIRS = [\n os.path.join(PROJECT_ROOT, 'static'),\n]\n\n# Simplified static file serving.\n# https://warehouse.python.org/project/whitenoise/\nSTATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\n\n\n# add vars\n\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\n\nAUTH_USER_MODEL = 'core.User' # if 'core' app in INSTALLED_APPS\nSOCIAL_AUTH_USER_MODEL = 'core.User' # if 'core' app in INSTALLED_APPS\n\nLOGIN_REDIRECT_URL = reverse_lazy('dashboard')\nLOGIN_URL = reverse_lazy('login')\nLOGOUT_URL = reverse_lazy('logout')\n\n\n# 設定 Django 在 console 中輸出 e-mail 內容來代替通過 SMTP 服務發送郵件\n# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\n\n# EMAIL\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_HOST_USER = 'upeu2018pro@gmail.com'\nEMAIL_HOST_PASSWORD = '12345678a'\nEMAIL_PORT = 587\nEMAIL_USE_TLS = True\nDEFAULT_FROM_EMAIL = 'upeu2018pro@gmail.com'\n\nAUTHENTICATION_BACKENDS = (\n 'social_core.backends.facebook.FacebookOAuth2',\n 'social_core.backends.github.GithubOAuth2',\n 'social_core.backends.google.GoogleOAuth2',\n 'social_core.backends.twitter.TwitterOAuth',\n 'django.contrib.auth.backends.ModelBackend',\n 'accounts.authentication.EmailAuthBackend',\n #'oauth2_provider.backends.OAuth2Backend',\n)\n\nAUTHENTICATION_BACKENDSx = (\n 'oauth2_provider.backends.OAuth2Backend',\n # Uncomment following if you want to access the admin\n 'django.contrib.auth.backends.ModelBackend',\n\n)\n\nSOCIAL_AUTH_URL_NAMESPACE = 'social'\n\nSOCIAL_AUTH_FACEBOOK_KEY = '1505995752817741'\nSOCIAL_AUTH_FACEBOOK_SECRET = 'a1b671143334bf268f0881655dd7f08c'\nSOCIAL_AUTH_FACEBOOK_SCOPE = ['email']\nSOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {\n 'fields': 'id, name, email'\n}\n\nSOCIAL_AUTH_GITHUB_KEY = 'ddcde373489a4be6deec'\nSOCIAL_AUTH_GITHUB_SECRET = '39319ff7120c0f1cb57af7130f323ebf7cb35669'\nSOCIAL_AUTH_GITHUB_SCOPE = ['email']\nSOCIAL_AUTH_GITHUB_PROFILE_EXTRA_PARAMS = {\n 'fields': 'id, name, email'\n}\n\nSOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '1082996671890-fbu61vmp0gfehh7tg0tgs7feenqr95qj.apps.googleusercontent.com'\nSOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'kYj_RFjlDyDQbt6SnscPrC1j'\nSOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['email']\nSOCIAL_AUTH_GOOGLE_PROFILE_EXTRA_PARAMS = {\n 'fields': 'id, name, email'\n}\n#SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS = ['upeu.edu.pe', ]\n\nSOCIAL_AUTH_TWITTER_KEY = 'SYaVSEKyHbeoFrUJm6zEU1XVa'\nSOCIAL_AUTH_TWITTER_SECRET = 'deltB2apIjLqThoJXDRPkPVI8ure7x9Ik5RD3g6mF6H64gOrnJ'\nSOCIAL_AUTH_TWITTER_OAUTH2_SCOPE = ['email']\nSOCIAL_AUTH_TWITTER_PROFILE_EXTRA_PARAMS = {\n 'fields': 'id, name, email'\n}\n\n\n#CSRF_USE_SESSIONS = False\nCORS_ORIGIN_ALLOW_ALL = True # False\nCORS_ALLOW_CREDENTIALS = True\nCORS_ORIGIN_WHITELIST = ('127.0.0.1:9001', '127.0.0.1:9003',\n 'localhost:9003', 'localhost:8003')\n# Also\nOAUTH2_PROVIDER = {\n # this is the list of available scopes\n 'SCOPES': {\n 'read': 'Read scope',\n 'write': 'Write scope',\n 'openid': 'Access to your openid connect',\n 'home': 'Access to your home page',\n 'backend': 'Access to your backend app',\n 'catalogo': 'Access to your catalogo app',\n 'ubigeo': 'Access to your ubigeo app',\n 'eventos': 'Access to your admision app',\n 'acuerdos': 'Access to your admision app',\n 'admision': 'Access to your admision app',\n }\n}\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n #'rest_framework.authentication.SessionAuthentication',\n 'oauth2_provider.contrib.rest_framework.OAuth2Authentication',\n )\n}\n\n\nimport datetime\n\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose0': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'\n },\n 'verbose': {\n 'format': \"[%(asctime)s] [%(levelname)s] [%(name)s:%(lineno)s] [%(path)s] [%(ip)s] [%(user)s] [%(method)s] %(message)s\",\n 'datefmt': \"%Y-%m-%d %H:%M:%S\"\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n 'verbose_dj': {\n 'format': \"[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s\",\n 'datefmt': \"%Y-%m-%d %H:%M:%S\"\n },\n },\n 'handlers': {\n\n 'file_django': {\n 'level': 'DEBUG',\n #'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),\n 'class': 'logging.FileHandler',\n 'filename': os.path.join(\n BASE_DIR, 'temp/logs',\n 'dj%s.txt' % (datetime.datetime.now().strftime(\"%Y-%m-%d\"))\n ),\n 'formatter': 'verbose_dj'\n },\n 'file_log': {\n 'level': 'DEBUG',\n 'class': 'logging.FileHandler',\n 'filename': os.path.join(\n BASE_DIR, 'temp/logs',\n 'log%s.txt' % (datetime.datetime.now().strftime(\"%Y-%m-%d\"))\n ),\n 'formatter': 'verbose'\n },\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'verbose0'\n },\n\n },\n 'loggers': {\n 'django': {\n 'handlers': ['file_django'],\n 'propagate': False,\n 'level': 'DEBUG',\n },\n 'apps': {\n 'handlers': ['file_log'],\n 'level': 'DEBUG',\n },\n },\n 'root': {\n 'handlers': ['console', 'file_log', ],\n 'level': 'INFO'\n },\n}\n\n\n# Backup/restore database https://code.djangoproject.com/wiki/Fixtures\nFIXTURE_DIRS = (\n os.path.join(BASE_DIR, 'fixtures'),\n)\n","sub_path":"project_name/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":10115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"336754583","text":"from __future__ import annotations\n\nimport abc\nimport logging\nimport typing as tp\nfrom copy import deepcopy\nfrom pathlib import Path\n\nfrom soulstruct.containers import Binder\nfrom .fmg import BaseFMG\n\nif tp.TYPE_CHECKING:\n from soulstruct.containers.bnd import BaseBND\n from soulstruct.containers.entry import BinderEntry\n from soulstruct.utilities.misc import BiDict\n\n__all__ = [\"MSGDirectory\"]\n_LOGGER = logging.getLogger(__name__)\n\n\nclass MSGDirectory(abc.ABC):\n\n IS_DCX: bool = None\n\n # These are text categories you are likely to want to change in mod projects.\n MAIN_CATEGORIES = ()\n\n # These are text categories you are unlikely to change, whether it's for pragmatic\n # reasons or because they contain low-level menu/system text. Generally, new IDs\n # cannot be added to these categories without modifying the game engine.\n INTERNAL_CATEGORIES = ()\n\n ALL_CATEGORIES = ALL_FMG_NAMES = MAIN_CATEGORIES + INTERNAL_CATEGORIES\n\n _MSGBND_INDEX_NAMES = None # type: BiDict[str, str]\n\n FMG_CLASS = None # type: tp.Type[BaseFMG]\n\n def __init__(self, msg_directory=None):\n \"\"\"Unpack all text data in given folder (from both 'item' and 'menu' MSGBND files) into one unified structure.\n\n You can access and modify the `entries` attributes of each loaded `FMG` instance using the names of the FMGs,\n which I have translated into a standard list (see game-specific attribute hints). The source (item/menu) of the\n FMG and its type (standard/Patch) are handled internally.\n , though the latter does not matter in either version of DS1\n (and neither do the names of the FMG files in the MSGBND archives)\n\n Args:\n msg_directory: Directory containing 'item.msgbnd[.dcx]' and 'menu.msgbnd[.dcx]', in any of the language\n folders (such as 'ENGLISH' or 'engus') within the 'msg' directory in your game installation.\n \"\"\"\n self.directory = None\n self._is_menu = {} # Records whether each FMG belongs in 'item' or 'menu' MSGBND.\n self._original_names = {} # Records original names of FMG files in BNDs.\n self.categories = {} # type: dict[str, dict[int, str]]\n\n if msg_directory is None:\n self.item_msgbnd = None\n self.menu_msgbnd = None\n return\n\n self.directory = Path(msg_directory)\n\n ext = \"msgbnd.dcx\" if self.IS_DCX else \"msgbnd\"\n self.item_msgbnd = Binder(self.directory / f\"item.{ext}\")\n self.menu_msgbnd = Binder(self.directory / f\"menu.{ext}\")\n\n self.load_fmg_entries_from_bnd(self.item_msgbnd, is_menu=False)\n self.load_fmg_entries_from_bnd(self.menu_msgbnd, is_menu=True)\n\n for key, fmg_dict in self.categories.items():\n setattr(self, key, fmg_dict)\n\n @classmethod\n def from_bnds(cls, item_msgbnd: BaseBND, menu_msgbnd: BaseBND):\n instance = cls()\n instance.item_msgbnd = item_msgbnd\n instance.menu_msgbnd = menu_msgbnd\n instance.load_fmg_entries_from_bnd(instance.item_msgbnd, is_menu=False)\n instance.load_fmg_entries_from_bnd(instance.menu_msgbnd, is_menu=True)\n for key, fmg_dict in instance.categories.items():\n setattr(instance, key, fmg_dict)\n return instance\n\n def load_fmg_entries_from_bnd(self, msgbnd: BaseBND, is_menu: bool):\n \"\"\"Loads FMGs from given `msgbnd` into `categories` dictionary.\"\"\"\n for entry in msgbnd:\n try:\n attr_name = self._MSGBND_INDEX_NAMES[entry.id]\n except KeyError:\n raise ValueError(f\"MSGBND entry '{entry.path}' has unexpected index {entry.id} in its msgbnd.\")\n self._original_names[attr_name] = entry.name\n self._is_menu[attr_name] = is_menu\n fmg = self.FMG_CLASS(entry.get_uncompressed_data())\n if attr_name.endswith(\"Patch\"):\n # Patch FMGs are used to update the base FMGs here.\n # Original source (patch or no) is not tracked; all entries will be written to patch FMG by `pack()`.\n attr_name = attr_name[:-5]\n self.categories.setdefault(attr_name, {}).update(fmg.entries)\n\n def update_msgbnd_entry(\n self, msgbnd, fmg_name, fmg_entries: dict, word_wrap_limit=None, pipe_to_newline=False, use_original_names=True\n ):\n fmg_data = self.FMG_CLASS({\"entries\": fmg_entries}).pack(\n word_wrap_limit=word_wrap_limit, pipe_to_newline=pipe_to_newline\n )\n try:\n bnd_entry_id = self._MSGBND_INDEX_NAMES[fmg_name]\n except IndexError:\n raise ValueError(f\"Could not recover BND entry ID for FMG named {fmg_name}.\")\n bnd_entry = msgbnd.entries_by_id[bnd_entry_id] # type: BinderEntry\n bnd_entry.set_uncompressed_data(fmg_data)\n if not use_original_names:\n bnd_entry.path = bnd_entry.path.replace(self._original_names[fmg_name], fmg_name + \".fmg\")\n\n def pack(\n self,\n description_word_wrap_limit=None,\n use_original_names=True,\n pipe_to_newline=True,\n ) -> tuple[BaseBND, BaseBND]:\n \"\"\"Pack up and return new \"item\" and \"menu\" MSGBNDs. Does not modify any instance state.\"\"\"\n new_item_msgbnd = deepcopy(self.item_msgbnd) # type: BaseBND\n new_menu_msgbnd = deepcopy(self.menu_msgbnd) # type: BaseBND\n\n for fmg_name, fmg_entries in self.categories.items():\n word_wrap = description_word_wrap_limit if \"Descriptions\" in fmg_name else None\n\n if fmg_name + \"Patch\" in self._is_menu:\n # Updates patch only, if available.\n fmg_name = fmg_name + \"Patch\"\n\n fmg_msgbnd = new_menu_msgbnd if self._is_menu[fmg_name] else new_item_msgbnd\n self.update_msgbnd_entry(\n fmg_msgbnd,\n fmg_name,\n fmg_entries,\n word_wrap_limit=word_wrap,\n pipe_to_newline=pipe_to_newline,\n use_original_names=use_original_names,\n )\n\n return new_item_msgbnd, new_menu_msgbnd\n\n def write(\n self,\n msg_directory=None,\n description_word_wrap_limit=None,\n use_original_names=True,\n pipe_to_newline=True,\n update_instance=True,\n ):\n \"\"\"Pack up and write new \"item\" and \"menu\" MSGBNDs. See `pack()` for more.\"\"\"\n msg_directory = self.directory if msg_directory is None else Path(msg_directory)\n\n new_item_msgbnd, new_menu_msgbnd = self.pack(\n description_word_wrap_limit=description_word_wrap_limit,\n use_original_names=use_original_names,\n pipe_to_newline=pipe_to_newline,\n )\n\n # Write BNDs (to original directory by default).\n new_item_msgbnd.write(msg_directory / new_item_msgbnd.path.name)\n new_menu_msgbnd.write(msg_directory / new_menu_msgbnd.path.name)\n\n _LOGGER.info(\"MSGDirectory files (`item` and `menu` MSGBND files) written successfully.\")\n\n if update_instance:\n # Update BNDs only after successful write.\n self.item_msgbnd = new_item_msgbnd\n self.menu_msgbnd = new_menu_msgbnd\n\n def get_all_item_text(self, index, item_type=\"good\"):\n \"\"\" Get name, summary, and description of goods, weapons, armor, or rings. \"\"\"\n item_fmg = self.resolve_item_type(item_type)\n if index not in self.categories[item_fmg + \"Names\"]:\n return None\n return {\n \"name\": self.categories[item_fmg + \"Names\"][index],\n \"summary\": self.categories[item_fmg + \"Summaries\"][index],\n \"description\": self.categories[item_fmg + \"Descriptions\"][index],\n }\n\n def add_item_text(self, index, item_type, name, summary, description):\n item_fmg = self.resolve_item_type(item_type)\n if index in self.categories[item_fmg + \"Names\"]:\n raise ValueError(\n f\"Item with index {index} already exists in {item_fmg}Names: \"\n f\"{self.categories[item_fmg + 'Names'][index]}\"\n )\n self.categories[item_fmg + \"Names\"][index] = name\n self.categories[item_fmg + \"Summaries\"][index] = summary\n self.categories[item_fmg + \"Descriptions\"][index] = description\n\n def delete_item_text(self, index, item_fmg=\"good\"):\n \"\"\" Remove entries for item name, summary, and description. \"\"\"\n item_fmg = self.resolve_item_type(item_fmg)\n if index not in self.categories[item_fmg + \"Names\"]:\n raise ValueError(f\"There is no {item_fmg} with index {index} to delete.\")\n self.categories[item_fmg + \"Names\"][index] = \"\"\n self.categories[item_fmg + \"Summaries\"][index] = \"\"\n self.categories[item_fmg + \"Descriptions\"][index] = \"\"\n\n def change_item_text(self, text_dict, index=None, item_type=None, patch=False):\n if index is None:\n index = text_dict[\"index\"]\n if not isinstance(index, (list, tuple)):\n index = (index,)\n if item_type is None:\n item_type = text_dict[\"item_type\"]\n item_fmg = self.resolve_item_type(item_type)\n patch = \"Patch\" if patch else \"\"\n for i in index:\n if i not in self[item_fmg + \"Names\"]:\n _LOGGER.info(\n f\"NEW ENTRY: {item_fmg} with index {i} has been added ({text_dict.get('name', 'unknown name')})\"\n )\n if \"name\" in text_dict:\n self[item_fmg + \"Names\" + patch][i] = text_dict[\"name\"]\n if \"summary\" in text_dict:\n self[item_fmg + \"Summaries\" + patch][i] = text_dict[\"summary\"]\n if \"description\" in text_dict:\n self[item_fmg + \"Descriptions\" + patch][i] = text_dict[\"description\"]\n\n def find(self, search_string, replace_with=None, text_category=None, exclude_conversations=True):\n \"\"\"Search for the given text in the entire game.\n\n Args:\n search_string: Text to find. The text can appear anywhere inside an entry to return a result.\n replace_with: String to replace the given text with in any results. (Default: None)\n text_category: Name of text category (FMG) to search. If no category is given, all categories will be\n searched (except perhaps Subtitles; see below). (Default: None)\n exclude_conversations: If True, the Subtitles text category will not be searched when all categories are\n searched. (This category contains a lot of text, and you are unlikely to want to modify it, given how it\n lines up with the audio.) (Default: True)\n \"\"\"\n if text_category is None:\n dicts_to_search = (\n [(fmg_name, fmg_dict) for fmg_name, fmg_dict in self.categories.items() if fmg_name != \"Subtitles\"]\n if exclude_conversations\n else self.categories.items()\n )\n else:\n dicts_to_search = ((text_category, self[text_category]),)\n\n found_something = False\n for fmg_name, fmg_dict in dicts_to_search:\n for index, text in fmg_dict.items():\n if search_string in text:\n found_something = True\n print(f\"\\n~~~ {fmg_name}[{index}]:\\n{text}\")\n if replace_with is not None:\n fmg_dict[index] = text.replace(search_string, replace_with)\n print(f\"-> {fmg_dict[index]}\")\n if not found_something:\n print(f\"Could not find any occurrences of string {repr(search_string)}.\")\n\n def __iter__(self):\n return iter(self.categories.items())\n\n def __getitem__(self, text_category):\n try:\n return self.categories[text_category]\n except KeyError:\n raise AttributeError(f\"Non-existent text category (FMG): '{text_category}'\")\n\n def get_range(self, category, start, end):\n \"\"\"Get a list of (id, text) pairs from a certain range inside the ID-sorted text dictionary.\"\"\"\n return [\n (text_id, self.categories[category][text_id])\n for text_id in sorted(self.categories[category])[start:end]\n ]\n\n @staticmethod\n def resolve_item_type(item_type) -> str:\n if item_type.lower() in {\"good\", \"consumable\"}:\n return \"Good\"\n elif item_type.lower() in {\"ring\", \"accessory\"}:\n return \"Ring\"\n elif item_type.lower() in {\"weapon\", \"shield\"}:\n return \"Weapon\"\n elif item_type.lower() in {\"armour\", \"armor\", \"protector\"}:\n return \"Armor\"\n elif item_type.lower() == \"equipment\":\n raise ValueError(\"'equipment' is ambiguous. Did you mean 'weapon', 'armor', 'ring', or 'good'?\")\n elif item_type.lower() == \"item\":\n raise ValueError(\n \"'item' is ambiguous; it's the term used to describe everything in your inventory.\\n\"\n \"Did you mean 'weapon', 'armor', 'ring', or 'good'?\"\n )\n else:\n raise ValueError(f\"Unrecognized item type: '{item_type}'\")\n\n\n_CAN_MERGE_PATCH = {\n \"WeaponNamesPatch\",\n \"WeaponSummariesPatch\",\n \"WeaponDescriptionsPatch\",\n \"ArmorNamesPatch\",\n \"ArmorSummariesPatch\",\n \"ArmorDescriptionsPatch\",\n \"RingNamesPatch\",\n \"RingSummariesPatch\",\n \"RingDescriptionsPatch\",\n \"GoodNamesPatch\",\n \"GoodSummariesPatch\",\n \"GoodDescriptionsPatch\",\n \"SpellNamesPatch\",\n \"SpellDescriptionsPatch\",\n \"NPCNamesPatch\",\n \"PlaceNamesPatch\",\n}\n_CANNOT_MERGE_PATCH = {\n \"EventText\",\n \"MenuDialogs\",\n \"SoapstoneMessages\",\n \"MenuHelpSnippets\",\n \"KeyGuide\",\n \"MenuText_Other\",\n \"MenuText_Common\",\n}\n","sub_path":"soulstruct/base/text/msg_directory.py","file_name":"msg_directory.py","file_ext":"py","file_size_in_byte":13727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"652977227","text":"# -*- coding: utf-8 -*-\nimport xadmin\nfrom xadmin import views\nfrom blog import models as blog_models\n\n__author__ = 'xpizza'\n\n\nclass BaseSetting(object):\n enable_themes = True\n use_bootswatch = True\n\n\n# 全局设置\nclass GlobalSetting(object):\n # 设置base_site.html的Title\n site_title = '后台管理系统'\n # 设置base_site.html的FooterBannerAdminBannerAdmin\n site_footer = 'xpizza'\n # 设置菜单\n menu_style = \"accordion\"\n\n\nclass UserAdmin(object):\n list_display = ['id', 'name', 'password', 'email', 'blog_name', 'forget_question', 'forget_answer', 'img_url','image_tag', 'add_time']\n search_fields = ['name', 'blog_name']\n list_filter = ['id', 'name', 'password', 'email', 'blog_name', 'forget_question', 'forget_answer', 'add_time']\n\n\nclass ArticleTypeAdmin(object):\n list_display = ['name', 'user']\n search_fields = ['name']\n list_filter = ['name', 'user']\n\n\nclass ArticleAdmin(object):\n list_display = [\"id\", \"title\", \"author\", \"pub_time\", \"click_times\", \"recommended_times\", 'status']\n search_fields = [\"title\", \"click_times\", \"recommended_times\", 'status']\n list_filter = [\"id\", \"title\", \"author\", \"pub_time\", \"click_times\", \"recommended_times\", 'status']\n\n\nclass AdvertisementAdmin(object):\n list_display = ['id', 'name', 'image_tag', 'sort_key']\n search_fields = ['name', 'sort_key']\n list_filter =['id', 'name', 'sort_key']\n\n\nclass ConfigurationAdmin(object):\n list_display = ['key', 'val']\n search_fields = ['key', 'val']\n list_filter = ['key', 'val']\n\n\nclass ContractUsAdmin(object):\n list_display = ['key', 'val']\n search_fields = ['key', 'val']\n list_filter = ['key', 'val']\n\n\nclass DiscussAdmin(object):\n list_display = ['id', 'article', 'user', 'message']\n search_fields = ['message']\n list_filter = ['id', 'article', 'user', 'message']\n\n\nclass AccusationAdmin(object):\n list_display = ['id', 'article', 'user', 'content']\n search_fields = ['content']\n list_filter = ['id', 'article', 'user', 'content']\n\n\nclass RecommendRecordAdmin(object):\n list_display = ['article', 'user']\n\n\nxadmin.site.register(views.BaseAdminView, BaseSetting)\nxadmin.site.register(views.CommAdminView, GlobalSetting)\nxadmin.site.register(blog_models.user, UserAdmin)\nxadmin.site.register(blog_models.article_type, ArticleTypeAdmin)\nxadmin.site.register(blog_models.article, ArticleAdmin)\nxadmin.site.register(blog_models.discuss, DiscussAdmin)\nxadmin.site.register(blog_models.accusation, AccusationAdmin)\nxadmin.site.register(blog_models.advertisement, AdvertisementAdmin)\nxadmin.site.register(blog_models.configuration, ConfigurationAdmin)\nxadmin.site.register(blog_models.contract_us, ContractUsAdmin)\nxadmin.site.register(blog_models.recommended_record, RecommendRecordAdmin)","sub_path":"blog/adminx.py","file_name":"adminx.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"365630789","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 1 13:05:03 2020\n\n@author: Akihiro Yamaguchi\n\nGoals:\n * Plot the psychometric curve of previous response + correctness.\n * See/Check if there's any behavioral pattern that we can find.\n\"\"\"\nimport os\nimport functions_get_ as fun\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Load data (run functions in 'main_behavior_analysis.py')\nfname = [] # initialize the list\nfname = fun.load_names()\nprint(fname)\n\nsrcdir = os.getcwd()\nprint('Current directory is...', srcdir)\n\n# ====================== Lost Stuff ======================\nalldat = np.array([])\nfor j in range(len(fname)):\n alldat = np.hstack((alldat, np.load('steinmetz_part%d.npz'%j, allow_pickle=True)['dat']))\n\n# =========== Get data for one selected session ===========\nn_session = 11\ndat, barea, NN, regions, brain_groups, nareas = fun.load_data(n_session, alldat) \n_, _, cont_diff, _, _, _ = fun.get_task_difference(n_session, dat)\n\n# ====================== Compute Stuff ======================\n# % rightward at each contrast difference for all trials (no history)\nrightward = fun.get_rightward(dat, cont_diff) \n\n# check the contrast differences and the number of occurences\nunique, counts = np.unique(cont_diff, return_counts=True) \nprint('Contrast difference and no. of trials:')\nfor i,val in enumerate(unique): print(val, ':', counts[i])\n\n# ==================== Analysis ====================\n\nright_levels, n_trials = fun.get_correctness(dat, cont_diff)\nimport functions_plot_ as fun_plt\n\nfun_plt.plot_correctness(dat, right_levels, cont_diff, n_trials, n_session, saveplot=False)\n\n# Loop Over All the Sessions\nfor i in range(39):\n n_session = i\n dat, barea, NN, regions, brain_groups, nareas = fun.load_data(n_session, alldat) \n _, _, cont_diff, _, _, _ = fun.get_task_difference(n_session, dat) \n right_levels, n_trials = fun.get_correctness(dat, cont_diff)\n # fun_plt.plot_correctness(dat, right_levels, cont_diff, n_trials, n_session, saveplot=False)\n\n","sub_path":"NMA_Project/resp_correctness.py","file_name":"resp_correctness.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"472386851","text":"import os.path\nimport numpy as np\nfrom argparse import ArgumentParser\nfrom collections import Counter\nfrom itertools import chain\nfrom typing import Dict, Tuple, Iterable, Any\n\nfrom utils.data_writer import DataWriter\nfrom utils.constants import INPUTS, OUTPUT, SAMPLE_ID, TIMESTAMP\n\n\ndef load_labels(path: str) -> Dict[Tuple[int, int], int]:\n with open(path, 'r') as label_file:\n label_dict = dict()\n\n for line in label_file:\n tokens = line.split(',')\n\n start, end = int(tokens[0].strip()), int(tokens[1].strip())\n label = int(tokens[2].strip())\n label_dict[(start, end)] = label\n\n return label_dict\n\n\ndef get_label(timestamp: int, label_dict: Dict[Tuple[int, int], int]) -> Tuple[Tuple[int, int], int]:\n for time_range, label in label_dict.items():\n if timestamp >= time_range[0] and timestamp <= time_range[1]:\n return time_range, label\n return None, None\n\n\ndef get_data_generator(input_path: str, window: int, reps: int, label_dict: Dict[Tuple[int, int], int]) -> Iterable[Dict[str, Any]]:\n with open(input_path, 'r') as input_file:\n \n data_window: List[List[float]] = []\n \n current_timestamp = None\n label = None\n\n for i, line in enumerate(input_file):\n if i == 0:\n continue\n\n tokens = line.split(',')\n\n timestamp = int(tokens[0].strip())\n features = [float(t.strip()) for t in tokens[1:]]\n\n if current_timestamp is None or timestamp <= current_timestamp[0] or timestamp >= current_timestamp[1]:\n if len(data_window) >= window:\n indices = list(range(len(data_window)))\n seen = set()\n\n for _ in range(reps):\n sampled_indices = np.sort(np.random.choice(indices, size=window, replace=False))\n\n # Remove duplicates\n sampled_indices_str = ','.join(map(str, sampled_indices))\n if sampled_indices_str in seen:\n continue\n\n seen.add(sampled_indices_str)\n\n sampled_features = [data_window[i] for i in sampled_indices]\n\n sample_dict = {\n INPUTS: sampled_features,\n OUTPUT: label,\n TIMESTAMP: timestamp\n }\n yield sample_dict\n\n data_window = []\n current_timestamp, label = get_label(timestamp, label_dict)\n\n data_window.append(features)\n\n\ndef tokenize_dataset(input_folder: str,\n output_folder: str,\n window: int,\n reps: int,\n chunk_size: int,\n label_one_dict: Dict[Tuple[int, int], int],\n label_two_dict: Dict[Tuple[int, int], int]):\n\n smartwatch_generator_one = get_data_generator(os.path.join(input_folder, 'measure1_smartwatch_sens.csv'), window, reps, label_one_dict)\n smartwatch_generator_two = get_data_generator(os.path.join(input_folder, 'measure2_smartwatch_sens.csv'), window, reps, label_two_dict)\n\n smartphone_generator_one = get_data_generator(os.path.join(input_folder, 'measure1_smartphone_sens.csv'), window, reps, label_one_dict)\n smartphone_generator_two = get_data_generator(os.path.join(input_folder, 'measure2_smartphone_sens.csv'), window, reps, label_one_dict)\n\n data_generator = chain(smartwatch_generator_one, smartwatch_generator_two, smartphone_generator_one, smartphone_generator_two)\n\n label_distribution: Counter = Counter()\n\n with DataWriter(output_folder, file_prefix='data', file_suffix='jsonl.gz', chunk_size=chunk_size) as writer:\n sample_id = 0\n for sample in data_generator:\n sample[SAMPLE_ID] = sample_id\n label_distribution[sample[OUTPUT]] += 1\n\n writer.add(sample)\n\n sample_id += 1\n\n if sample_id % chunk_size == 0:\n print('Completed {0} samples.'.format(sample_id), end='\\r')\n\n print()\n print('Total: {0}'.format(sample_id))\n print(label_distribution)\n\n# with DataWriter(output_folder, file_prefix='data', chunk_size=chunk_size, file_suffix='jsonl.gz') as writer:\n \n\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument('--input-folder', type=str, required=True)\n parser.add_argument('--output-folder', type=str, required=True)\n parser.add_argument('--window', type=int, required=True)\n parser.add_argument('--reps', type=int, required=True)\n parser.add_argument('--chunk-size', type=int, default=10000)\n args = parser.parse_args()\n\n assert os.path.exists(args.input_folder), 'The folder {0} does not exist!'.format(args.input_folder)\n\n label_one_dict = load_labels(os.path.join(args.input_folder, 'measure1_timestamp_id.csv'))\n label_two_dict = load_labels(os.path.join(args.input_folder, 'measure2_timestamp_id.csv'))\n\n tokenize_dataset(input_folder=args.input_folder,\n output_folder=args.output_folder,\n window=args.window,\n reps=args.reps,\n chunk_size=args.chunk_size,\n label_one_dict=label_one_dict,\n label_two_dict=label_two_dict)\n\n","sub_path":"src/data_generation/localization/tokenize_localization.py","file_name":"tokenize_localization.py","file_ext":"py","file_size_in_byte":5428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"37003531","text":"from typing import Optional\n\nfrom bson import DBRef\nfrom singleton_decorator import singleton\n\nfrom uwclouddb.models.be import *\nfrom uwclouddb.models.fp import BeFloorplanDoc\nfrom uwclouddb.models.me import MeReleaseDoc\nfrom uwclouddb.models.projects import ReleaseTag, CoreId\n\n\n@singleton\nclass UnwCloudDb:\n\n dbref2queryset = {\n 'project_structure_doc': lambda **kwargs: BeStageDoc.objects(**kwargs),\n\n 'me_release_doc': lambda **kwargs: MeReleaseDoc.objects(**kwargs),\n\n 'be_release_doc': lambda **kwargs: BeReleaseDoc.objects(**kwargs),\n 'be_floorplan_doc': lambda **kwargs: BeFloorplanDoc.objects(**kwargs),\n 'be_stage_doc': lambda **kwargs: BeStageDoc.objects(**kwargs),\n 'be_stage_snapshots_doc': lambda **kwargs: BeStageDoc.objects(**kwargs),\n }\n\n def __init__(self):\n self._project = None # current project\n\n @property\n def project(self): return self._project\n\n @project.setter\n def project(self, value): self._project = value\n\n #-----------------------------------------------------\n def _deref(self, dbref, **kwargs):\n if isinstance(dbref, str):\n return self.dbref2queryset[dbref](**kwargs)\n elif isinstance(dbref, DBRef):\n return self.dbref2queryset[dbref.collection](id=dbref.id, **kwargs)\n else:\n return dbref\n\n #-----------------------------------------------------\n def me_release_doc(self, name, **kwargs) -> MeReleaseDoc:\n me = self._deref('me_release_doc')(relname=name, **kwargs)\n\n if me.count(): return me.first()\n\n me = MeReleaseDoc(relname=name)\n me.save()\n\n return me\n\n #-----------------------------------------------------\n # noinspection PyMethodMayBeStatic\n def be_release_doc(self, core_id: CoreId, release, create:bool = False, **kwargs) -> Optional[BeReleaseDoc]:\n\n relname = release.name if isinstance(release, ReleaseTag) else release\n\n be = BeReleaseDoc.objects(project=core_id.project, core= core_id.core, relname=relname, **kwargs)\n\n if be.count(): return be.first()\n\n if create:\n be = BeReleaseDoc(project=core_id.project, core= core_id.core, relname=relname)\n be.save()\n return be\n\n return None\n\n #-----------------------------------------------------\n def be_floorplan_doc(self, core: CoreId, release: str, **kwargs) -> Optional[BeReleaseDoc]:\n relname = release.name if isinstance(release, ReleaseTag) else release\n\n fp = self._deref('be_floorplan_doc')(project=core.project, core= core.core, relname=relname, **kwargs)\n\n if fp.count(): return fp.first()\n\n return None\n\n #-----------------------------------------------------\n def be_stage_doc(self, core: CoreId, release, stage : STAGE) -> BeStageDoc:\n relname = release.name if isinstance(release, ReleaseTag) else release\n\n return self._deref('be_stage_doc')(project=core.project, core= core.core,\n relname=relname, name=stage.value).first()\n","sub_path":"server_flask/uwclouddb/query/q_be_data.py","file_name":"q_be_data.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"187521985","text":"__author__ = \"Rafael Arquero Gimeno\"\n\nfrom model import *\nimport view\nimport parserLastFM\n\n\ndef add(parser):\n \"\"\"\n :param parser: File parser\n :return: A Binary Search Tree containing old + parsed values\n \"\"\"\n return parser.next()\n\n\ndef search(tree, minimum=0.0, maximum=1.0):\n \"\"\"Returns an iterator that returns values inside the interval in the given tree\n :rtype : generator\n :param tree: Original Tree\n :param minimum: lower bound\n :param maximum: higher bound\n \"\"\"\n assert 0 <= minimum <= 1\n assert 0 <= maximum <= 1\n assert minimum <= maximum\n\n # tree is passed by reference, clone is done to safely operate through tree\n result = ABB().clone(tree).deleteLower(minimum).deleteHigher(maximum)\n\n return None if result.isEmpty() else result.inOrder(endless=True)\n\n\ndef remove(tree, minimum=0.0, maximum=1.0):\n \"\"\"Returns a tree with with the values of given tree if they are out of given interval\"\"\"\n assert 0 <= minimum <= 1\n assert 0 <= maximum <= 1\n assert minimum <= maximum\n\n lowers, highers = ABB().clone(tree).deleteHigher(minimum), ABB().clone(tree).deleteLower(maximum)\n\n root = highers.min() # the lowest of highers, can be the root\n highers.delete(root, wholeNode=True)\n\n result = ABB().insert(root)\n result.root.left = lowers.root\n result.root.right = highers.root\n\n return result\n\n\ndef initParser(filename):\n \"\"\"Returns a parser ready for retrieve users from given file\"\"\"\n return parserLastFM.parser(filename, ABB())\n\n\nif __name__ == \"__main__\":\n\n users = ABB()\n parser = initParser('LastFM_small.dat')\n\n app = view.MainApp(parser, add, search, remove, users)\n app.mainloop()\n","sub_path":"RafaelArqueroGimeno_S5/ABBInterface.py","file_name":"ABBInterface.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"298076166","text":"\"\"\"\nYou are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string \n(not necessarily different) and swap the characters at these indices.\n\nReturn true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings.\nOtherwise, return false.\n\n \nExample 1:\n\nInput: s1 = \"bank\", s2 = \"kanb\"\nOutput: true\nExplanation: For example, swap the first character with the last character of s2 to make \"bank\".\nExample 2:\n\nInput: s1 = \"attack\", s2 = \"defend\"\nOutput: false\nExplanation: It is impossible to make them equal with one string swap.\nExample 3:\n\nInput: s1 = \"kelb\", s2 = \"kelb\"\nOutput: true\nExplanation: The two strings are already equal, so no string swap operation is required.\n \n\"\"\"\n\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n \n if len(s1) != len(s2):\n return False\n \n if s1 == s2:\n return True\n\n A = []\n B = []\n \n \n for i in range(len(s1)):\n\n # if the characte is differenr\n if s1[i] != s2[i]:\n\n A.append(s1[i])\n B.append(s2[i])\n\n if len(A) == len(B) == 2:\n\n if A[0] == A[1] and B[0] == B[1]:\n return True\n \n return False\n \n\n\n\ntest = Solution()\n\nprint(test.areAlmostEqual(\"hello\", \"hlelo\"))","sub_path":"all_programs/mixed/014-check-if-one-string-swap-can-make-strings-equal.py","file_name":"014-check-if-one-string-swap-can-make-strings-equal.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"516966634","text":"#frame.number;frame.time;ip.src;tcp.srcport;ip.dst;tcp.dstport;ip.proto;ip.len;Proto;Info\n\n#--------- Incomplete 'find most common IP' - add numbers together and print them for each line\n#This program is somewhat 'hard coded' for a certain kind of log, but it could be changed to work for\n#many other types of log is an IP check is added, and used to 'scan' the first line for which arguments\n#would contain IPs. Might need to add another argument for specifying if client or server IP comes first\n#to use the second function.. but then I could easily have it scan for the most common host IP too!\n\n# IMPORT NECESSARY LIBRARIES\nimport sys\n\n#!/usr/bin/env python3\n\n#-----CREATE HELPER FUNCTIONS-----\n\ndef findMostCommonIP(log):\n# open the file used in command\n file = open(log, 'r');\n#set variable for the lines in file\n chars = file.read();\n#create dictionary for each IP with their counts as keys\n IPList = {};\n#set string for the current argument in line, starting with 0\n arg = 0;\n#set current IP for appending up to the next semicolon.\n currentIP = \"\";\n#for each character in 'lines'\n for i in chars:\n#check for semi colons, skip each character until one is reached #Deleted for now, redundant\n# if i == \";\":\n#when a semi colon is found, add +1 to arg(current argument) #Deleted for now, redundant\n# arg+=1;\n#if arg is the counting arguement(0)\n# if arg==0:\n#print that count\n# print(i)\n#If arg equals a source or destination IP argument\n if arg==2 or arg==4:\n#check if the character is a semi colon\n if i == \";\":\n#If character is a semi colon, check if currentIP doesn't match an existing key(is not in the dictionary) #Ideally, I woulc check if current IP matches IP format here, but those have a LOT of rules to consider..\n if IPList.get(currentIP)==None:\n# print(\"New IP Found: \"+currentIP);\n#If currentIP does not match a key, create a new one and add 1 to its value\n IPList[currentIP] = 1\n#If currentIP does match a key, set the value of that key +1\n else:\n IPList[currentIP] = (IPList.get(currentIP)+1);\n# value = IPList.get(currentIP)\n# value+=1\n# IPList[currentIP] = value\n# print(\"+1 Existing IP: \"+currentIP);\n#after the key has been added, set currentIP back to \"\"\n currentIP=\"\";\n#At the end of semicolon True=yes function, arg+=1\n arg+=1;\n#If character is not a semicolon, concatinate it to currentIP\n else:\n currentIP=(currentIP+str(i));\n# print(\"Current IP: \"+currentIP);\n#else if character is a semi colon\n elif i == \";\":\n#set arg +1\n arg+=1;\n#else if current character is a newline(other 'unimportant' characters are ignored)\n elif i == '\\n' or i == '\\r\\n':\n#set arg to zero\n arg = 0;\n#other 'unimportant' characters skip resetting the currentIP\n# else:\n# continue\n#print the most common IP in IPList, which I think is possible with max and get\n mostCommonIP = max(IPList, key=IPList.get)\n#now print that value and the IP sorted(IPList.items[0])\n print(\"Most Common IP: \"+str(mostCommonIP)+\" Count: \"+str(IPList.get(mostCommonIP)))\n\n\n\ndef findMostCommonClientIP(log):\n# open the file used in command\n file = open(log, 'r');\n#set variable for the lines in file\n lines = file.readlines();\n#create dictionary for each IP with their counts as keys\n IPList = {};\n#set string for the current argument in line, starting with 0\n arg = 0;\n#set current IP for appending up to the next semicolon.\n currentIP = \"\";\n#set counter for checking packet type(request or response)\n checkCounter = 0;\n#for each line in 'lines'\n for line in lines:\n#set variable for current line\n currentLine = line;\n#for each character in 'line'\n for i in currentLine:\n#if arg is the counting arguement(0)\n# if arg==0:\n#print the character count for checking for packet type(and/or other variables)\n# print(\"char: \":i)\n# print(\"Argument: \"+str(arg));\n# print(\"Counter: \"+str(checkCounter));\n# print(\"Current IP: \"+currentIP);\n#if arg equals the packet type arguement 8\n if arg==9:\n#If checkCounter equals 2 is also true(its the divergent character in the log) and it equals q\n if checkCounter==2 and i==\"q\":\n#Take the saved IP and check if currentIP doesn't match an existing key(is not in the dictionary) #Ideally, I would check if current IP matches IP format here, but those have a LOT of rules to consider..\n if IPList.get(currentIP)==None:\n# print(\"New IP Found: \"+currentIP);\n#If currentIP does not match a key, create a new one and add 1 to its value\n IPList[currentIP] = 1\n#If currentIP does match a key, set the value of that key +1\n else:\n IPList[currentIP] = (IPList.get(currentIP)+1);\n# value = IPList.get(currentIP)\n# value+=1\n# IPList[currentIP] = value\n# print(\"+1 Existing IP: \"+currentIP);\n#if checkCounter equals 2, but i does not equal q, break out of line.\n# elif checkCounter > 2:\n# checkCounter = 0;\n# break\n#if checkCounter is less than 2, add 1 to checkCounter to get to the correct character.\n elif checkCounter<2:\n checkCounter+=1;\n#If arg equals the source IP argument\n if arg==2:\n#check if the character is a semi colon\n if i == \";\":\n#If character is a semi colon, arg+=1\n arg+=1;\n#If character is not a semicolon, concatinate it to currentIP\n else:\n currentIP=(currentIP+str(i));\n#else if character is a semi colon\n elif i == \";\":\n#set arg +1\n arg+=1;\n#else if current character is a newline(other 'unimportant' characters are ignored)\n elif i == '\\n' or i == '\\r\\n':\n#set arg to zero\n arg = 0;\n#after the line has ended, set currentIP back to \"\" and checkCounter to 0\n currentIP=\"\";\n checkCounter = 0\n#other 'unimportant' characters skip resetting the currentIP\n# else:\n# continue\n#print the most common Client IP in IPList and its count, not including responses sent by a server.\n mostCommonIP = max(IPList, key=IPList.get)\n#now print that value and the IP sorted(IPList.items[0])\n print(\"Most Common Client IP: \"+str(mostCommonIP)+\" Count: \"+str(IPList.get(mostCommonIP)))\n\n\n\n#-----CREATE A MAIN FUNCTION TO CALL HELPER FUNCTIONS-----\ndef main(args):\n #check if looking for any most common IP, or only clients.\n if (sys.argv[1] == \"any\"):\n #call the correct helper function\n findMostCommonIP(args);\n elif (sys.argv[1] == \"client\"):\n #call the correct helper function\n findMostCommonClientIP(args);\n else:\n #end script early and give the user an error message if format is incorrect.\n print(\"Please use this format: ./commonIP (client/any) (file name) [verbose] \");\n\n\n#-----CHECK TO SEE IF THIS SCRIPT IS THE MAIN SCRIPT-----\nif __name__ == '__main__':\n if 3>len(sys.argv)>1:\n if sys.argv[1] == --help:\n print(\"./commonIP (client/any) (file name) [verbose]\")\n print(\"verbose will display every time a new IP is found, or an existing one is added.\")\n print(\"'any' option will find all instances of an IP in a log.\")\n print(\"'client' option will ONLY count packets where a client makes a request, NOT responses.\")\n elif (len(sys.argv)<3):\n#end script early and give the user an error message if format is incorrect.\n print(\"Please use this format: ./commonIP (client/any) (file name) [verbose]\");\n \n else:\n arg_list = sys.argv[2] # adjust this for the number of args you need sys.argv[-2:] would take the last two.\n main(arg_list) # call your main function","sub_path":"CommonIP.py","file_name":"CommonIP.py","file_ext":"py","file_size_in_byte":8170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"542115201","text":"#!/usr/bin/env python\n\"\"\"\nScript Header\n\n$Id: US22891\n\nCopyright (c) 2016-2017 Cisco Systems, Inc.\n\nName:\n cmCC22891_3pcc_BS_IOT_Interop_32_reInvite_Without_SDP.py\n\nPurpose:\n Test verifies DUT responds to a re-invite without SDP by sending OFFER\n SDP in 200 OK. The DUT must send OFFER SDP (with a list of all supporting\n codecs in response to a re-INVITE without SDP.\n\nAuthor:\n Anuradha N (anakre@cisco.com)\n\nReferences:\n BW-SIPPhone-InteropTestPlan-R21.0\n\nDescription:\n Originate a call from a BroadWorks User A to BroadWorks User B. Do not\n answer the call. From the DUT dial the call pick up feature access code (\n *98) to pick up the call.\n\nTopology:\n 1. 3 3pcc phones\n 2. All the phones should register successfully before running script\n 3. Assign the call pick up service to the BroadWorks group.\n 4. Creat a call pick up group and assign the DUT, Broadworks User A and B\n to the call pick up group.\n\nPass/Fail Criteria:\n - The SDP in the 200 OK should contain all of the supported and enabled\n codecs.\n - The version in the o-line must be incremented\n\nTest Steps:\n 1. Phone B calls Phone C. Do not answer the call.\n 2. Phone A (DUT) dials *98 to initiate call pick up.\n\n Verify:\n 1. Phone B receives audible ringback and Phone C is alerted\n 2. DUT dials *98 to pickup the call.\n 3. Call is connected and two-way voice path is established between DUT\n and Phone B.\n\n 4. Verify the Signaling to the DUT:\n - Inspect the SDP in 200 OK from DUT in response to re-INVITE without\n SDP from BroadWorks.\n - SDP must contain all of the DUT's enabled and supported codecs.\n - The version in the o-line must be incremented.\n\n Notes:\n\n Known Bugs:\n\"\"\"\n\nimport tng\nimport logging\nfrom tng_sl.device.endpoint.synergylite.synergylite_3pcc_extended \\\n import wait_for_ccapi_call_states\nfrom tng.frontend.timing import wait\nfrom tng_sl.contrib.mpp.phone_line_reg_helper import PhoneLineRegHelper\nfrom tng_sl.contrib.mpp.phone_line_reg_helper import PhoneConfigHelper\nfrom tng_sl.contrib.mpp.tshark_helper import TsharkHelper\nfrom tng_sl.contrib.mpp.broadsoft_login_helper import BroadsoftLoginHelper\nfrom tng_sl.contrib.setup_helper import SetupHelpersTestCase\n\nlog = logging.getLogger('CodecNegotiationReInviteWithoutSDP')\n\n\nclass CodecNegotiationReInviteWithoutSDP(\n SetupHelpersTestCase, tng.api.TestCase):\n helpers = (\n PhoneConfigHelper, PhoneLineRegHelper, TsharkHelper,\n BroadsoftLoginHelper)\n helper_num_devices = 3\n\n def setUp(self):\n log.info(\"Start of setUp method\")\n\n self.serverproxy = self.toolkit.get_test_env_info(\n section='bsoft', parameter_name=\"as_ip_addr\")\n self.call_pickup_group = self.bsoft_web.create_callpickup_group(\n [self.user_id2, self.user_id3, self.user_id1])\n\n def broadsoft_delete_callpickup_group():\n self.bsoft_web.delete_callpickup_group(self.call_pickup_group)\n self.addCleanup(broadsoft_delete_callpickup_group)\n\n log.info(\"End of setUp method\")\n\n def test_Codec_Negotiation_re_Invite_Without_SDP(self):\n log.info(\"Start of test_Codec_Negotiation_re_Invite_Without_SDP\")\n\n log.info('Set use preffered codec only to \"No')\n self.oPhone1.ui.set_web_parameter_http(\n Use_Pref_Codec=['Ext 1', 'Use Pref Codec Only', 0])\n\n use_pref_codec = self.oPhone1.ui.get_web_parameter_http(\n 'Ext 1', 'Use Pref Codec Only')\n self.assertEqual(\"0\", str(use_pref_codec))\n\n log.info('Start tshark on linux')\n dut_ip = self.oPhone1.ip\n filter_cmd = 'port sip and host {}'.format(dut_ip)\n capture_file = self.tshark.tshark_start(filter_cmd)\n\n log.info(\"PhoneB dials PhoneC's number: {}\".format(self.user_id3))\n self.oPhone2.ccapi.dial('null', self.user_id3, '', 1, 0, 1)\n # check phoneB ringout status and PhoneC ringing status\n wait_for_ccapi_call_states(\n self.devices, (\"IDLE\", \"PROCEEDING\", \"RINGING\"), timeout=20)\n wait(5, 'Wait before initiating the call pick up')\n\n log.info(\"PhoneA dials call pickup access code\")\n self.oPhone1.ccapi.dial('null', '*98', '', 1, 0, 1)\n # check phoneA and phoneB's status are connected\n wait_for_ccapi_call_states(\n self.devices, (\"CONNECTED\", \"CONNECTED\", \"IDLE\"), timeout=20)\n\n log.info(\"PhoneA disconnects the call\")\n self.oPhone1.ccapi.hangUp('0000')\n # check phoneA and phoneB's status are idle\n wait_for_ccapi_call_states(self.devices, (\"IDLE\", \"IDLE\", \"IDLE\"))\n\n self.tshark.tshark_stop()\n\n # analyse tshark capture\n log.info(\"Starting Tshark analysis\")\n log.info(\"Get CSeq and Call-ID from INVITE\")\n\n cseq, call_id = self.tshark.tshark_get_message_cseq_call_id(\n capture_file, \"Request: INVITE\", self.serverproxy, dut_ip)\n\n log.info(\"Check if 200 OK is sent for re-invite from server\")\n self.tshark.tshark_verify_message_and_response_with_invite_txn(\n capture_file, 'Request: INVITE', self.serverproxy, dut_ip,\n call_id, check_indialog=True)\n\n log.info(\"Verify if 200OK message contains all enabled codecs of DUT\")\n codecs = [\n ('G729a Enable', 'rtpmap:18 G729a'),\n ('G722 Enable', 'rtpmap:9 G722'),\n ('OPUS Enable', 'rtpmap:99 OPUS'),\n ('iLBC Enable', 'rtpmap:97 iLBC'),\n ('G722.2 Enable', 'rtpmap:96 AMR-WB'),\n ('G711u Enable', 'rtpmap:0 PCMU/8000'),\n ('G711a Enable', 'rtpmap:8 PCMA/8000')]\n for web_codec, shark_str in codecs:\n codec_status = self.oPhone1.ui.get_web_parameter_http(\n 'Ext 1', web_codec)\n log.info(\"checking {} Codec status: {}\".format(\n web_codec.split()[0], codec_status))\n if int(codec_status):\n self.tshark.tshark_check_string_in_message(\n capture_file, 'Status: 200 OK', shark_str, dut_ip,\n self.serverproxy, cseq, call_id)\n\n log.info(\"Verified traces for CodecNegotiationReInviteWithoutSDP\")\n log.info(\"Tshark analysis stopped\")\n\n log.info(\"End of test_Codec_Negotiation_re_Invite_Without_SDP\")\n\n\n# this is called by 'tng run'\ndef main():\n tng.api.runner()\n\nif __name__ == '__main__':\n tng.run(main)\n","sub_path":"common/IOT/Broadsoft_Interop/section_5/cc_basic/cmCC22891_3pcc_BS_IOT_Interop_32_reInvite_Without_SDP.py","file_name":"cmCC22891_3pcc_BS_IOT_Interop_32_reInvite_Without_SDP.py","file_ext":"py","file_size_in_byte":6411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"644618867","text":"from __future__ import division\n# CS434\n# Final Project\n# Tao Chen\n# this is the file that contains the Data class and all its methods\nimport csv\nfrom helper import wordsToLists\nfrom features_generator import differenceInNumOfWord\nfrom features_generator import wordRatio\nfrom features_generator import sameOverUnique\nfrom features_generator import calSignificance\nfrom features_generator import significanceRatio\nfrom helper import lookForSameWords\nfrom helper import lookForUniqueWords\n\n# A class that refers to the pre-processed raw data\nclass Data:\n def __init__(self, fileName, limit):\n self.__readFile(fileName, limit)\n self.__toLowerCase()\n self.__toLists()\n\n def __readFile(self, fileName, limit):\n openFile = open(fileName, 'r')\n readCSV = csv.reader(openFile, delimiter=',')\n self.__rawData = []\n\n currentAmount = 0\n for row in readCSV:\n if currentAmount > limit:\n break\n self.__rawData.append(row)\n currentAmount = currentAmount + 1\n\n # remove the headings\n self.__rawData.pop(0)\n # convert ids and labels to numbers instead of strings\n for row in self.__rawData:\n row[0] = int(row[0])\n row[1] = int(row[1])\n row[2] = int(row[2])\n row[5] = int(row[5])\n\n # convert all letters to lower case\n def __toLowerCase(self):\n for row in self.__rawData:\n row[3] = row[3].lower()\n row[4] = row[4].lower()\n\n # make the questions into lists of words while\n # removing punctuations\n def __toLists(self):\n for row in self.__rawData:\n row[3] = wordsToLists(row[3])\n row[4] = wordsToLists(row[4])\n\n def getRawData(self):\n return self.__rawData\n\n def generateFeatures(self, dictionary):\n featureTable = []\n index = 0\n for row in self.__rawData:\n featureTable.append([])\n # label\n featureTable[index].append(row[5])\n # first feature: difference in number of words\n featureTable[index].append(differenceInNumOfWord(row[3], row[4]))\n\n sameWords = lookForSameWords(row[3], row[4])\n uniqueWords = lookForUniqueWords(row[3], row[4], sameWords)\n totalWords = len(row[3]) + len(row[4])\n # second feature: ratio between number of same words and\n # total number of words in the two sentences\n featureTable[index].append(wordRatio(sameWords, totalWords))\n # third feature: ratio between number of unique words and\n # total number of words in the two sentences\n featureTable[index].append(wordRatio(uniqueWords, totalWords))\n # forth feature: ratio between # of same word and # of unique words\n featureTable[index].append(sameOverUnique(sameWords, uniqueWords))\n # fith feature: sum of the significance of all the same words over\n # total significance of the pair\n # sixth feature: sum of the significance of all the unique words over\n # total significance of the pair\n fifthFeature, sixthFeature = calSignificance(sameWords, uniqueWords, dictionary)\n featureTable[index].append(fifthFeature)\n featureTable[index].append(sixthFeature)\n # seventh feature: ration in same-word and unique-word significance\n featureTable[index].append(significanceRatio(fifthFeature, sixthFeature))\n # increment index\n index += 1\n return featureTable\n","sub_path":"Data.py","file_name":"Data.py","file_ext":"py","file_size_in_byte":3605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"455981677","text":"import urllib2\nimport urllib\nfrom twilio.rest import TwilioRestClient\n\ndef send_sms(message, number):\n message = message\n account_sid = \"AC385bd57fd90621e58f6d146d7c00844f\"\n auth_token = \"58809a0c9c074750a99d6e4046891d97\"\n client = TwilioRestClient(account_sid, auth_token)\n\n try:\n message = client.sms.messages.create(to=\"+91\" + number, from_=\"+19156006069\", body=message)\n except:\n return False\n else:\n return message","sub_path":"pscexams/sms.py","file_name":"sms.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"499091856","text":"# -*- coding: utf-8 -*-\nfrom www.shortcuts import *\n\n\nclass SpaceStat(UserHandler):\n rule = Rule('/space/')\n def get(self):\n user = self.request.user\n used_space = (user.getUsedSpace() or 0) / (1024 * 1024 * 1024.)\n left_space = user.space - used_space\n rate = int(used_space * 100 / user.space)\n tmpl = env.get_template('stat_space.html')\n return Response(tmpl.render(\n request = self.request,\n active = 'space',\n used_space = used_space,\n left_space = left_space,\n rate = rate,\n ))\n\n","sub_path":"FrameWork/www/views/space.py","file_name":"space.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"110714379","text":"n = int(input('Digite um número inteiro: '))\n\nanterior = n % 10\nn = n // 10\nvizinho_igual = False\n\nwhile n > 0 and not vizinho_igual:\n atual = n % 10\n if atual == anterior:\n vizinho_igual = True\n \n anterior = atual\n n = n // 10\n\nif vizinho_igual:\n print('sim')\nelse:\n print('não')\n\n\n","sub_path":"USP_Exercicios_Semana4/Exercicios_Adcionais/Ex2_NumeroAdjacente.py","file_name":"Ex2_NumeroAdjacente.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"266860501","text":"import matplotlib.pyplot as plt\nimport requests\n\n\ndef marital_status():\n data = requests.get('http://127.0.0.1:5002/marital_statuses').json()\n labels = data.keys()\n sizes = []\n for label in labels:\n sizes.append(data[label])\n colors = ['gold', 'yellowgreen']\n explode = (0.1, 0) \n\n plt.pie(sizes, explode=explode, labels=labels, colors=colors,\n autopct='%1.1f%%', shadow=True, startangle=140)\n\n plt.title(\"Marital Status of Patients\")\n plt.axis('equal')\n plt.savefig('MaritalStatus.png')\n plt.cla()\n\ndef birth_decades():\n labels = []\n data_male = requests.get('http://127.0.0.1:5002/birth_decades_male').json()\n data_female = requests.get('http://127.0.0.1:5002/birth_decades_female').json()\n\n for decade in data_male.keys():\n labels.append(decade)\n for decade in data_female.keys():\n if decade not in labels:\n labels.append(decade)\n\n labels.sort()\n male_means = []\n female_means = []\n\n for decade in labels:\n male_means.append(data_male[decade])\n female_means.append(data_female[decade])\n\n width = 0.35 \n fig, ax = plt.subplots()\n plt.bar(labels, male_means, width, label='Men')\n plt.bar(labels, female_means, width, bottom=male_means, label='Women')\n\n plt.ylabel('Number of Patient Births')\n plt.xlabel('Decade')\n plt.title('Number of Patient Births in Each Decade')\n plt.legend()\n plt.savefig(\"BirthDecades.png\")\n plt.cla()\n\n\n\ndef languages():\n data = requests.get('http://127.0.0.1:5002/languages').json()\n labels = []\n for lang in data.keys():\n labels.append(lang)\n\n values = []\n for lang in labels:\n values.append(data[lang])\n\n quick_sort(values, labels)\n labels = labels[:5]\n values = values[:5]\n\n plt.bar(labels, values, align='center', alpha=0.5)\n plt.ylabel('Number of Patients')\n plt.xlabel('Language')\n plt.title('Top 5 Languages Spoken by Patients')\n plt.savefig(\"Languages.png\")\n plt.cla()\n \n\ndef partition(array, begin, end, array2):\n pivot_idx = begin\n for i in range(begin+1, end+1):\n if array[i] >= array[begin]:\n pivot_idx += 1\n array[i], array[pivot_idx] = array[pivot_idx], array[i]\n array2[i], array2[pivot_idx] = array2[pivot_idx], array2[i]\n array[pivot_idx], array[begin] = array[begin], array[pivot_idx]\n array2[pivot_idx], array2[begin] = array2[begin], array2[pivot_idx]\n return pivot_idx\n\ndef quick_sort_recursion(array, begin, end, array2):\n if begin >= end:\n return\n pivot_idx = partition(array, begin, end, array2)\n quick_sort_recursion(array, begin, pivot_idx-1, array2)\n quick_sort_recursion(array, pivot_idx+1, end, array2)\n\ndef quick_sort(array, array2, begin=0, end=None):\n if end is None:\n end = len(array) - 1\n \n return quick_sort_recursion(array, begin, end, array2)\n\nmarital_status()\nbirth_decades()\nlanguages()\n\n\n","sub_path":"ReportGraphs.py","file_name":"ReportGraphs.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"386733787","text":"import cProfile, pstats, io\nprofile = cProfile.Profile()\nprofile.enable()\n\nimport profilethis\n\nprofile.disable()\ns = io.StringIO()\nsortby = 'tottime'\nps = pstats.Stats(profile, stream=s).sort_stats(sortby)\nps.print_stats(20)\nprint(s.getvalue())\n","sub_path":"Python/src/_mytime.py","file_name":"_mytime.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"403813861","text":"# -*- coding: utf-8 -*-\n#\n# pnnl-buildingid: buildingid/v1.py\n#\n# Copyright (c) 2018, Battelle Memorial Institute\n# All rights reserved.\n#\n# See LICENSE.txt and WARRANTY.txt for details.\n\nfrom .context import openlocationcode\n\nfrom .code_area import CodeArea\nfrom .version import __version__\n\nimport deprecation\nimport re\n\n# Separator for components of a UBID code.\nSEPARATOR_ = '-'\n\n# Format string for UBID codes.\nFORMAT_STRING_ = '%(centroid_openlocationcode)s%(sep)s%(height_in_openlocationcode_units).0f%(sep)s%(width_in_openlocationcode_units).0f'\n\n# Regular expression for UBID codes.\nRE_PATTERN_ = re.compile(r'^([^' + re.escape(SEPARATOR_) + r']+)' + re.escape(SEPARATOR_) + r'([1-9][0-9]*)' + re.escape(SEPARATOR_) + r'([1-9][0-9]*)$')\n\n# The first group of a UBID code is the OLC for the geometric center of mass\n# (i.e., centroid) of the building footprint.\nRE_GROUP_CENTROID_ = 1\n\n# The second group of the UBID code is the height in OLC grid units of the OLC\n# bounding box for the building footprint.\nRE_GROUP_HEIGHT_ = 2\n\n# The second group of the UBID code is the width in OLC grid units of the OLC\n# bounding box for the building footprint.\nRE_GROUP_WIDTH_ = 3\n\n@deprecation.deprecated(deprecated_in='1.0.0', removed_in=None, current_version=__version__, details='Use `buildingid.v2.decode` or `buildingid.v3.decode` instead.')\ndef decode(code: str) -> CodeArea:\n \"\"\"Returns the UBID code area for the given UBID code.\n\n Arguments:\n code - the UBID code\n\n Returns:\n The UBID code area.\n\n Raises:\n 'ValueError' - if the UBID code is invalid or if the OLC for the centroid of the building footprint is invalid\n \"\"\"\n\n # Attempt to match the regular expression.\n match = RE_PATTERN_.match(code)\n\n # If the UBID code does not match the regular expression, raise an error.\n if match is None:\n raise ValueError('Invalid UBID')\n\n # Extract the OLC for the centroid of the building footprint.\n centroid_openlocationcode_CodeArea = openlocationcode.decode(match.group(RE_GROUP_CENTROID_))\n\n # Extract the size of the OLC bounding box and calculate the half-height and\n # half-width of the OLC code area for the OLC code for the centroid of the\n # building footprint.\n half_height = ((centroid_openlocationcode_CodeArea.latitudeHi - centroid_openlocationcode_CodeArea.latitudeLo) * float(match.group(RE_GROUP_HEIGHT_))) / 2.0\n half_width = ((centroid_openlocationcode_CodeArea.longitudeHi - centroid_openlocationcode_CodeArea.longitudeLo) * float(match.group(RE_GROUP_WIDTH_))) / 2.0\n\n # Construct and return the UBID code area.\n return CodeArea(centroid_openlocationcode_CodeArea, centroid_openlocationcode_CodeArea.latitudeLo - half_height, centroid_openlocationcode_CodeArea.longitudeLo - half_width, centroid_openlocationcode_CodeArea.latitudeHi + half_height, centroid_openlocationcode_CodeArea.longitudeHi + half_width, centroid_openlocationcode_CodeArea.codeLength)\n\n@deprecation.deprecated(deprecated_in='1.0.0', removed_in=None, current_version=__version__, details='Use `buildingid.v2.encode` or `buildingid.v3.encode` instead.')\ndef encode(latitudeLo: float, longitudeLo: float, latitudeHi: float, longitudeHi: float, latitudeCenter: float, longitudeCenter: float, **kwargs) -> str:\n \"\"\"Returns the UBID code for the given coordinates.\n\n Arguments:\n latitudeLo - the latitude in decimal degrees of the southwest corner of the minimal bounding box for the building footprint\n longitudeLo - the longitude in decimal degrees of the southwest corner of the minimal bounding box for the building footprint\n latitudeHi - the latitude in decimal degrees of the northeast corner of the minimal bounding box for the building footprint\n longitudeHi - the longitude in decimal degrees of the northeast corner of the minimal bounding box for the building footprint\n latitudeCenter - the latitude in decimal degrees of the centroid of the building footprint\n longitudeCenter - the longitude in decimal degrees of the centroid of the building footprint\n\n Keyword arguments:\n codeLength - the OLC code length (not including the separator)\n\n Returns:\n The UBID code area.\n\n Raises:\n 'ValueError' - if the OLC for the centroid of the building footprint cannot be encoded (e.g., invalid code length)\n \"\"\"\n\n # Encode the OLC for the centroid of the building footprint.\n centroid_openlocationcode = openlocationcode.encode(latitudeCenter, longitudeCenter, **kwargs)\n\n # Decode the OLC for the centroid of the building footprint.\n centroid_openlocationcode_CodeArea = openlocationcode.decode(centroid_openlocationcode)\n\n # Calculate the size of the OLC bounding box for the building footprint,\n # assuming that the centroid of the building footprint is also the centroid\n # of the OLC bounding box.\n #\n # NOTE This introduces two issues. First, the centroid of the building\n # footprint is not necessarily the centroid of the corresponding OLC\n # bounding box (e.g., if the height or width is even). Second, the position\n # of the OLC bounding box (relative to the position of the centroid) is\n # not encoded in the UBID code (i.e., is lost).\n height = (latitudeHi - latitudeLo) / (centroid_openlocationcode_CodeArea.latitudeHi - centroid_openlocationcode_CodeArea.latitudeLo)\n width = (longitudeHi - longitudeLo) / (centroid_openlocationcode_CodeArea.longitudeHi - centroid_openlocationcode_CodeArea.longitudeLo)\n\n # Construct and return the UBID code.\n return FORMAT_STRING_ % {\n 'sep': SEPARATOR_,\n 'centroid_openlocationcode': centroid_openlocationcode,\n 'height_in_openlocationcode_units': height,\n 'width_in_openlocationcode_units': width,\n }\n\n@deprecation.deprecated(deprecated_in='1.0.0', removed_in=None, current_version=__version__, details='Use `buildingid.v2.encodeCodeArea` or `buildingid.v3.encodeCodeArea` instead.')\ndef encodeCodeArea(parent: CodeArea) -> str:\n \"\"\"Returns the UBID code for the given UBID code area.\n\n Arguments:\n parent - the UBID code area\n\n Returns:\n The UBID code area.\n\n Raises:\n 'ValueError' - if the OLC for the centroid of the building footprint cannot be encoded (e.g., invalid code length)\n \"\"\"\n\n # Ensure that the UBID code area is valid (e.g., that the OLC code lengths\n # for the UBID code area and the OLC code area are equal).\n if parent is None:\n raise ValueError('Invalid CodeArea')\n elif not (parent.codeLength == parent.child.codeLength):\n raise ValueError('Invalid CodeArea: \\'codeLength\\' mismatch')\n\n # Delegate.\n return encode(parent.latitudeLo, parent.longitudeLo, parent.latitudeHi, parent.longitudeHi, parent.child.latitudeCenter, parent.child.longitudeCenter, codeLength=parent.codeLength)\n\n@deprecation.deprecated(deprecated_in='1.0.0', removed_in=None, current_version=__version__, details='Use `buildingid.v2.isValid` or `buildingid.v3.isValid` instead.')\ndef isValid(code: str) -> bool:\n \"\"\"Is the given UBID code valid?\n\n Arguments:\n code - the UBID code\n\n Returns:\n 'True' if the UBID code is valid. Otherwise, 'False'.\n \"\"\"\n\n # Undefined UBID codes are invalid.\n if code is None:\n return False\n\n # Attempt to match the regular expression.\n match = RE_PATTERN_.match(code)\n\n # UBID codes that fail to match the regular expression are invalid.\n if match is None:\n return False\n\n # A UBID code that successfully matches the regular expression is valid if\n # (i) the OLC for the centroid of the building footprint is valid and (ii)\n # the height and width are greater than zero.\n return openlocationcode.isValid(match.group(RE_GROUP_CENTROID_)) and (int(match.group(RE_GROUP_HEIGHT_)) > 0) and (int(match.group(RE_GROUP_WIDTH_)) > 0)\n","sub_path":"buildingid/v1.py","file_name":"v1.py","file_ext":"py","file_size_in_byte":7809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"559379775","text":"import json #导入json格式\n\n\ndatas = {\"text\":\"中文\",\"polyline\":\"116.621248,41.02831\"}\nfl=open('p05.txt', 'w')\n\nfl.write(\"var polyline_data=\")\nfl.write(json.dumps(datas,ensure_ascii=False,indent=2))\nfl.close()\n\n\n#解码json格式,可以用json.loads()函数的解析方法,\ndecode_json = json.loads(encoded_json)\nprint(type(decode_json)) #查看解码后的对象类型\nprint(decode_json)\n","sub_path":"ex04/ex04_04_txt_write_read.py","file_name":"ex04_04_txt_write_read.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"373466200","text":"# Usage: python main_oshea.py --blksize 8 --chuse 4 --snr 10.0 --epochs 2500 --models 100 --prefix ./models/awgn_oshea_64_32_16_10dB\n\nimport numpy as np\nimport datetime, os, sys, argparse, time\nimport dill \nimport tensorflow.keras.backend as K\n\nfrom AEOshea import AEOshea1hot\n\nimport callbacks\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--blksize', type=int, help=\"Block Size\", default=8)\nparser.add_argument('--chuse', type=int, help=\"No. of channel uses\", default=4 )\nparser.add_argument('--snr', type=float, help=\"Train SNR (dB)\", default=10.0 )\nparser.add_argument('--epochs', type=int, help='No.of epochs to train', default=2500 )\nparser.add_argument('--models', type=int, help='No.of models to train', default=100 )\nparser.add_argument('--prefix', type=str, help='Output directory', default = './test/aeoshea' )\nargs = parser.parse_args()\n\nnoOfModels = args.models\nnoOfEpochs = args.epochs\nblkSize = args.blksize\nchUse = args.chuse\noutPrefix = args.prefix\ntrain_snr = args.snr\n\nSNR_range_dB = np.arange( 0.0, 11.0, 1.0 )\n\n# Input\ninVecDim = 2 ** blkSize # 1-hot vector length for block\nencDim = 2*chUse\nprint( \"In Vector Dim:\", inVecDim )\nprint( \"z dim:\", encDim )\n\n# Train Data\nxTrain = np.eye(inVecDim)[np.random.randint(inVecDim,size=10000)]\nxVal = np.eye(inVecDim)[np.random.randint(inVecDim,size=10000)]\n\n# ==========================================================================================\nresults = {}\nfor i in range(noOfModels):\n timestamp = datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\")\n print(\"{} Training {:3d}/{}\".format(timestamp,i+1,noOfModels))\n \n # Clear Model\n K.clear_session()\n try:\n del m\n except:\n pass\n\n m = AEOshea1hot(inVecDim, encDim, h_dim=[64,32,16], train_snr_dB=train_snr)\n \n # Create callback monitor\n # Create callback monitor\n monitors = {\n \"packing_density\": callbacks.PackingDensityMonitor(m, \n in_dim=inVecDim, \n interval=25), # Packing density monitor\n \"bler_4dB\": callbacks.BlerMonitor(m, in_dim=inVecDim, \n ch_use=chUse, snr_dB=4.0, \n interval=100),\n \"bler_6dB\": callbacks.BlerMonitor(m, in_dim=inVecDim, \n ch_use=chUse, snr_dB=6.0, \n interval=100)\n }\n\n h = m.fit(xTrain, epochs=noOfEpochs, batch_size=1000, verbose=0, \n callbacks=[ cb for (_, cb) in monitors.items() ])\n m.save_model(outPrefix + \"_\" + timestamp)\n\n z_mu, _ = m.encode(np.eye(inVecDim))\n sym_pow = np.mean(np.sum(z_mu*z_mu,axis=1))\n print( \"Avg. Tx Sym Power:\", sym_pow )\n noisePower = sym_pow * 10.0**(-SNR_range_dB/10.0)\n n0_per_comp = noisePower/(2*chUse)\n\n err = []\n for n0 in n0_per_comp:\n thisErr = 0\n thisCount = 0\n while thisErr < 500:\n txSym = txSym = np.random.randint(inVecDim, size=1000)\n tx1hot = np.eye(inVecDim)[txSym]\n txTest, _ = m.encode(tx1hot)\n rxTest = txTest + np.random.normal(scale=np.sqrt(n0), size=txTest.shape)\n rxDecode = m.decode(rxTest)\n rxSym = np.argmax(rxDecode,axis=1)\n thisErr += np.sum(rxSym!=txSym)\n thisCount += 1000\n err.append(thisErr/thisCount)\n blkErr = np.array(err)\n \n # Make results entry\n results[timestamp] = {\n \"sym_pow\": sym_pow, \n \"snr_dB\": SNR_range_dB,\n \"bler\": blkErr\n }\n # Merge all monitor results\n for label, monitor in monitors.items():\n for (k, v) in monitor.results.items():\n results[timestamp][\"{}_{}\".format(label, k)] = v\n\nwith open(outPrefix+\"_summary.dil\", \"wb\") as f:\n dill.dump(results, f)","sub_path":"AWGN/main_oshea.py","file_name":"main_oshea.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"49754448","text":"def dictdiff(dct2,dct1):\n for i in dct1:\n if i in dct2:\n dct2[i]-=dct1[i]\n return dct2\n\nn=int(input())\nstringy=input()\nxhash=dict()\nlst=[dict()]\nfor i in stringy:\n if i in xhash:\n xhash[i]+=1\n else:\n xhash[i]=1\n lst.append(xhash.copy())\n\nq=int(input())\nfor _ in range(q):\n l,r=[int(x) for x in input().split()]\n tempdict=dictdiff(lst[r+1].copy(),lst[l].copy())\n evencount,oddcount=0,0\n for i in tempdict:\n if tempdict[i]%2==0:\n evencount+=1\n else:\n oddcount+=1\n #print(evencount,oddcount)\n if oddcount==0 or oddcount==1:\n print(\"YES\")\n else:\n print(\"NO\")\n\n","sub_path":"Python/Palindrome string making.py","file_name":"Palindrome string making.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"37828244","text":"from Report import *\nfrom BigMat import sync_backend,garbage_collect,memory_info\n\nclass TrainingRun(object):\n '''\n Trains a given model by stochastic gradient descent.\n '''\n def __init__(self,model,data,report_args={},\n learn_rate=1.0,learn_rate_decay=.995,momentum=0.0,slowness=0.0,\n batchsize=64,epochs=3000):\n \n self.model = model\n self.data = data\n\n self.batchsize = batchsize\n self.batches = data.train.make_batches(batchsize)\n self.epochs = epochs\n self.epoch = 0\n\n self.learn_rate_schedule = learn_rate\n self.learn_rate = self._calc_scheduled_rate(learn_rate,0.0)\n self.learn_rate_decay = learn_rate_decay\n self.momentum_schedule= momentum\n self.momentum = self._calc_scheduled_rate(momentum,0.0)\n self.slowness_schedule = slowness\n self.slowness = self._calc_scheduled_rate(slowness,0.0)\n\n # wstep is pre-allocated memory for storing gradient matrices\n self._wgrad = model.make_weights()\n self._wstep = model.make_weights() if momentum else None\n \n if report_args['verbose']: self.log = TrainingReport(self,**report_args) \n else: self.log = lambda event: 0 # do nothing\n\n def train(self,epochs_this_call=None):\n '''\n Train the current model up the the maximum number of epochs.\n '''\n model,weights = self.model,self.model.weights\n wgrad,wstep = self._wgrad,self._wstep\n\n model.apply_constraints()\n\n self.log('start')\n\n # Outer loop over epochs\n last_epoch = self.epochs if epochs_this_call == None else (self.epoch+epochs_this_call)\n for self.epoch in xrange(self.epoch+1,last_epoch+1):\n self.batches.shuffle()\n\n # Compute learning rate and momentum for this epoch\n self.learn_rate = self._calc_scheduled_rate(self.learn_rate_schedule,self.learn_rate)\n self.learn_rate *= self.learn_rate_decay**(self.epoch-1)\n self.momentum = self._calc_scheduled_rate(self.momentum_schedule,self.momentum)\n self.slowness = self._calc_scheduled_rate(self.slowness_schedule,self.slowness)\n\n # Inner loop over one shuffled sweep of the data\n for batch in self.batches:\n if self.momentum:\n # Add Nesterov look-ahead momentum, before computing gradient\n wstep *= self.momentum\n weights += wstep\n\n # Compute gradient, storing it in wstep\n model.grad(batch,out=wgrad)\n \n # Add momentum to the step, then adjust the weights\n wgrad *= -self.learn_rate;\n weights += wgrad\n wstep += wgrad\n else:\n model.grad(batch,out=wgrad)\n weights.step_by(wgrad,alpha=-self.learn_rate)\n\n # Apply any model constraints, like clipping norm of weights\n model.apply_constraints()\n\n self.log('epoch')\n\n self.log('stop')\n sync_backend() # make sure all gpu operations are complete\n\n\n def _calc_scheduled_rate(self,schedule,rate):\n if not isinstance(schedule,list):\n return float(schedule)\n\n n = len(schedule)\n if n == 1:\n epoch0,m0 = schedule[0]\n if self.epoch >= epoch0:\n return m0\n return rate\n\n if self.epoch < schedule[0][0]:\n return rate\n\n for i in range(n-1):\n epoch0,m0 = schedule[i]\n epoch1,m1 = schedule[i+1]\n assert(epoch0 < epoch1)\n if self.epoch >= epoch0 and self.epoch <= epoch1:\n t = float(self.epoch - epoch0) / (epoch1 - epoch0)\n return m0 + t*(m1-m0)\n\n if self.epoch < schedule[0][0]:\n return schedule[0][1]\n return schedule[-1][1]\n\n def task(self):\n if self.model._loss_type == \"nll\":\n return \"classification\" \n return \"regression\"","sub_path":"TrainingRun.py","file_name":"TrainingRun.py","file_ext":"py","file_size_in_byte":4162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"258046793","text":"\"\"\" Checks for ACE_INLINE or and ASYS_INLINE in a .cpp file \"\"\"\nfrom _types import source_files\ntype_list = source_files\n\n\nimport re\nfrom sys import stderr\nregex = re.compile (\"(^\\s*ACE_INLINE)|(^\\s*ASYS_INLINE)\", re.MULTILINE)\n\nerror_message = \": error: ACE_INLINE or ASYS_INLINE found in .cpp file\\n\"\n\ndef handler (file_name, file_content):\n if regex.search (file_content) != None:\n # Lets take some time to generate a detailed error report\n # since we appear to have a violation\n lines = file_content.splitlines ()\n for line in range (len (lines)):\n if regex.search (lines[line]) != None:\n stderr.write (file_name + ':' + str (line + 1) + error_message)\n\n return 1\n else:\n return 0\n","sub_path":"3rd/ACE-5.7.0/ACE_wrappers/bin/PythonACE/fuzz/cpp_inline.py","file_name":"cpp_inline.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"473649867","text":"import sys\nfrom oslo_config import cfg\nfrom oslo_log import log\n\n\nlogger = log.getLogger(__name__)\n\n# register logger conf\nlog.register_options(cfg.CONF)\n\n# set CONF from sys.args\ncfg.CONF(sys.argv[1:], \"test-domain\")\n\n# set logger conf\nlog.setup(cfg.CONF, \"test-domain\")\n\nlogger.info(\"log info\")\nlogger.debug(\"log debug\")\nlogger.warning(\"log warning\")\nlogger.error(\"log error\")\n\n# usage:\n# python log_with_cfg.py -h\n","sub_path":"python/oslo_log/log_with_cfg.py","file_name":"log_with_cfg.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"409293815","text":"# Copyright (c) 2019 Kouhei Sekiguchi, Yoshiaki Bando\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\"\"\"\nFastMNMF\n========\n\nBlind Source Separation based on Fast Multichannel Nonnegative Matrix Factorization (FastMNMF)\n\"\"\"\nimport numpy as np\n\n\ndef fastmnmf(\n X,\n n_src=None,\n n_iter=30,\n W0=None,\n n_components=4,\n callback=None,\n mic_index=0,\n interval_update_Q=1,\n interval_normalize=10,\n initialize_ilrma=False,\n):\n \"\"\"\n Implementation of FastMNMF algorithm presented in\n\n K. Sekiguchi, A. A. Nugraha, Y. Bando, K. Yoshii, *Fast Multichannel Source\n Separation Based on Jointly Diagonalizable Spatial Covariance Matrices*, EUSIPCO, 2019. [`arXiv <https://arxiv.org/abs/1903.03237>`_]\n\n The code of FastMNMF with GPU support and FastMNMF-DP which integrates DNN-based source model\n into FastMNMF is available on https://github.com/sekiguchi92/SpeechEnhancement\n\n Parameters\n ----------\n X: ndarray (nframes, nfrequencies, nchannels)\n STFT representation of the observed signal\n n_src: int, optional\n The number of sound sources (if n_src = None, n_src is set to the number of microphone)\n n_iter: int, optional\n The number of iterations\n W0: ndarray (nfrequencies, nchannels, nchannels), optional\n Initial value for diagonalizer Q\n Demixing matrix can be used as the initial value\n n_components: int, optional\n Number of components in the non-negative spectrum\n callback: func, optional\n A callback function called every 10 iterations, allows to monitor convergence\n mic_index: int, optional\n The index of microphone of which you want to get the source image\n interval_update_Q: int, optional\n The interval of updating Q\n interval_normalize: int, optional\n The interval of parameter normalization\n initialize_ilrma: boolean, optional\n Initialize diagonalizer Q by using ILRMA\n\n Returns\n -------\n separated spectrogram: numpy.ndarray\n An (nframes, nfrequencies, nsources) array.\n \"\"\"\n\n eps = 1e-7\n\n # initialize parameter\n X_FTM = X.transpose(1, 0, 2)\n n_freq, n_frames, n_chan = X_FTM.shape\n XX_FTMM = np.matmul(X_FTM[:, :, :, None], X_FTM[:, :, None, :].conj())\n if n_src is None:\n n_src = X_FTM.shape[\n 2\n ] # determined case (the number of source = the number of microphone)\n\n if initialize_ilrma: # initialize by using ILRMA\n from pyroomacoustics.bss.ilrma import ilrma\n\n Y_TFM, W = ilrma(\n X, n_iter=10, n_components=2, proj_back=False, return_filters=True\n )\n Q_FMM = W\n sep_power_M = np.abs(Y_TFM).mean(axis=(0, 1))\n g_NFM = np.ones([n_src, n_freq, n_chan]) * 1e-2\n for n in range(n_src):\n g_NFM[n, :, sep_power_M.argmax()] = 1\n sep_power_M[sep_power_M.argmax()] = 0\n elif W0 != None: # initialize by W0\n Q_FMM = W0\n g_NFM = np.ones([n_src, n_freq, n_chan]) * 1e-2\n for m in range(n_chan):\n g_NFM[m % n_src, :, m] = 1\n else: # initialize by using observed signals\n Q_FMM = np.tile(np.eye(n_chan).astype(np.complex), [n_freq, 1, 1])\n g_NFM = np.ones([n_src, n_freq, n_chan]) * 1e-2\n for m in range(n_chan):\n g_NFM[m % n_src, :, m] = 1\n for m in range(n_chan):\n mu_F = (Q_FMM[:, m] * Q_FMM[:, m].conj()).sum(axis=1).real\n Q_FMM[:, m] = Q_FMM[:, m] / np.sqrt(mu_F[:, None])\n H_NKT = np.random.rand(n_src, n_components, n_frames)\n W_NFK = np.random.rand(n_src, n_freq, n_components)\n lambda_NFT = np.matmul(W_NFK, H_NKT)\n Qx_power_FTM = (\n np.abs((np.matmul(Q_FMM[:, None], X_FTM[:, :, :, None]))[:, :, :, 0]) ** 2\n )\n Y_FTM = (lambda_NFT[..., None] * g_NFM[:, :, None]).sum(axis=0)\n\n separated_spec = np.zeros([n_src, n_freq, n_frames], dtype=np.complex)\n\n def separate():\n Qx_FTM = (Q_FMM[:, None] * X_FTM[:, :, None]).sum(axis=3)\n diagonalizer_inv_FMM = np.linalg.inv(Q_FMM)\n tmp_NFTM = lambda_NFT[..., None] * g_NFM[:, :, None]\n for n in range(n_src):\n tmp = (\n np.matmul(\n diagonalizer_inv_FMM[:, None],\n (Qx_FTM * (tmp_NFTM[n] / (tmp_NFTM).sum(axis=0)))[..., None],\n )\n )[:, :, mic_index, 0]\n separated_spec[n] = tmp\n return separated_spec.transpose(2, 1, 0)\n\n # update parameters\n for epoch in range(n_iter):\n if callback is not None and epoch % 10 == 0:\n callback(separate())\n\n # update_WH (basis and activation of NMF)\n tmp_yb1 = (g_NFM[:, :, None] * (Qx_power_FTM / (Y_FTM ** 2))[None]).sum(\n axis=3\n ) # [N, F, T]\n tmp_yb2 = (g_NFM[:, :, None] / Y_FTM[None]).sum(axis=3) # [N, F, T]\n a_1 = (H_NKT[:, None, :, :] * tmp_yb1[:, :, None]).sum(axis=3) # [N, F, K]\n b_1 = (H_NKT[:, None, :, :] * tmp_yb2[:, :, None]).sum(axis=3) # [N, F, K]\n W_NFK *= np.sqrt(a_1 / b_1)\n\n a_1 = (W_NFK[:, :, :, None] * tmp_yb1[:, :, None]).sum(axis=1) # [N, K, T]\n b_1 = (W_NFK[:, :, :, None] * tmp_yb2[:, :, None]).sum(axis=1) # [N, F, K]\n H_NKT *= np.sqrt(a_1 / b_1)\n\n np.matmul(W_NFK, H_NKT, out=lambda_NFT)\n np.maximum(lambda_NFT, eps, out=lambda_NFT)\n Y_FTM = (lambda_NFT[..., None] * g_NFM[:, :, None]).sum(axis=0)\n\n # update diagonal element of spatial covariance matrix\n a_1 = (lambda_NFT[..., None] * (Qx_power_FTM / (Y_FTM ** 2))[None]).sum(\n axis=2\n ) # N F T M\n b_1 = (lambda_NFT[..., None] / Y_FTM[None]).sum(axis=2)\n g_NFM *= np.sqrt(a_1 / b_1)\n Y_FTM = (lambda_NFT[..., None] * g_NFM[:, :, None]).sum(axis=0)\n\n # udpate Diagonalizer which jointly diagonalize spatial covariance matrix\n if (interval_update_Q <= 0) or ((epoch + 1) % interval_update_Q == 0):\n for m in range(n_chan):\n V_FMM = (XX_FTMM / Y_FTM[:, :, m, None, None]).mean(axis=1)\n tmp_FM = np.linalg.solve(\n np.matmul(Q_FMM, V_FMM), np.eye(n_chan)[None, m]\n )\n Q_FMM[:, m] = (\n tmp_FM\n / np.sqrt(\n ((tmp_FM.conj()[:, :, None] * V_FMM).sum(axis=1) * tmp_FM).sum(\n axis=1\n )\n )[:, None]\n ).conj()\n Qx_power_FTM = (\n np.abs((np.matmul(Q_FMM[:, None], X_FTM[:, :, :, None]))[:, :, :, 0])\n ** 2\n )\n\n # normalize\n if (interval_normalize <= 0) or (epoch % interval_normalize == 0):\n phi_F = np.sum(Q_FMM * Q_FMM.conj(), axis=(1, 2)).real / n_chan\n Q_FMM /= np.sqrt(phi_F)[:, None, None]\n g_NFM /= phi_F[None, :, None]\n\n mu_NF = (g_NFM).sum(axis=2)\n g_NFM /= mu_NF[:, :, None]\n W_NFK *= mu_NF[:, :, None]\n\n mu_NK = W_NFK.sum(axis=1)\n W_NFK /= mu_NK[:, None]\n H_NKT *= mu_NK[:, :, None]\n np.matmul(W_NFK, H_NKT, out=lambda_NFT)\n np.maximum(lambda_NFT, 1e-10, out=lambda_NFT)\n\n Qx_power_FTM = (\n np.abs((np.matmul(Q_FMM[:, None], X_FTM[:, :, :, None]))[:, :, :, 0])\n ** 2\n )\n Y_FTM = (lambda_NFT[..., None] * g_NFM[:, :, None]).sum(axis=0)\n\n return separate()\n","sub_path":"pyroomacoustics/bss/fastmnmf.py","file_name":"fastmnmf.py","file_ext":"py","file_size_in_byte":8485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"461045484","text":"# -*- coding: utf-8 -*-\n__license__ = \"MIT License <http://www.opensource.org/licenses/mit-license.php>\"\n__copyright__ = \"2005, Tiago Cogumbreiro\"\n__author__ = \"Tiago Cogumbreiro <cogumbreiro@users.sf.net>\"\n\nfrom common import *\nfrom gtkutil import signal_holder\nimport core\n\ndef _activate_action(widget, action):\n action.set_active(True)\n\ndef _deactivate_action(widget, action):\n action.set_active(False)\n\ndef _toggle_visibility(action, widget):\n if action.get_active():\n widget.show()\n else:\n widget.hide()\n \n\nclass VisibilitySync:\n\n def __init__(self, widget, toggle_action, apply_now=True):\n\n self._activate = signal_holder(\n widget,\n \"show\",\n _activate_action,\n userdata=toggle_action\n )\n \n self._deactivate = signal_holder(\n widget,\n \"hide\",\n _deactivate_action,\n userdata=toggle_action\n )\n \n self._toggle_visible = signal_holder(\n toggle_action,\n \"toggled\",\n _toggle_visibility,\n userdata=widget\n )\n \n # Take effect now\n visible = widget.get_property(\"visible\")\n if apply_now and visible != toggle_action.get_active():\n toggle_action.set_active(visible)\n \n\nclass Bar(core.BaseService):\n toggle_action = None\n \n ############\n # Widget\n\n _widget = None\n \n def get_widget(self):\n if self._widget is None:\n self._widget = self.create_widget()\n self._widget.connect(\"key-release-event\", self._on_key_pressed)\n self.__update_visibility_sync()\n \n return self._widget\n \n widget = property(get_widget)\n \n def __update_visibility_sync(self):\n if self._widget is not None and self.toggle_action is not None:\n self.__visibility_sync = VisibilitySync(self._widget, self.toggle_action)\n else:\n self.__visibility_sync = None\n \n ##########\n # Methods\n def set_action_group(self, action_group):\n if action_group is None:\n self.toggle_source = None\n return\n \n self.toggle_action = self._create_toggle_action(action_group)\n self.__update_visibility_sync()\n\n \n def _on_action_toggled(self, action):\n if action.get_active():\n self.widget.show()\n else:\n self.widget.hide()\n \n def _on_key_pressed(self, search_text, event):\n global KEY_ESCAPE\n \n if event.keyval == KEY_ESCAPE:\n self.toggle_action.set_active(False)\n\n \n\n \n","sub_path":"branches/model-config/pida/utils/culebra/bar.py","file_name":"bar.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"121096843","text":"import numpy as np\nimport pandas as pd\nimport gc\n\nprint(\"-------------------------Beginning Training-------------------------\")\n\n# Load the properties 2016 dataset. Low_memory=False needed due to size of the dataset.\nproperties = pd.read_csv('data/properties_2016.csv', low_memory=False)\n\n# Load the training 2016 dataset which contains the label to train on, logerror.\ntraining = pd.read_csv('data/train_2016_v2.csv', parse_dates=['transactiondate'])\n\n# Use pandas merge function to join the training data and the properties on the unique identifier 'parcelid'\ndata = training.merge(properties, how='left', on='parcelid')\n\ndel training\ngc.collect()\n\n# Create a new column for the transaction month from the original transactiondate column\ndata['transaction_month'] = data['transactiondate'].dt.month\n\n# Select the most useful features\ndata = data[['logerror', 'calculatedbathnbr', 'bedroomcnt', 'calculatedfinishedsquarefeet',\n 'latitude', 'longitude', 'lotsizesquarefeet', 'yearbuilt',\n 'structuretaxvaluedollarcnt', 'taxvaluedollarcnt',\n 'landtaxvaluedollarcnt', 'taxamount', 'regionidzip',\n 'transaction_month']]\n\n# Compress the log error of outliers\nfor idx in data.index:\n q = data.get_value(idx, 'logerror')\n if q > 0.4:\n x = q / 2\n data.set_value(idx, 'logerror', x)\n elif q < -0.4:\n x = q / 2\n data.set_value(idx, 'logerror', x)\n\n# Create target and drop it from the training data\nlabel = data[\"logerror\"]\ndata = data.drop(['logerror'], 1)\n\nfrom sklearn.preprocessing import Imputer, StandardScaler\nfrom sklearn.externals import joblib\n\n# Define, impute, and transform numerical features\nnumerical = ['calculatedbathnbr', \"bedroomcnt\", \"calculatedfinishedsquarefeet\", \"latitude\",\n \"longitude\", \"lotsizesquarefeet\", \"yearbuilt\", \"structuretaxvaluedollarcnt\",\n \"taxvaluedollarcnt\", \"landtaxvaluedollarcnt\", \"taxamount\"]\n\nimputer = Imputer(missing_values='NaN', strategy='median', axis=0)\n\nimputer = imputer.fit(data[numerical])\ndata[numerical] = imputer.transform(data[numerical])\njoblib.dump(imputer, 'transformers/imputer.pkl')\nprint(\"Numerical Fillna Complete\")\n\nscaler = StandardScaler()\n \nscaler = scaler.fit(data[numerical]) \ndata[numerical] = scaler.transform(data[numerical])\njoblib.dump(scaler, 'transformers/scaler.pkl')\nprint(\"Numerical Scaling Complete\")\n\n# Define, impute, and transform categorical features\ncategorical = ['regionidzip', \"transaction_month\"]\n\ncat_imputer = Imputer(missing_values='NaN', strategy='most_frequent', axis=0)\n\ncat_imputer = cat_imputer.fit(data[categorical])\ndata[categorical] = cat_imputer.transform(data[categorical])\njoblib.dump(cat_imputer, 'transformers/cat_imputer.pkl')\nprint(\"Categorical fillna complete\")\n\nfrom sklearn.preprocessing import LabelEncoder\n\nle_zip = LabelEncoder()\nzip_values = properties['regionidzip'].append(data['regionidzip'])\nle_zip = le_zip.fit(zip_values.values)\ndata['regionidzip'] = le_zip.transform(data['regionidzip'])\njoblib.dump(le_zip, 'transformers/le_zip.pkl')\n\nprint(\"Zip Code Label Encoded\")\n\nle_month = LabelEncoder()\nle_month = le_month.fit(data['transaction_month'].values)\ndata['transaction_month'] = le_month.transform(data['transaction_month'])\njoblib.dump(le_month, 'transformers/le_month.pkl')\n\nprint(\"Transaction Month Label Encoded\")\n\ndel properties\ngc.collect()\n\nfrom catboost import CatBoostRegressor\n\nprint(\"Beginning 2016 Training\")\ncat = CatBoostRegressor(iterations=1000,\n learning_rate=0.005,\n depth=4, l2_leaf_reg=15,\n loss_function='MAE',\n eval_metric='MAE',\n random_seed=10)\n\ncat.fit(data, label)\njoblib.dump(cat, 'models/cat.pkl')\n\nprint(\"-------------------------Training Complete-------------------------\")","sub_path":"Trainer_2016.py","file_name":"Trainer_2016.py","file_ext":"py","file_size_in_byte":3849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"358387122","text":"from selenium import webdriver\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nimport time\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nimport selenium\r\n\r\nclass autotwitter:\r\n def __init__(self):\r\n self.driver = webdriver.Chrome('D:/chromedriver')\r\n def login(self):\r\n driver=self.driver\r\n driver.get('https://twitter.com/login')\r\n time.sleep(5)\r\n name = driver.find_element_by_class_name('js-username-field')\r\n name.send_keys(\"trichopathophobiainfinity123@gmail.com\")\r\n password = driver.find_element_by_class_name('js-password-field')\r\n password.send_keys(\"googlemailservice\")\r\n time.sleep(2)\r\n password.send_keys(Keys.RETURN)\r\n #login = driver.find_element_by_tag_name('button')\r\n # login.click()\r\n def bs4(self):\r\n url = 'https://twitter.com/search?q=webdevelopment&src=typd'\r\n page = requests.get(url)\r\n soup = BeautifulSoup(page.content, 'html.parser')\r\n s1 = soup.find_all('div', class_='tweet')\r\n for tweet in s1:\r\n print(tweet)\r\n\r\n def like_tweet(self,hashtag):\r\n driver=self.driver\r\n driver.get('https://twitter.com/search?q='+hashtag+'&src=typd')\r\n time.sleep(6)\r\n for _ in range(100):\r\n driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')\r\n time.sleep(5)\r\n tweets = driver.find_elements_by_class_name('tweet')\r\n links=[elem.get_attribute('data-permalink-path') for elem in tweets]\r\n print(links)\r\n driver.execute_script(\"window.open('https://www.google.com', 'new_window')\")\r\n driver.switch_to_window(driver.window_handles[1])\r\n for link in links:\r\n if(link==None):\r\n break\r\n else:\r\n driver=self.driver\r\n driver.get('https://twitter.com'+link)\r\n try:\r\n driver.find_element_by_class_name('HeartAnimation').click()\r\n except:\r\n print()\r\n print()\r\n print(\"end of page\")\r\n print()\r\n print()\r\n print()\r\n print()\r\n break\r\n driver.switch_to_window(driver.window_handles[0])\r\n \r\nbot=autotwitter()\r\nbot.login()\r\nbot.like_tweet('python')\r\n\r\n\r\n\r\n\r\n","sub_path":"twitter likes.py","file_name":"twitter likes.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"491263604","text":"#!/usr/bin/env python\n#\n\nfrom __future__ import print_function\n\nimport sys\nimport struct\nimport argparse\nimport logging\nimport cmd\nimport threading\nimport serial\n\nLOGGER = logging.getLogger(__name__)\n\nSOAM_TYPE_COMMAND_REQUEST = 1\nSOAM_TYPE_COMMAND_RESPONSE_DATA = 2\nSOAM_TYPE_COMMAND_RESPONSE = 3\nSOAM_TYPE_LOG_POINT = 4\n\n\ndef crc_ccitt(data):\n msb = 0xff\n lsb = 0xff\n\n for c in data:\n x = ord(c) ^ msb\n x ^= (x >> 4)\n msb = (lsb ^ (x >> 3) ^ (x << 4)) & 255\n lsb = (x ^ (x << 5)) & 255\n\n return (msb << 8) + lsb\n\n\ndef create_packet(packet_type, payload):\n \"\"\"Create a SOAM/SLIP packet.\n\n \"\"\"\n\n soam_packet = struct.pack('>BH', packet_type, len(payload) + 2)\n soam_packet += payload\n soam_packet += struct.pack('>H', crc_ccitt(soam_packet))\n\n slip_packet = b'\\xc0'\n\n for byte in soam_packet:\n if byte == b'\\xc0':\n slip_packet += b'\\xdb\\xdc'\n elif byte == b'\\xdb':\n slip_packet += b'\\xdb\\xdd'\n else:\n slip_packet += byte\n\n slip_packet += b'\\xc0'\n\n return slip_packet\n\n\nclass TimeoutError(Exception):\n pass\n\n\nclass ReaderThread(threading.Thread):\n\n def __init__(self, client):\n super(ReaderThread, self).__init__()\n self.client = client\n self.running = True\n self.response_packet_cond = threading.Condition()\n self.response_packet = None\n\n def _read_packet(self):\n \"\"\"Read a packet from the SOAM server.\n\n \"\"\"\n\n packet = b''\n is_escaped = False\n\n while self.running:\n byte = self.client.serial.read(1)\n\n if not is_escaped:\n if byte == b'\\xc0':\n if len(packet) > 0:\n return packet\n elif byte == b'db':\n is_escaped = True\n else:\n packet += byte\n else:\n if byte == b'\\xdc':\n packet += b'c0'\n elif byte == b'\\xdd':\n packet += b'db'\n else:\n # Protocol error. Discard the packet.\n print('Discarding:', packet)\n packet = b''\n\n is_escaped = False\n\n\n def read_command_response(self, timeout=None):\n \"\"\"Wait for a response packet of given type.\n\n \"\"\"\n\n with self.response_packet_cond:\n if self.response_packet is None:\n self.response_packet_cond.wait(timeout)\n\n if self.response_packet is None:\n raise TimeoutError(\"no response packet received\")\n\n packet = self.response_packet\n self.response_packet = None\n\n return packet[0], packet[1]\n\n def run(self):\n \"\"\"Read packets from the soam server.\n\n \"\"\"\n\n response_data = b''\n\n while self.running:\n try:\n packet = self._read_packet()\n if packet is None:\n break\n except BaseException as e:\n LOGGER.info(\"failed to read packet with error: %s\", e)\n break\n\n #print(packet.encode('hex'))\n\n if len(packet) < 5:\n continue\n\n # Parse the received packet.\n crc = crc_ccitt(packet[:-2])\n\n if crc != struct.unpack('>H', packet[-2:])[0]:\n print('Packet CRC mismatch:', packet)\n continue\n\n packet_type = struct.unpack('B', packet[0:1])[0]\n\n if packet_type == SOAM_TYPE_COMMAND_RESPONSE_DATA:\n response_data += packet[5:-2]\n elif packet_type == SOAM_TYPE_COMMAND_RESPONSE:\n code = struct.unpack('>i', packet[5:-2])[0]\n\n with self.response_packet_cond:\n self.response_packet = code, response_data\n response_data = b''\n self.response_packet_cond.notify_all()\n elif packet_type == SOAM_TYPE_LOG_POINT:\n print(packet[3:-2], end='')\n else:\n print('Bad packet type:', packet)\n\n def stop(self):\n self.running = False\n\n\nclass SlipSerialClient(object):\n\n def __init__(self, serial_port, baudrate):\n self.serial = serial.Serial(serial_port,\n baudrate=baudrate,\n timeout=0.5)\n self.reader = ReaderThread(self)\n self.reader.start()\n\n def execute_command(self, command_with_args):\n \"\"\"Execute given file system (fs) command and return a tuple of the\n command status code and output.\n\n \"\"\"\n\n command = command_with_args.split(' ')[0]\n command_id = command\n command_with_args = command_with_args.replace(command, command_id, 1)\n command_with_args += b'\\x00'\n\n packet = create_packet(SOAM_TYPE_COMMAND_REQUEST, command_with_args)\n\n self.serial.write(packet)\n\n return self.reader.read_command_response(3.0)\n\n\nclass CommandStatus(object):\n\n OK = \"OK\"\n ERROR = \"ERROR\"\n\n\ndef handle_errors(func):\n \"\"\"Decorator that catches exceptions and prints them.\n\n \"\"\"\n\n def wrapper(*args, **kwargs):\n self = args[0]\n\n try:\n return func(*args, **kwargs)\n except KeyboardInterrupt:\n LOGGER.info(\"Keyboard interrupt.\")\n self.output(CommandStatus.ERROR)\n except BaseException as e:\n self.output_exception(e)\n self.output(CommandStatus.ERROR)\n\n # The command help needs the docstring on the wrapper function.\n wrapper.__doc__ = func.__doc__\n\n return wrapper\n\n\nclass Shell(cmd.Cmd):\n\n intro = \"Welcome to the SOAM shell.\\n\\nType help or ? to list commands.\\n\"\n prompt = \"$ \"\n\n def __init__(self, client, stdout=None):\n if stdout is None:\n stdout = sys.stdout\n\n cmd.Cmd.__init__(self, stdout=stdout)\n\n self.client = client\n self.stdout = stdout\n\n def emptyline(self):\n pass\n\n def output_exception(self, e):\n text = \"{module}.{name}: {message}\".format(module=type(e).__module__,\n name=type(e).__name__,\n message=str(e))\n LOGGER.warning(text)\n self.output(text)\n\n def output(self, text=\"\", end=\"\\n\"):\n print(text, file=self.stdout, end=end)\n\n @handle_errors\n def do_command(self, args):\n \"\"\"Execute given command.\n\n \"\"\"\n\n if not args:\n self.output(\"Invalid command.\")\n self.output(CommandStatus.ERROR)\n return\n\n code, output = self.client.execute_command(args)\n self.output(output, end='')\n\n if code == 0:\n self.output(CommandStatus.OK)\n else:\n self.output(CommandStatus.ERROR + '({})'.format(code))\n\n @handle_errors\n def do_exit(self, args):\n \"\"\"Exit the shell.\n\n \"\"\"\n\n del args\n self.output()\n self.output()\n self.output(\"Bye!\")\n return True\n\n @handle_errors\n def do_EOF(self, args):\n \"\"\"Exit the shell.\n\n \"\"\"\n\n return self.do_exit(args)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-p', '--port', default='/dev/ttyACM1')\n parser.add_argument('-b', '--baudrate', type=int, default=115200)\n args = parser.parse_args()\n\n client = SlipSerialClient(args.port, args.baudrate)\n shell = Shell(client)\n shell.cmdloop()\n client.reader.stop()\n\nif __name__ == '__main__':\n main()\n","sub_path":"bin/soam.py","file_name":"soam.py","file_ext":"py","file_size_in_byte":7633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"617538700","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\n\"\"\"Synthesizes speech from the input string of text or ssml.\n\nNote: ssml must be well-formed according to:\n https://www.w3.org/TR/speech-synthesis/\n\"\"\"\n\nimport os\nfrom google.cloud import texttospeech\nimport string\nimport configparser\nimport json\nimport argparse\n\n# required arg\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"--speech\", required=False, action=\"store_true\")\nparser.add_argument(\"--config\", required=False, action=\"store_true\")\nparser.add_argument(\"--alphabet\", required=False, action=\"store_true\")\nparser.add_argument(\"--numbers\", required=False, action=\"store_true\")\nparser.add_argument(\"--full\", required=False, action=\"store_true\")\n\nargs = parser.parse_args()\n\n\n# Instantiates a client\nclient = texttospeech.TextToSpeechClient()\n\n\ndef store_text(text_to_store, filename=None, folder=None):\n\n folderpath = \"data/sounds/\" + folder\n print(folderpath)\n if not os.path.exists(folderpath):\n os.makedirs(folderpath)\n\n # Set the text input to be synthesized\n synthesis_input = texttospeech.types.SynthesisInput(text=text_to_store)\n\n # Build the voice request, select the language code (\"en-US\") and the ssml\n # voice gender (\"neutral\")\n voice = texttospeech.types.VoiceSelectionParams(\n language_code=\"fr-fr\",\n ssml_gender=texttospeech.enums.SsmlVoiceGender.MALE,\n name=\"fr-FR-Wavenet-B\",\n )\n\n # Select the type of audio file you want returned\n audio_config = texttospeech.types.AudioConfig(\n speaking_rate=0.80, audio_encoding=texttospeech.enums.AudioEncoding.MP3\n )\n\n # Perform the text-to-speech request on the text input with the selected\n # voice parameters and audio file type\n response = client.synthesize_speech(synthesis_input, voice, audio_config)\n if filename is None:\n\n filename = str(text_to_store)\n\n # The response's audio_content is binary.\n with open(\"data/sounds/\" + folder + \"/\" + filename + \".mp3\", \"wb\") as out:\n\n # Write the response to the output file.\n out.write(response.audio_content)\n print(f\"Audio content written to file {filename}\")\n\n\ndef read_config_file():\n config = configparser.ConfigParser()\n config.read(\"text_content.ini\")\n\n\nconfig = configparser.ConfigParser()\nconfig.read(\"text_content.ini\")\n\n\ndef create_config_json():\n with open(\"config.json\", \"w\") as fp:\n json.dump({\"data\": config._sections}, fp)\n\n\n# create alphabet\ndef create_alphabet():\n for letter in string.ascii_lowercase:\n store_text(letter, folder=\"ALPHABET\")\n\n\n# create number :\ndef create_numbers():\n number_questions = len(config[\"QUESTIONS\"])\n print(range(1, number_questions)[-1])\n for i in range(number_questions):\n store_text(str(i + 1), folder=\"NUMBER\")\n\n\n# create all sounds :\ndef create_all_sounds():\n for s in config.sections():\n if s != \"SOUNDS\":\n for k, v in config[s].items():\n store_text(v, k, s)\n\n\nif __name__ == \"__main__\":\n if args.alphabet:\n create_alphabet()\n \n if args.numbers:\n create_numbers()\n \n if args.config:\n create_config_json()\n \n if args.speech:\n create_all_sounds()\n \n\n if args.full:\n create_alphabet()\n create_numbers()\n create_all_sounds()\n create_config_json()\n\n","sub_path":"service/prepare_sounds.py","file_name":"prepare_sounds.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"36953912","text":"\r\nletters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']\r\nletters\r\n\r\nletters[2:5] = ['C', 'D', 'E']\r\nletters\r\n\r\n# now remove them\r\nletters[2:5] = []\r\nletters\r\n# clear the list by replacing all the elements with an empty list\r\nletters[:] = []\r\nletters\r\nlen(letters)\r\n","sub_path":"s0/h6.py","file_name":"h6.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"392058649","text":"import sqlite3\nimport logging\n\nfrom datetime import datetime\n\nclass sqlite_provider():\n\tdef __init__(self, config):\n\t\tlogging.debug('Sqlite provider init: config {}'.format(config))\n\t\tself.__config = config\n\t\tself.__filename = self.__config.find('file').text\n\t\tself.__datefmt = self.__config.find('dateformat').text\n\n\tdef connect(self):\n\t\tlogging.debug('Connecting to `{}`'.format(self.__filename))\n\t\tself.__cnx = sqlite3.connect(self.__filename)\n\n\tdef close(self):\n\t\tlogging.debug('Closing connection to `{}`'.format(self.__filename))\n\t\tself.__cnx.commit()\n\t\tself.__cnx.close()\n\n\tdef apply(self, fp):\n\t\tself.__cnx.executescript(fp.read())\n\n\tdef execute(self, query, **kw):\n\t\tfor k in kw:\n\t\t\tif type(kw[k]) == datetime:\n\t\t\t\tkw[k] = datetime.strftime(kw[k], self.__datefmt)\n\n\t\tquery = query.format(**kw)\n\t\tlogging.info(query)\n\n\t\tres = []\n\n\t\tfor row in self.__cnx.execute(query):\n\t\t\tdata = []\n\n\t\t\tfor idx, el in enumerate(row):\n\t\t\t\tif 'sqlitedatefmtids' in kw and idx in kw['sqlitedatefmtids']:\n\t\t\t\t\tdata.append(datetime.strptime(row[idx], self.__datefmt))\n\t\t\t\telse:\n\t\t\t\t\tdata.append(row[idx])\n\n\t\t\tres.append(data)\n\n\t\treturn res\n","sub_path":"stockviewer/stockviewer/db/provider/sqlite_provider.py","file_name":"sqlite_provider.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"291983834","text":"from os import getenv\n\nSOURCES = {\n \"news\": ('localhost', 40001),\n \"weather\": ('localhost', 40002),\n \"random.org\": ('localhost', 40003),\n \"twitter\": ('localhost', 40004),\n}\n\n# Timeouts in seconds\nTIMEOUTS = {\n \"news\": 10 * 60,\n \"weather\": 30 * 60,\n \"random.org\": 30,\n \"twitter\": 2 * 60,\n}\n\nREDIS_HOST = getenv('REDIS_HOST', 'localhost')\nREDIS_PORT = getenv('REDIS_PORT', 6379)\n","sub_path":"aggregator/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"174926965","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.cluster import KMeans\nfrom sklearn.linear_model import LogisticRegression, Lasso\n\n\n\ndef random_normal(nrow, ncol):\n W = np.zeros(ncol**2)\n W = W.reshape(ncol, -1)\n for i in range(ncol):\n for j in range(i, ncol):\n r = abs(round(np.random.normal(0, 2), 2))\n W[i, j] = r\n W[j, i] = r\n return(np.random.multivariate_normal(mean=[0] * ncol, cov = W, size = nrow))\n\nclass Ising:\n def __init__(self, W, u):\n #assert(W.shape[0] == W.shape[1] and W.shape[0] == u.shape[0])\n #assert(np.allclose(W, W.T, atol=1e-8))\n self.W = W\n self.u = u\n self.d = W.shape[0]\n \n @staticmethod\n def gibbs_sampling(model, n):\n X = np.array([+1 if np.random.rand() < .5 else -1 for i in range(model.d)])\n samples = [np.copy(X)]\n for i in range(2*n + 99):\n for j in range(model.d):\n p = model.conditonal(j, X)\n X[j] = +1 if np.random.rand() < p else -1\n samples.append(np.copy(X))\n return np.array(samples[100::2])\n \n \n @staticmethod\n def get_sample(W, n):\n u = np.zeros(W.shape[0])\n ising_model = Ising(W, u)\n return Ising.gibbs_sampling(ising_model, n)\n \n @staticmethod\n def random_coupling(ncol):\n W = np.zeros(ncol**2)\n W = W.reshape(ncol, -1)\n for j in range(int(30)):\n for i in range(ncol):\n x = np.random.choice(ncol, 1, replace=False)\n y = np.random.choice(i+1, 1, replace=False)\n r = round(np.random.normal(0, 1), 2)\n W[x, y] = r\n W[y, x] = r \n return(W)\n \n @staticmethod\n def save_ising(Z, W, name_theta = \"Theta.csv\", name_z = \"Z.csv\"):\n W_df = pd.DataFrame(W)\n W_df.to_csv(name_theta, index=False, index_label=False)\n Z_df = pd.DataFrame(Z)\n Z_df.to_csv(name_z, index=False, index_label=False)\n \n def conditonal(self, i, X):\n def sigmoid(x):\n return 1. / (1 + np.exp(-x))\n tmp = self.W[i, :].dot(X)\n return sigmoid(2 * (tmp + self.u[i]))\n\n def energy(self, X):\n return -X.dot(self.W).dot(X) - X.dot(self.u)\n\n\n\nclass Ising_Data:\n \n def __init__(self, Z):\n self.Z = Z\n \n def predict_cluster(self, k):\n kmeans = KMeans(n_clusters = k)\n kmeans.fit(self.Z)\n return(kmeans.predict(self.Z))\n \n def reduce_cluster(self, k):\n predicted_clusters = self.predict_cluster(k)\n Z_reduced = np.zeros(shape = (self.Z.shape[0], k)) - 1\n for i in range(self.Z.shape[0]):\n Z_reduced[i, predicted_clusters[i]] = 1\n states = predicted_clusters\n TM = np.zeros((len(np.unique(states)), len(np.unique(states))))\n for s in np.unique(states):\n c = 0\n n_transitions = sum(states[1:] == s)\n for i, ts in enumerate(states[1:]):\n if ts == s:\n TM[states[1:][i-1], ts] += 1/n_transitions\n TM = TM.T\n return(Z_reduced, TM)\n \n @staticmethod\n def joint_coupling(Z, Y):\n return(Z.T.dot(Y) / Z.shape[1])\n \n \n\n \n \n \n \n\n","sub_path":"KnockoffMixedGraphicalModel/isingutils.py","file_name":"isingutils.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"242443711","text":"import base64\nimport os\nimport random\nimport traceback\nfrom datetime import datetime\n\nimport pytz\nfrom django.db import connection\nfrom django.core.cache import cache\n\nfrom ..module import key_store\nfrom ...models import UploadToken\n\n\ndef get_bit_string(k=32):\n \"\"\"\n Get a set of random bits up to k length\n :param k: The number of bits to return\n :type k: int\n :return: A base64 encoded byte string\n :rtype: str\n \"\"\"\n return base64.b64encode(os.urandom(k))\n\n\ndef hex_string(value):\n \"\"\"\n Convert a string or bytes to a hex value\n :param value: The value to convert\n :type value: str\n :return: A string converted to a hex value\n :rtype: str\n \"\"\"\n return \"\".join([hex(c)[2:].zfill(2) for c in value])\n\n\ndef gen_upload_token(unique_data, max_length=32):\n \"\"\"\n Generate a license from a given key (private)\n\n :param unique_data: A unique identifier to include\n :type unique_data: object\n :param key: The key to use, preferably private\n :type key: str\n :param max_length: The maximum length of the secret defaulting to 128\n :type max_length: int\n :return: the license\n :rtype: str\n \"\"\"\n rbits = random.getrandbits(max_length)\n rbits = str(rbits).encode()\n ubytes = bytes(unique_data.encode())\n value = rbits + ubytes\n value = hex_string(value)\n return value\n\n\ndef is_valid_upload_token(user, token):\n \"\"\"\n Test to see if an upload token is valid.\n\n :param user: The user for\n :param token:\n :return:\n \"\"\"\n tkn = UploadToken.objects.filter(user_id=user.id).order_by('-expiration_date')\n try:\n if tkn.count() > 0:\n tkn = tkn.first()\n key = cache.get('PRIV_KEY', None)\n if key is None:\n key = key_store.load_private_key()\n key = base64.b64decode(key).decode('utf-8')\n cache.set('PRIV_KEY', key)\n if key:\n token = base64.b64decode(token)\n token = decrypt_data(key, token)\n if tkn == token:\n return (tkn.expiration_date < datetime.now(tz=pytz.utc))\n else:\n return False\n return False\n except Exception as e:\n tback = traceback.format_exc()\n print(tback)\n return False\n\n\ndef check_upload_token_validity(token, user):\n \"\"\"\n Checks the upload token and returns a potential error value\n\n :param token: The token to check against\n :type token: str\n :param user: The user to check against\n :type user: FileUser\n :return: The validity, error, and code tuple\n :rtype: tuple\n \"\"\"\n rtup = (False, '412 - Token or User Not Provided', 412)\n if token and user:\n ut = UploadToken.objects.filter(user=user, expiration_date__gte=datetime.now(tz=pytz.utc))\n print(ut)\n if ut.count() > 0:\n for utk in ut:\n if utk.token.decode() == token:\n return (True, None, 200)\n return (False, '401 - Token Not Found', 200)\n else:\n rtup = (False, '401 - Token Not Found', 401)\n sql = \"DELETE FROM filestorageapp_uploadtoken WHERE expiration_date < now()\"\n with connection.cursor() as cursor:\n cursor.execute(sql)\n return rtup\n","sub_path":"filestorage/filestorageapp/views/module/tokens.py","file_name":"tokens.py","file_ext":"py","file_size_in_byte":3308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"458852670","text":"#!/usr/bin/env Python\n#Este script se lanza cada vez que se inicie una Raspberry y se encarga de guardar en el servidor externo los datos del equipo para el evento actual\n#Habra un directorio(/home/pi/Monitor) en cada Rasberry con un archivo json que contiene la informacion para cada evento\nimport socket\nimport json\nimport requests\nimport sys\nimport paramiko\n\n#Lee el json con los datos del evento y los retorna\ndef obtener_info_equipo():\n try:\n with open('/home/pi/Pantalla/evento.json', 'r') as f:\n info = json.load(f)\n return info\n\n except IOError:\n print(\"No se ha podido abrir el archivo\")\n sys.exit()\n\n\n#Obtiene la ip priada del equipo y lo retorna\ndef obtener_ip_equipo():\n #nombre_equipo = socket.gethostname()\n # print(nombre_equipo)\n try:\n #ip_equipo = socket.gethostbyname(nombre_equipo)\n # print(ip_equipo)\n #if (not ip_equipo.startswith(\"10.\") or not ip_equipo.startswith(\"172.\") or not ip_equipo.startswith(\"192.\") or not ip_equipo.startswith(\"192.\")):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n ip_equipo = s.getsockname()[0]\n s.close()\n\n # if (ip_equipo.startswith(\"10.\") or ip_equipo.startswith(\"172.\") or ip_equipo.startswith(\"192.\") or ip_equipo.startswith(\"192.\")):\n #time.sleep(30)\n # url = 'localhost/Central/Raspberries/Central.php'\n #chrome_path = '/usr/bin/chromium'\n #webbrowser.get(chrome_path).open(url)\n\n\n\n except OSError as err:\n print(\"Error OS: {0}\".format(err))\n sys.exit()\n\n except:\n print(\"Error inesperado:\", sys.exc_info()[0])\n sys.exit()\n\n\n return ip_equipo\n\ndef obtener_ip_central():\n\t\n datos_raspberry = obtener_info_equipo()\n\n info = [datos_raspberry[\"CodEvento\"]]\n\n #print(info)\n \n\n parametros = {'CodEvento': datos_raspberry[\"CodEvento\"]}\n print(info)\n\n try:\t\n #msg = requests.get('http://192.168.181.1/dashboard/server/PDO/obtenerIPCentral.php', params=parametros)\n msg = requests.get('http://34.70.183.119/Login/db_scripts/obtenerIpCentral.php', params=parametros)\n print(msg.json()['IpPantalla'])\n #print(msg.json()['IpPantalla']+\"/ControlPaneles/Central/Raspberries/\"+datos_raspberry[\"CodPantalla\"]+\".php\")\n #print(msg.text)\n print(\"d\")\n return msg.json()['IpPantalla']\n except ConnectionError as err:\n # print(\"Error ConnectionError: {0}\".format(err))\n sys.exit()\n except OSError as err:\n # print(\"Error OS: {0}\".format(err))\n sys.exit()\n except:\n # print(\"Error inesperado:\", sys.exc_info()[0])\n sys.exit()\n\n#Una vez obtenidos todos los datos del equipo se guardarán en la BD\ndef almacenar_info_bd():\n \t\t\n datos_raspberry = obtener_info_equipo()\n\t\n ip_raspberry = obtener_ip_equipo()\n\n info = [datos_raspberry[\"CodEvento\"], datos_raspberry[\"CodPantalla\"], ip_raspberry, datos_raspberry[\"NomPantalla\"]]\n\n #print(info)\n\n parametros = {'CodEvento': info[0], 'CodPantalla': info[1], 'IpPantalla': info[2], 'NomPantalla': info[3]}\n try:\n \t \n #msg = requests.get('http://192.168.181.1/dashboard/server/PDO/almacenapantalla.php', params=parametros)\n msg = requests.get('http://34.70.183.119/Login/db_scripts/almacenapantalla.php', params=parametros) \n crear_template(info[1])\n \n return msg\n except ConnectionError as err:\n # print(\"Error ConnectionError: {0}\".format(err))\n sys.exit()\n except OSError as err:\n # print(\"Error OS: {0}\".format(err))\n sys.exit()\n except:\n # print(\"Error inesperado:\", sys.exc_info()[0])\n sys.exit()\n \n \ndef crear_template(codPantalla):\n\t\n\tip_central = obtener_ip_central()\n\tprint(\"d\")\n\tclient = paramiko.SSHClient()\n\tclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())\t\n\tclient.connect(ip_central, username=\"pi\", password=\"alvaro\")\n\tprint(ip_central)\n\t\n\thtml = \"<html ><head></head><body><style> <?php include '../css/templates.css'; ?> </style></body></html>\"\n\t\n\t\n\tclient.exec_command('echo \\\"'+html+'\\\" > /var/www/html/ControlPaneles/Central/Raspberries/' + str(codPantalla)+'.php')\n\t\n\tclient.exec_command('sudo chmod 777 /var/www/html/ControlPaneles/Central/Raspberries/'+ str(codPantalla)+'.php')\n\n\tclient.close()\n\t\n\t\nif __name__ == \"__main__\":\n almacenar_info_bd()\n","sub_path":"almacenar_pantalla.py","file_name":"almacenar_pantalla.py","file_ext":"py","file_size_in_byte":4466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"368990095","text":"import graphviz\r\nimport os, errno\r\n\r\ndef silentremove(filename):\r\n try:\r\n os.remove(filename)\r\n except OSError as e: # this would be \"except OSError, e:\" before Python 2.6\r\n if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory\r\n raise\r\n\r\nnums= [int(i) for i in input().split()]\r\nedges = list()\r\nfor i in range(nums[1]):\r\n edges.append([int(i) for i in input().split()])\r\ndot = graphviz.Graph(format = \"png\")\r\nfor i in range(1,nums[0]+1):\r\n dot.node(str(i))\r\nfor edge in edges:\r\n dot.edge(str(edge[0]),str(edge[1]))\r\n\r\nmatrix = []\r\nfor i in range(nums[0]):\r\n matrix.append([0 for i in range(nums[0])])\r\n\r\nfor edge in edges:\r\n matrix[edge[0]-1][edge[1]-1] = 1\r\n matrix[edge[1]-1][edge[0]-1] = 1\r\n\r\nsilentremove('graph')\r\nsilentremove('graph.png')\r\ndot.render(\"graph\", view = True)\r\nfor line in matrix:\r\n print (line)\r\n\r\n","sub_path":"lab2.3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"504543217","text":"import matplotlib \nmatplotlib.use('Agg') \nimport matplotlib.pyplot as plt\nimport keras\nfrom models import resnet_model,wide_residual_network as wrn, VGG_model as VGG\nfrom keras.optimizers import SGD\nfrom keras.callbacks import LearningRateScheduler\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras import backend as K\nimport numpy as np\nfrom callbacks.clr_callbacks import LossHistory\nimport argparse\nfrom data import data_generator\n\nparser = argparse.ArgumentParser(description='training the model')\nparser.add_argument('lr_1', type=float, metavar='lr_1',\n help='lr_1 maximum learning rate ')\nparser.add_argument('lr_2', type=float, metavar='lr_2',\n help='lr_2 minimum learning rate')\nparser.add_argument('model_type', type=str, default='resnet', metavar='model_type',\n help='model type (default:resnet)')\nparser.add_argument('num_classes', type=int, default=10, metavar='num_classes',\n help='num_classes (default:10)')\nparser.add_argument('dataset', type=str, default='cifar10', metavar='dataset',\n help='dataset (default:cifar10)')\nparser.add_argument('pretrain_model_path', type=str, metavar='pretrain_model_path',\n help='pretrain_model_path')\nparser.add_argument('pretrain_epochs', type=int, metavar='pretrain_epochs',\n help='pretrain_epochs')\nparser.add_argument('data_dir', type=str,default='/home/yj/dataset', metavar='data_dir',\n help='data_dir (default:/home/yj/dataset)')\nargs = parser.parse_args()\nbatch_size = 128 # orig paper trained all networks with batch_size=128\nepochs = args.pretrain_epochs\ndata_augmentation = True\nnum_classes = args.num_classes\nmodel_type = args.model_type\ndata_dir = args.data_dir\ndataset = args.dataset\niterations = 50000 // batch_size + 1\n# Subtracting pixel mean improves accuracy\nsubtract_pixel_mean = True\n\nlr_count = []\nn = 12\n\n# Model version\n# Orig paper: version = 1 (ResNet v1), Improved ResNet: version = 2 (ResNet v2)\nversion = 2\n\n# Computed depth from supplied model parameter n\nif version == 1:\n depth = n * 6 + 2\nelif version == 2:\n depth = n * 9 + 2\n\n# Model name, depth and version\n\nx_train, y_train, x_test, y_test = data_generator.load_data(model_type, num_classes, data_dir, dataset)\nprint(x_train.shape)\ninput_shape = x_train.shape[1:]\nprint(input_shape)\n\n\n\ninit_shape = (3, 32, 32) if K.image_dim_ordering() == 'th' else (32, 32, 3)\nif model_type == 'wrn':\n model = wrn.create_wide_residual_network(init_shape, nb_classes=num_classes, N=4, k=8, dropout=0.0)\nelif model_type == 'VGG': \n model = VGG.VGG_model(init_shape, num_classes = num_classes)\nelse: \n model = resnet_model.resnet_v2(input_shape=init_shape, depth=depth, num_classes = num_classes)\n\n\n \nmodel.compile(loss='categorical_crossentropy',\n optimizer=SGD(lr=0.5, decay=1e-5),\n metrics=['accuracy'])\n\n\n\nprint(model_type)\n\n# Prepare callbacks for model saving and for learning rate adjustment.\nlr_1 = args.lr_1\nlr_2 = args.lr_2\n#lr_3 = 0.5*1e-3\ngrad_down = (lr_1-lr_2)/30\ngrad_up = (lr_1-lr_2)/15\nlr_drop = 20\ndef lr_schedule_for_pretrain(epoch): #Customized Gradient Downward Learning Rate Schedule\n \"\"\"Learning Rate Schedule\n Learning rate is scheduled to be reduced after 80, 120, 160, 180 epochs.\n Called automatically every epoch as part of callbacks during training.\n # Arguments\n epoch (int): The number of epochs\n # Returns\n lr (float32): learning rate\n \"\"\"\n #lr = 5e-1\n lr = lr_1-grad_down * epoch\n if epoch > 30:\n lr = lr_2\n if epoch > 50:\n lr = lr_2 * 1e-1\n if epoch > 100:\n lr = lr_2 * 1e-2\n \n #elif epoch > 80:\n #lr *= 1e-1\n lr_count.append(lr)\n print('Learning rate: ', lr)\n return lr\n\n\ndef lr_scheduler(epoch):#Stepped-down Standard Learning Rate Schedule\n lr = lr_1 * (0.5 ** (epoch // lr_drop))\n lr_count.append(lr)\n print('Learning rate: ', lr)\n return lr\n\n\n\nlr_scheduler_for_train = LearningRateScheduler(lr_schedule_for_pretrain) \n\nreduce_lr = LearningRateScheduler(lr_scheduler)\nhistory = LossHistory()\nlr_reducer = ReduceLROnPlateau(factor=np.sqrt(0.1),\n cooldown=0,\n patience=5,\n min_lr=0.5e-6)\nmodel_accs = []\nepoch_count = []\n#save_pretrain_model = FGEModelCheckpoint(model_accs, epoch_count, 'wrn_c100')\ncbk = [lr_reducer, lr_scheduler_for_train, history]\n\n# Run training, with or without data augmentation.\n\nprint('Using real-time data augmentation.')\n # This will do preprocessing and realtime data augmentation:\ndatagen = data_generator.data_generator(model_type)\n\ndatagen.fit(x_train)\n\nmodel_path =args.pretrain_model_path # '/home/yj/resnet/wrn_28_10_model/model_wrn_150_c100.h5'\nmodel.fit_generator(datagen.flow(x_train, y_train, batch_size=batch_size),\n validation_data=(x_test, y_test),\n steps_per_epoch=iterations,\n epochs=epochs, verbose=1, workers=4,\n callbacks=cbk)\nmodel.save_weights(model_path)\n# Score trained model.\nscores = model.evaluate(x_test, y_test, verbose=1)\nprint('Test loss:', scores[0])\nprint('Test accuracy:', scores[1])\nhistory.loss_plot('epoch', lr_count, scores[1])\n\nplt.figure()\n\nplt.plot(epoch_count, model_accs, 'g', label='train accs')\n\nplt.grid(True)\nplt.xlabel('epoch')\nplt.ylabel('accs')\nplt.legend(loc=\"upper right\")\nplt.show()\nplt.savefig('pretrain_accs.jpg')\nplt.close()\n","sub_path":"pretrain_model.py","file_name":"pretrain_model.py","file_ext":"py","file_size_in_byte":5617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"561572944","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n\nimport getpass, imaplib\nimport email\nimport time\n\nhost = 'imap.qq.com'\nport = 993\n\nM = imaplib.IMAP4_SSL(host, port)\nM.login(\"3030613122@qq.com\", \"jqadfmklhpuzdddg\")\n\nresult, message = M.select(\"INBOX\", readonly=False)\nprint(result, message)\nindex = 0\n\nwhile True:\n time.sleep(0.1)\n data_type, data = M.search(None, '(FROM \"3030613122@qq.com\")')\n newlist = data[0].split()\n newest_inedx = len(newlist)\n\n if not (index == newest_inedx):\n index = newest_inedx\n if index == 0:\n continue\n data_type, data = M.fetch(newlist[newest_inedx-1], '(RFC822)')\n msg = email.message_from_string(data[0][1].decode('utf-8'))\n sub = msg.get('subject')\n print(sub)\n\n\n","sub_path":"app/imap.py","file_name":"imap.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"308016697","text":"entrada = int(input())\n\nlista_resultados = []\n\nfor x in range(0, entrada):\n # primeiro valor tem peso 2, o segundo valor\n # tem peso 3 e o terceiro valor tem peso 5\n entrada = input().split()\n valor1 = float(entrada[0]) * 2\n valor2 = float(entrada[1]) * 3\n valor3 = float(entrada[2]) * 5\n\n resultado = (valor1 + valor2 + valor3) / 10\n\n lista_resultados.append(resultado)\n\nfor num in lista_resultados:\n print(\"{0:1.2}\".format(num))\n","sub_path":"uri/beginner/1079.py","file_name":"1079.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"390625334","text":"# Tested and working for Splatoon 2.7.0 (NA)\n\nfrom tcpgecko import TCPGecko\nimport sys\nimport binascii\nsys.argv.append(\"270\")\n\ntcp = TCPGecko(\"XXX.XXX.XXX.XXX\") # Wii U IP address\nif sys.argv[1] == \"270\":\n def fillSlots(address):\n tcp.pokemem(address + 0x4, 4) \t# num. slots filled\n tcp.pokemem(address + 0x8, 4) \t# num. slots unlocked\n tcp.pokemem(address + 0x18, 0)\t# exp\n\n def giveTriples(address): # sets sub1 to sub2 and sub3\n val = int(binascii.hexlify(tcp.readmem(address + 0xC, 1)), 16) # C OR F??? FUCK\n tcp.pokemem(address + 0x10, val) # 1 -> 3\n tcp.pokemem(address + 0x14, val) # 1 -> 2\n\n hatMem = 0x12CD6DA0 # first hat ID\n shirtMem = 0x12CD3DA0 # first shirt ID\n shoeMem = 0x12CD0DA0 # first shoe ID\n\n cHat = cShirt = cShoe = 0;\n\n print(\"Starting hats, please hold...\")\n while (cHat < 85): # not the best way to go about this, but it works\n fillSlots(hatMem)\n giveTriples(hatMem)\n cHat += 1\n hatMem += 0x30 \t# shift to next gear piece\n print(\"Hats processed.\")\n\n print(\"Starting clothes...\")\n while (cShirt < 120): # does this work, even?\n fillSlots(shirtMem)\n giveTriples(shirtMem)\n cShirt += 1\n shirtMem += 0x30\n print(\"Shirts processed.\")\n\n print(\"Starting shoes...\")\n while (cShoe < 59):\n fillSlots(shoeMem)\n giveTriples(shoeMem)\n cShoe += 1\n shoeMem += 0x30\n print(\"Shoes processed.\")\n\n tcp.s.close()\n print(\"Done.\")\nelse:\n tcp.s.close()\n print(\"Unsupported Splatoon version.\")\n","sub_path":"gearsubs.py","file_name":"gearsubs.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"40662895","text":"#! /usr/bin/python3\nimport iota.harness.api as api\n\ndef validate_error_counters(errors_counters):\n is_error = False\n for counter in errors_counters:\n val = int(counter.split(\":\")[1])\n pname = counter.split(\":\")[0]\n if 0 < val < 10:\n api.Logger.warn(\"%s is occurred with counter %s \" % (pname, val))\n elif val > 10:\n api.Logger.error(\"%s is occurred with counter %s \" % (pname, val))\n is_error = True\n return is_error\n\n\ndef validate_full_reset_counters(errors_counters):\n errors = []\n for counter in errors_counters:\n val = int(counter.split(\":\")[1])\n if val != 0:\n errors.append(counter)\n return errors\n\ndef Setup(tc):\n tc.naples_nodes = api.GetNaplesNodes()\n if len(tc.naples_nodes) == 0:\n api.Logger.error(\"No naples node found\")\n return api.types.status.ERROR\n return api.types.status.SUCCESS\n\ndef Trigger(tc):\n req = api.Trigger_CreateExecuteCommandsRequest(serial=True)\n for n in tc.naples_nodes:\n api.Trigger_AddNaplesCommand(req, n.Name(), \"export LD_LIBRARY_PATH=/platform/lib:/nic/lib && export PATH=$PATH:/platform/bin && mctputil -i\")\n tc.resp = api.Trigger(req)\n return api.types.status.SUCCESS\n\ndef Verify(tc):\n for cmd in tc.resp.commands:\n api.PrintCommandResults(cmd)\n if cmd.exit_code == 0:\n if cmd.stdout:\n removed_hash = [row for row in cmd.stdout.split(\"\\n\") if \"#\" not in row]\n errors_counters = [row for row in removed_hash if \"error\" in row]\n full_reset_counters = [row for row in removed_hash if \"full_reset\" in row]\n is_error_counter = validate_error_counters(errors_counters)\n err_full_reset_counters = validate_full_reset_counters(full_reset_counters)\n if is_error_counter:\n return api.types.status.FAILURE\n elif err_full_reset_counters:\n api.Logger.error(\"Counter is occurred with parameter %s\" % \", \".join(err_full_reset_counters))\n return api.types.status.FAILURE\n else:\n return api.types.status.FAILURE\n return api.types.status.SUCCESS\n\ndef Teardown(tc):\n return api.types.status.SUCCESS","sub_path":"iota/test/iris/testcases/dell_idrac/check_mctp_counters.py","file_name":"check_mctp_counters.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"562783499","text":"# -*- coding: utf-8 -*-\n# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n'''\nSend Mail\n'''\nfrom nipype.interfaces.base import (\n BaseInterface, traits, TraitedSpec, \n BaseInterfaceInputSpec, isdefined, DynamicTraitedSpec, Undefined)\n\n\nclass MailMsgInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec):\n From = traits.String(\n mandatory=True, desc='From: e-mail adress')\n To = traits.String(mandatory=True, desc=\"To: e-mail adress\")\n Body = traits.String(mandatory=True, desc=\"Messsage body\")\n Subject = traits.String(mandatory=True, desc=\"Message subject\")\n\n _outputs = traits.Dict(traits.Any, value={}, usedefault=True)\n\n def __setattr__(self, key, value):\n if key not in self.copyable_trait_names():\n if not isdefined(value):\n super(MailMsgInputSpec, self).__setattr__(key, value)\n self._outputs[key] = value\n else:\n if key in self._outputs:\n self._outputs[key] = value\n super(MailMsgInputSpec, self).__setattr__(key, value)\n\n\nclass MailMsgOutputSpec(TraitedSpec):\n msg = traits.Any(desc='E-mail Message as Byte object')\n\n\nclass MailMsg(BaseInterface):\n \"\"\"Simple interface to cretae an e-mail object.\n\n Example\n -------\n\n >>> from cni.mail import MailMsg\n >>> mail = MailMsg()\n >>> mail.inputs.From = \"foo@bar.com\"\n >>> mail.inputs.To = \"example@site.com, other@site.com\"\n >>> mail.inputs.Subject = \"Hello World\"\n >>> mail.inputs.Body = \"My e-mail body\"\n >>> mail.run() # doctest: +SKIP\n \"\"\"\n input_spec = MailMsgInputSpec\n output_spec = MailMsgOutputSpec\n\n def __init__(self, infields=None, force_run=True, **kwargs):\n super(MailMsg, self).__init__(**kwargs)\n undefined_traits = {}\n self._infields = infields\n\n if infields:\n for key in infields:\n self.inputs.add_trait(key, traits.Any)\n self.inputs._outputs[key] = Undefined\n undefined_traits[key] = Undefined\n self.inputs.trait_set(trait_change_notify=False, **undefined_traits)\n\n if force_run:\n self._always_run = True\n\n def _run_interface(self, runtime):\n from email.mime.multipart import MIMEMultipart\n from email.mime.application import MIMEApplication\n from email.mime.text import MIMEText\n from os.path import basename\n\n self.msg = MIMEMultipart()\n\n input_dict = {}\n for key, val in list(self.inputs._outputs.items()):\n # expand lists to several columns\n if key == 'trait_added' and val in self.inputs.copyable_trait_names(\n ):\n continue\n\n if isinstance(val, list):\n for i, v in enumerate(val):\n input_dict['%s_%d' % (key, i)] = v\n else:\n input_dict[key] = val\n # use input_dict for attachments\n self.msg[\"Subject\"] = self.inputs.Subject\n self.msg[\"From\"] = self.inputs.From\n self.msg[\"To\"] = self.inputs.To\n self.msg.attach(MIMEText(self.inputs.Body))\n\n for fname in input_dict.values():\n with open(fname, 'rb') as f:\n part = MIMEApplication(f.read(),\n Name=basename(fname))\n # After the file is closed\n part['Content-Disposition'] = 'attachment; filename=\"%s\"' % basename(fname)\n self.msg.attach(part)\n\n return runtime\n\n def _list_outputs(self):\n outputs = self.output_spec().get()\n outputs['msg'] = self.msg.as_bytes()\n return outputs\n\n def _outputs(self):\n return self._add_output_traits(super(MailMsg, self)._outputs())\n\n def _add_output_traits(self, base):\n return base\n\n\nclass UnixSendmailInputSpec(BaseInterfaceInputSpec):\n msg = traits.Bytes(mandatory=True, desc='Mail message as byte')\n\nclass UnixSendmailOutputSpec(TraitedSpec):\n error = traits.Tuple(desc='Error message')\n\n\nclass UnixSendmail(BaseInterface):\n \"\"\"Simple interface to send an e-mail with /usr/bin/sendmail\n\n Example\n -------\n\n >>> from cni.mail import UnixSendmail\n >>> send = UnixSendmail()\n >>> send.inputs.msg = msg # as_byte()\n >>> send.run() # doctest: +SKIP\n \"\"\"\n input_spec = UnixSendmailInputSpec\n output_spec = UnixSendmailOutputSpec\n\n\n def _run_interface(self, runtime):\n from subprocess import Popen, PIPE\n p=Popen([\"/usr/sbin/sendmail\", \"-t\", \"-oi\"], stdin=PIPE)\n self.error = p.communicate(self.inputs.msg)\n return runtime\n\n def _list_outputs(self):\n outputs = self.output_spec().get()\n outputs['error'] = self.error\n return outputs\n","sub_path":"mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":4788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"163957688","text":"\n'''\nPrint out all of the numbers in the following array that are divisible by 3:\n'''\n\nnumber_list = [85, 46, 27, 81, 94, 9, 27, 38, 43, 99, 37, 63, 31, 42, 14]\n\n\n# need to loop and check if divisble by 3\n# print\n# in a func\n\ndef number(number_list):\n for i in number_list:\n if i % 3 == 0:\n print(i)\n\n\nnumber(number_list)\n","sub_path":"single_number/codeChallenge.py","file_name":"codeChallenge.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"63164539","text":"import pygame\nimport sys\nimport os\nimport random\n\n\n#TO DO:\n#Start anywhere\n#Add Moving Animation\n#Lift start orb\n#Add Gravity\n#Connect to monkeyrunner/androidviewclient\n\n\nclass Board:\n\n def __init__(self, dimension_of_board, tile_size, margin_size, board_pattern):\n self.board_pattern = board_pattern\n self.moves = []\n\n self.tile_size = tile_size\n self.margin_size = margin_size\n\n self.columns = dimension_of_board[0]\n self.rows = dimension_of_board[1]\n self.size = self.rows * self.columns\n\n self.orbkey = {'g': pygame.image.load('Green.png'),\n 'r': pygame.image.load('Red.png'),\n 'b': pygame.image.load('Blue.png'),\n 'l': pygame.image.load('Light.png'),\n 'd': pygame.image.load('Dark.png'),\n 'h': pygame.image.load('Heart.png'),\n 'x': pygame.image.load('Poison.png'),\n '*': pygame.image.load('Jammer.png')}\n\n self.tiles = [(x, y) for y in range(self.rows) for x in range(self.columns)]\n\n self.tilespos = {(x, y): (x * (tile_size + margin_size) + margin_size,\n y * (tile_size + margin_size) + margin_size)\n for y in range(self.rows) for x in range(self.columns)}\n\n # purely for monkeyRunner, if i can make that work\n self.orb_pattern = []\n for i in range(self.size):\n self.orb_pattern.append(self.orbkey.get(self.board_pattern[i]))\n\n # \"Blank\" - should be the orb you're holding\n def get_start_orb(self):\n # Currently always sets the start orb as the bottom right tile\n return self.tiles[-1]\n\n # Constantly update the current orb that is being held\n def set_start_orb(self, pos):\n self.tiles[-1] = pos\n\n opentile = property(get_start_orb, set_start_orb)\n\n def swap(self, tile):\n index = self.tiles.index(tile)\n self.tiles[index], self.opentile = self.opentile, self.tiles[index]\n\n def in_grid(self, tile):\n return tile[1] >= 0 and tile[1] < self.rows and tile[0] >= 0 and tile[0] <self.columns\n\n def adjacent(self):\n x,y = self.opentile\n return (x-1,y),(x+1,y),(x,y-1),(x,y+1)\n\n def update(self, dt):\n mouse = pygame.mouse.get_pressed()\n mpos = pygame.mouse.get_pos()\n if mouse[0]:\n ##maybe set opentile here\n tile = mpos[0] // (self.tile_size+self.margin_size), mpos[1] // (self.tile_size+self.margin_size)\n\n if self.in_grid(tile):\n if tile in self.adjacent():\n self.swap(tile)\n self.moves.append(tile)\n\n def draw(self, screen):\n\n for i in range(self.size):\n x, y = self.tilespos[self.tiles[i]]\n screen.blit(self.orb_pattern[i], (x -self.margin_size, y - self.margin_size))\n\n def print_moves(self):\n print( self.moves)\n\ndef generate_random_board():\n orbs = ['r', 'g', 'b', 'l', 'd', 'h']\n board = [random.choice(orbs) for i in range(30)]\n return board\n\n\ndef main():\n bg = pygame.image.load(\"bg.png\")\n\n pygame.init()\n os.environ['SDL_VIDEO_CENTERED'] = '1'\n pygame.display.set_caption('Pazudora')\n screen = pygame.display.set_mode((720, 600))\n fpsclock = pygame.time.Clock()\n ##tile size and margin size should add up to 120\n program = Board((6, 5), 118, 2, generate_random_board())\n\n while True:\n dt = fpsclock.tick() / 1000\n screen.fill((0, 0, 0))\n screen.blit(bg, (0, 0))\n program.draw(screen)\n pygame.display.flip()\n for event in pygame.event.get():\n if event.type == pygame.QUIT: program.print_moves();pygame.quit(); sys.exit()\n program.update(dt)\n\nmain()\n","sub_path":"Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":3805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"171129247","text":"#!/usr/bin/env python\n\n# \n# active.py: Manage active tasks, projects, and notifications.\n#\n# Author: Lain Supe (lainproliant)\n# Date: September 22nd, 2014\n#\n# Released under the GNU General Public License, version 3\n#\n\nimport getopt\nimport json\nimport os\nimport sys\n\n#-------------------------------------------------------------------\nSHORTOPTS = ''\nLONGOPTS = []\n\nDEFAULT_WORKSPACE_FILENAME = \"~/.workspace.json\"\n\n#--------------------------------------------------------------------\ndef full_path(path):\n \"\"\"\n Helper method for full expansion of filenames.\n \"\"\"\n\n return os.path.abspath(os.path.expanduser(path))\n\n#--------------------------------------------------------------------\nclass OptionValues():\n \"\"\"\n Wraps common opt/val logic to support getopt output.\n \"\"\"\n\n def __init__(self, opts):\n self.opts = opts\n\n def get_single(self, *args):\n \"\"\"\n Get a single option value matching the given opts,\n short or long.\n \"\"\"\n\n for opt, val in self.opts:\n if opt in args:\n return val\n\n return None\n\n def get_multi(self, *args):\n \"\"\"\n Get all option values matching the given opts,\n short or long.\n \"\"\"\n \n values = []\n\n for opt, val in self.opts:\n if opt in args:\n values.append(val)\n\n return values\n\n def has_option(self, *args):\n \"\"\"\n Determine if one of the given short or long opts\n was specified.\n \"\"\"\n\n for opt, val in self.opts:\n if opt in args:\n return True\n\n return False\n\n#--------------------------------------------------------------------\nclass Project():\n \"\"\"\n A Project is the realization of the wish to achieve a\n particular goal. Examples are:\n \n - Baking a pizza: because you're hungry and would like\n something to eat, or maybe you have a party of friends\n coming over and want to entertain them with food.\n - Writing this project management tool: I'm tired of\n forgetting what I'm working on and when it's due.\n - Assembling your new Ikea chair: You need a place to sit.\n\n In order to achieve the goal of any given Project, you\n must complete Tasks. Tasks are **actionable** items which\n can be achieved individually. Ideally, they are units of\n work which can be achieved in a single session.\n\n In this paradigm, we also assign Timers to Projects to help\n remind us of repeating triggers or assist us in completing\n Tasks.\n \"\"\"\n def __init__(self, name, tasks = [], timers = []):\n self.name = name\n self.tasks = tasks\n self.timers = timers\n self.activeTask = None\n \n def get_name(self):\n return self.name\n\n def get_active_task(self):\n \"\"\"\n Get the currently active task.\n Returns None if there isn't one.\n \"\"\"\n \n return self.activeTask\n\n def get_first_incomplete_task(self):\n \"\"\"\n Get the first task which has not been marked\n as completed, or None if there are none.\n \"\"\"\n\n incompleteTask = None\n \n for task in self.tasks:\n if not task.is_complete():\n incompleteTask = task\n break\n\n return incompleteTask\n\n def set_active_task(self, task):\n \"\"\"\n Set the currently active task. If the task is not\n in the list of project tasks, it is inserted before\n the first incomplete task.\n \"\"\"\n\n if task not in self.tasks:\n incompleteTask = self.get_first_incomplete_task()\n if incompleteTask is None:\n self.tasks.append(task)\n\n else:\n offset = self.tasks.index(incompleteTask)\n self.tasks.insert(offset, task)\n\n self.activeTask = task\n\n def is_complete(self):\n \"\"\"\n Determine if the project is complete.\n A project is considered complete when each of its\n tasks are complete.\n \"\"\"\n\n return self.get_first_incomplete_task() is None\n\n def insert_task(self, task, offset = None):\n \"\"\"\n Insert a task into the project. \n \"\"\"\n \n if task in self.tasks:\n self.tasks.remove(task)\n\n if offset is not None:\n self.tasks.insert(offset, task)\n\n else:\n self.tasks.append(task)\n\n @staticmethod\n def from_json(jsonData):\n \"\"\"\n Load a Project from the given JSON data.\n \"\"\"\n # TODO: Implement!\n tasks = [Task.from_json(x) for x in jsonData[\"tasks\"]]\n project = Project(jsonData[\"name\"], tasks)\n\n if \"activeTaskId\" in jsonData:\n activeTask = tasks[jsonData.activeTaskId]\n project.set_active_task(activeTask)\n\n return project\n \n def to_json(self):\n \"\"\"\n Serialize to JSON data.\n \"\"\"\n\n jsonData = {}\n jsonData[\"name\"] = self.name\n jsonData[\"tasks\"] = [x.to_json() for x in self.tasks]\n\n if self.activeTask is not None:\n jsonData[\"activeTaskId\"] = self.tasks.index(\n self.activeTask)\n\n return jsonData\n\n#--------------------------------------------------------------------\nclass Task():\n \"\"\"\n A Task is an individual unit of work.\n \"\"\"\n\n def __init__(self, name, complete = False):\n self.name = name\n self.complete = complete\n \n def get_name(self):\n return self.name\n\n def is_complete(self):\n return self.complete\n\n @staticmethod\n def from_json(jsonData):\n \"\"\"\n Load a Task from the given JSON data.\n \"\"\"\n \n return Task(jsonData[\"name\"], jsonData[\"complete\"])\n\n def to_json(self):\n \"\"\"\n Serialize to JSON data. \n \"\"\"\n\n return {\n \"name\": self.name,\n \"complete\": self.complete\n }\n \n#--------------------------------------------------------------------\nclass Timer():\n \"\"\"\n A timer is a reminder which helps you complete a task,\n or reminds you of an upcoming deadline or event.\n\n In this paradigm, Tasks are assoiated with a Project.\n \"\"\"\n\n def __init__(self, name, eventDate):\n self.name = name\n self.eventDate = eventDate\n\n def is_elapsed(self, date = None):\n \"\"\"\n Determine if the timer has elapsed.\n\n @param date The date at which to check. If not\n specified, the current date and time are assumed.\n \"\"\"\n # TODO: Implement!\n raise NotImplementedError\n \n @staticmethod\n def from_json(jsonData):\n # TODO: Implement!\n raise NotImplementedError\n\n def to_json(self):\n # TODO: Implement!\n raise NotImplementedError\n\n#--------------------------------------------------------------------\nclass Workspace():\n \"\"\"\n Stores information about the currently active projects,\n tasks, and timers.\n \"\"\"\n\n def __init__(self, projects = {}):\n self.projects = projects\n self.currentProject = None\n\n def get_active_project(self):\n return self.currentProject\n \n def add_project(self, project):\n \"\"\"\n Add a new project. It must have a unique name among\n all existing projects in the workspace.\n \"\"\"\n\n if project.get_name() in self.projects:\n raise Exception(\"A project named '%s' already exists.\" % (\n project.get_name()))\n\n self.projects[project.get_name()] = project\n\n def set_active_project(self, project):\n \"\"\"\n Set the current project. If this project is not yet in the\n workspace, it will be added.\n \"\"\"\n if project not in self.projects.values():\n self.add_project(project)\n\n self.currentProject = project\n\n @staticmethod\n def from_json(jsonData):\n projectList = [Project.from_json(x) for x in jsonData[\"projects\"]]\n projectMap = {x.get_name(): x for x in projectList}\n workspace = Workspace(projectMap)\n if \"currentProjectName\" in jsonData:\n workspace.set_active_project(projectMap[jsonData[\"currentProjectName\"]])\n\n return workspace\n\n def to_json(self):\n jsonData = {}\n jsonData[\"projects\"] = [x.to_json() for x in self.projects.values()]\n\n if self.currentProject is not None:\n jsonData[\"currentProjectName\"] = self.currentProject.get_name()\n\n return jsonData\n\n#--------------------------------------------------------------------\nclass ActiveApp():\n \"\"\"\n The main application component. Maintains a project file\n and sets up notification broadcasts and timed events.\n \"\"\"\n\n #----------------------------------------------------------------\n def __init__(self, opts, args):\n \"\"\"\n Constructor.\n \"\"\"\n \n self.opts = OptionValues(opts)\n self.args = args\n self.workspace = None\n self.filename = None\n self.activeData = self.load_workspace()\n\n #----------------------------------------------------------------\n def load_workspace(self):\n \"\"\"\n Load the current workspace from a JSON file.\n\n If no file is specified, this defaults to the\n \"~/.workspace.json\" file in the user's home directory.\n \"\"\"\n\n self.filename = self.opts.get_single(\"-w\", \"--workspace\") \\\n or DEFAULT_WORKSPACE_FILENAME\n\n if not os.path.isfile(full_path(self.filename)):\n print(\"No workspace file found at '%s', attempting to \"\n \"create a new one there...\", self.filename)\n self.workspace = Workspace()\n self.save_workspace()\n\n with open(full_path(self.filename), 'r') as input:\n self.workspace = Workspace.from_json(json.load(input))\n\n #----------------------------------------------------------------\n def save_workspace(self):\n \"\"\"\n Save the current workspace to disk at the same\n file location from which it was loaded.\n \"\"\"\n\n if self.filename is None:\n raise Exception(\"Workspace was not loaded!\")\n\n with open(full_path(self.filename), 'w', encoding = 'utf8') as output:\n json.dump(self.workspace.to_json(), output, indent = 4)\n\n #----------------------------------------------------------------\n def get_command_map(self):\n \"\"\"\n Get a map of instance bound method closures for each\n avaliable top-level command word.\n \"\"\"\n\n return {\n \"project-and-task\": self.print_project_and_task,\n \"project\": self.print_project,\n \"task\": self.print_task,\n \"add\": {\n \"project\": self.add_project,\n \"task\": self.add_task\n }\n }\n\n #----------------------------------------------------------------\n def get_command(self, commandMap, defaultCommand = None,\n parentWords = []):\n \"\"\"\n Get an instance bound method closure to be run for the\n current command, determined by the command line args.\n \"\"\"\n \n commandWord = None\n command = None\n\n if len(self.args) > 0:\n commandWord = self.args.pop(0)\n \n commandWord = commandWord or defaultCommand\n \n if commandWord is None:\n raise Exception(\"Missing subcommand for '%s' \"\n \"(one of [%s]).\" % (\n ' '.join(parentWords),\n ', '.join(commandMap.keys()))) \n \n if commandWord in commandMap:\n command = commandMap[commandWord]\n else:\n raise Exception(\"Unknown command '%s'.\" % (\n ' '.join(parentWords + [commandWord])))\n\n if isinstance(command, dict):\n return self.get_command(command,\n defaultCommand = None,\n parentWords = parentWords + [commandWord])\n\n else:\n return command\n\n #----------------------------------------------------------------\n def run(self):\n command = self.get_command(\n commandMap = self.get_command_map(),\n defaultCommand = \"project-and-task\")\n \n self.load_workspace()\n command()\n\n return 0\n\n #----------------------------------------------------------------\n def print_project_and_task(self):\n \"\"\"\n List the active project and task.\n \"\"\"\n \n self.print_project()\n self.print_task()\n\n #----------------------------------------------------------------\n def print_project(self):\n \"\"\"\n List the active project.\n \"\"\"\n \n project = self.workspace.get_active_project()\n \n if project is None:\n print(\"There is no active project.\")\n\n else:\n print(\"Project: %s\" % project.get_name())\n\n #----------------------------------------------------------------\n def print_task(self):\n \"\"\"\n Print the active task.\n \"\"\"\n \n project = self.workspace.get_active_project()\n\n if project is not None:\n task = project.get_active_task()\n \n if task is None:\n print(\"There are no tasks left to complete.\")\n\n else:\n print(task.get_name())\n\n #----------------------------------------------------------------\n def add_project(self):\n \"\"\"\n Add a new project.\n \"\"\"\n \n if len(self.args) < 1:\n raise Exception(\"A project name is required.\")\n\n project = Project(self.args.pop(0))\n self.workspace.set_active_project(project)\n self.save_workspace()\n \n print(\"Added project '%s'.\" % project.get_name())\n self.print_project_and_task()\n\n #----------------------------------------------------------------\n def add_task(self):\n \"\"\"\n Add a new task to the current project.\n \"\"\"\n\n if len(self.args) < 1:\n raise Exception(\"A task name is required.\")\n \n project = self.workspace.get_active_project()\n if project is None:\n raise Exception(\"Cannot add task because there is no \"\n \"active project. Please add a project first.\")\n\n task = Task(self.args.pop(0))\n project.insert_task(task)\n self.save_workspace()\n\n print(\"Added task '%s'.\" % task.get_name())\n self.print_task()\n\n#-------------------------------------------------------------------\nif __name__ == \"__main__\":\n opts, args = getopt.getopt(sys.argv[1:], SHORTOPTS, LONGOPTS)\n app = ActiveApp(opts, args)\n exitCode = app.run()\n sys.exit(exitCode)\n\n","sub_path":"active.py","file_name":"active.py","file_ext":"py","file_size_in_byte":15156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"224872786","text":"\"\"\" RandomSearchAgent module.\n\nAttributes:\n resulttuple (namedtuple): namedtuple contains lists of results.\n\"\"\"\nimport random\nimport itertools\nfrom collections import namedtuple\n\nfrom multiml import logger\nfrom multiml.agent.basic import BaseAgent\n\nresulttuple = namedtuple(\n 'resulttuple', ('task_ids', 'subtask_ids', 'subtask_hps', 'metric_value'))\n\n\nclass RandomSearchAgent(BaseAgent):\n \"\"\" Agent executing with only one possible hyper parameter combination.\n \"\"\"\n def __init__(self,\n samplings=[0],\n seed=0,\n metric_type=None,\n dump_all_results=False,\n **kwargs):\n \"\"\" Initialize simple agent.\n\n Args:\n samplings (int or list): If int, number of random samplings.\n If list, indexes of combination. \n seed (int): seed of random samplings.\n metric_type (str): 'min' or 'max' for indicating direction of\n metric optimization. If it is None, ``type`` is retrieved from\n metric class instance.\n dump_all_results (bool): dump all results or not.\n \"\"\"\n super().__init__(**kwargs)\n self._result = None # backward compatibility\n self._history = []\n self._samplings = samplings\n self._seed = seed\n self._dump_all_results = dump_all_results\n self._task_prod = self.task_scheduler.get_all_subtasks_with_hps()\n\n if metric_type is None:\n self._metric_type = self._metric.type\n else:\n self._metric_type = metric_type\n\n random.seed(seed)\n\n @property\n def result(self):\n \"\"\" Return result of execution.\n \"\"\"\n return self._result\n\n @result.setter\n def result(self, result):\n \"\"\" Set result of execution.\n \"\"\"\n self._result = result\n\n @logger.logging\n def execute(self):\n \"\"\" Execute simple agent.\n \"\"\"\n if isinstance(self._samplings, int):\n samples = range(0, len(self.task_scheduler))\n self._samplings = random.sample(samples, k=self._samplings)\n\n for counter, index in enumerate(self._samplings):\n subtasktuples = self.task_scheduler[index]\n self._history.append(self.execute_pipeline(subtasktuples, counter))\n\n @logger.logging\n def finalize(self):\n \"\"\" Finalize grid scan agent.\n \"\"\"\n # backward compatibility\n if self._result is not None:\n self.finalize_legacy()\n return\n\n if self._dump_all_results:\n logger.header1('All results')\n for result in self._history:\n self._print_result(result)\n logger.header1('Best results')\n\n metrics = [result.metric_value for result in self._history]\n if self._metric_type == 'max':\n index = metrics.index(max(metrics))\n elif self._metric_type == 'min':\n index = metrics.index(min(metrics))\n else:\n raise NotImplementedError(\n f'{self._metric_type} is not valid option.')\n best_result = self._history[index]\n self._print_result(best_result)\n\n scan_history = [{\n \"task_ids\": result.task_ids,\n \"subtask_ids\": result.subtask_ids,\n \"subtask_hps\": result.subtask_hps,\n \"metric_value\": result.metric_value\n } for result in self._history]\n\n self._saver.add('scan_history', scan_history)\n\n self._saver.add('result.task_ids', best_result.task_ids)\n self._saver.add('result.subtask_ids', best_result.subtask_ids)\n self._saver.add('result.subtask_hps', best_result.subtask_hps)\n self._saver.add('result.metric_value', best_result.metric_value)\n\n self._best_result = best_result\n\n self._saver.save()\n\n @logger.logging\n def finalize_legacy(self):\n \"\"\" Finalize simple agent. Result is shown and saved.\n \"\"\"\n self._print_result(self._result)\n\n self._saver.add('result.task_ids', self._result.task_ids)\n self._saver.add('result.subtask_ids', self._result.subtask_ids)\n self._saver.add('result.subtask_hps', self._result.subtask_hps)\n self._saver.add('result.metric_value', self._result.metric_value)\n\n self._saver.save()\n\n def get_best_result(self):\n \"\"\" Return the best result.\n \"\"\"\n return self._best_result\n\n def execute_pipeline(self, subtasktuples, counter):\n \"\"\" Execute pipeline.\n \"\"\"\n result_task_ids = []\n result_subtask_ids = []\n result_subtask_hps = []\n\n for subtasktuple in subtasktuples:\n task_id = subtasktuple.task_id\n subtask_id = subtasktuple.subtask_id\n subtask_env = subtasktuple.env\n subtask_hps = subtasktuple.hps.copy()\n subtask_hps['job_id'] = counter\n\n subtask_env.saver = self._saver\n subtask_env.set_hps(subtask_hps)\n self._execute_subtask(subtasktuple)\n\n result_task_ids.append(task_id)\n result_subtask_ids.append(subtask_id)\n result_subtask_hps.append(subtask_hps)\n\n self._metric.storegate = self._storegate\n metric = self._metric.calculate()\n\n return resulttuple(result_task_ids, result_subtask_ids,\n result_subtask_hps, metric)\n\n def _execute_subtask(self, subtask):\n \"\"\" Execute subtask.\n \"\"\"\n subtask.env.storegate = self._storegate\n subtask.env.saver = self._saver\n subtask.env.execute()\n subtask.env.finalize()\n\n def _print_result(self, result):\n \"\"\" Show result.\n \"\"\"\n logger.header2('Result')\n for task_id, subtask_id, subtask_hp in zip(result.task_ids,\n result.subtask_ids,\n result.subtask_hps):\n logger.info(f'task_id {task_id} and subtask_id {subtask_id} with:')\n if subtask_hp is None or len(subtask_hp) == 0:\n logger.info(' No hyperparameters')\n else:\n for key, value in subtask_hp.items():\n logger.info(f' {key} = {value}')\n logger.info(f'Metric ({self._metric.name}) is {result.metric_value}')\n","sub_path":"multiml/agent/basic/random_search.py","file_name":"random_search.py","file_ext":"py","file_size_in_byte":6348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"589780466","text":"#!/usr/bin/env python3\n###############################################################################\n# Author: Agustin Bassi\n# Date: July 2020\n# Copyright: Bankar\n# Project: Bankar Python code challenge\n# Brief: Project to test skill working with Python & REST APIs\n###############################################################################\n\n#########[ Imports ]########################################################### \n\nimport datetime\nimport json\n\nfrom . import db\n\n#########[ Module main code ]##################################################\n\nclass StateModel(db.Model):\n\n \"\"\"\n StateModel Model\n \"\"\"\n\n __tablename__ = 'states'\n\n id = db.Column(db.Integer, primary_key=True)\n code = db.Column(db.Integer, nullable=False, index=True, unique=True)\n name = db.Column(db.String(64), nullable=False)\n created_at = db.Column(db.DateTime)\n updated_at = db.Column(db.DateTime)\n\n user = db.relationship('UserModel', backref='state', lazy='dynamic')\n\n def __init__(self, data):\n self.code = data.get('code')\n self.name = data.get('name')\n self.created_at = datetime.datetime.utcnow()\n self.updated_at = datetime.datetime.utcnow()\n StateModel.check_if_table_exists()\n\n\n def save(self):\n if not StateModel.check_if_code_exists(self.code):\n db.session.add(self)\n db.session.commit()\n return True\n return False\n\n def update(self, data):\n if not StateModel.check_if_code_exists(self.code):\n for key, item in data.items():\n setattr(self, key, item)\n self.updated_at = datetime.datetime.utcnow()\n db.session.commit()\n return True\n return False\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n @staticmethod\n def get_all_states():\n return StateModel.query.all()\n\n @staticmethod\n def get_one_state(id):\n return StateModel.query.get(id)\n\n @staticmethod\n def get_by_code(code):\n return StateModel.query.filter_by(code=code).first()\n\n @staticmethod\n def check_if_code_exists(code):\n if StateModel.query.filter_by(code=code).first():\n return True\n return False\n\n @staticmethod\n def check_if_table_exists():\n states = None\n try:\n states = StateModel.get_all_states()\n except:\n pass\n if not states:\n db.create_all()\n \n def __repr__(self):\n return {\n \"id\" : self.id,\n \"code\" : self.code,\n \"name\" : self.name,\n \"created_at\" : self.created_at.strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"updated_at\" : self.updated_at.strftime(\"%Y-%m-%d %H:%M:%S\"),\n }\n\n def serialize(self):\n return {\n \"id\" : self.id,\n \"code\" : self.code,\n \"name\" : self.name,\n \"created_at\" : self.created_at.strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"updated_at\" : self.updated_at.strftime(\"%Y-%m-%d %H:%M:%S\"),\n }\n\n#########[ end of file ]#######################################################","sub_path":"src/models/state_model.py","file_name":"state_model.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"188265504","text":"# -*- coding: utf-8 -*-\n\"\"\"Load coverage in chanjo database.\"\"\"\nimport logging\n\nfrom chanjo.cli.load import load_transcripts\nfrom chanjo.store.txmodels import BASE as TXBASE, Sample, TranscriptStat\nfrom chanjo.store import Store\nfrom pymip.api import load_analysis\nfrom sqlalchemy.exc import IntegrityError\n\nlogger = logging.getLogger(__name__)\n\n\ndef load(chanjo_db, bed_stream, source=None, sample=None, group=None,\n threshold=None):\n \"\"\"Load coverage data for a sample into the database.\"\"\"\n try:\n load_transcripts(chanjo_db, bed_stream, source=source,\n sample=sample, group=group, threshold=threshold)\n except IntegrityError as error:\n logger.warn(error)\n chanjo_db.session.rollback()\n\n\ndef remove(chanjo_db, group_id):\n logger.debug(\"find samples in database with id: %s\", group_id)\n sample_objs = chanjo_db.query(Sample).filter_by(group_id=group_id)\n\n for sample_obj in sample_objs:\n logger.debug(\"delete exon statistics for %s\", sample_obj.id)\n (chanjo_db.query(TranscriptStat)\n .filter(TranscriptStat.sample_id == sample_obj.id)\n .delete())\n logger.debug(\"delete '%s' from database\", sample_obj.id)\n chanjo_db.session.delete(sample_obj)\n chanjo_db.save()\n\n\ndef is_loaded(group_id):\n \"\"\"Check if a group of samples are already loaded in chanjo.\"\"\"\n query = Sample.query.filter_by(group_id=group_id)\n return query.first() is not None\n\n\ndef parse_mip(mip_analysis, use_family=False):\n \"\"\"Parse out what to upload.\"\"\"\n for sample_id, bed_path in mip_analysis.chanjo_sample_outputs():\n if use_family:\n sample_id = \"{}-{}\".format(mip_analysis.family_id, sample_id)\n yield sample_id, bed_path\n\n\ndef upload(chanjo_db, sample_id, group_id, bed_path, threshold=10):\n \"\"\"Upload coverage for a sample to the database.\"\"\"\n with open(bed_path, 'r') as bed_stream:\n load(chanjo_db, bed_stream, source=bed_path, group=group_id,\n sample=sample_id, threshold=threshold)\n\n\ndef parse_payload(db, payload, config, force=False):\n \"\"\"Process payload for coverage.\"\"\"\n mip_analysis = load_analysis(payload['family_dir'])\n chanjo_db = Store(config['CHANJO_URI'], base=TXBASE)\n group_id = payload['case_id']\n\n if force:\n remove(chanjo_db, group_id)\n\n if not is_loaded(group_id):\n samples = parse_mip(mip_analysis)\n for sample_id, bed_path in samples:\n logger.info(\"load coverage for %s\", sample_id)\n upload(chanjo_db, sample_id, group_id, bed_path)\n else:\n logger.info(\"samples already loaded: %s\", group_id)\n","sub_path":"moneypenny/flow/mutations/coverage.py","file_name":"coverage.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"34604191","text":"import os, pygame\n\n# game information\n################\nMAX_GAME = 4578\nNUM_SPRITES = 4\n################\n\n# addressing\n################\nIMAGE_PATH = os.getcwd() + \"\\\\images\\\\\"\nWEB_ADDR = \"http://www.j-archive.com/showgame.php?game_id=\"\nWEB_ADDR_RESP = \"http://j-archive.com/showgameresponses.php?game_id=\"\n################\n\n# default resolutions\n################\nRES = (1244, 700)\nBOARD_SIZE = (780, 480)\nBLOCK_SIZE = (130, 80)\nCHAR_SIZE = (180, 200)\n################\n\n# useful location tuples\n################\nBOARD_CENTER_LOC = (BOARD_SIZE[0]/2, BOARD_SIZE[1]/2)\n################\n\n# colour values\n################\nBLUE = 0, 80, 140\nRED = 240, 0, 0\nBLACK = 0, 0, 0\nWHITE = 255, 255, 255\nYELLOW = 200, 150, 30\nCOLOR_KEY = 0, 255, 0\n################\n\n# point value defaults\n################\nPOINT_VALUES = [[100, 200, 300, 400, 500], [200, 400, 600, 800, 1000]]\n################\n\n# font defaults\n################\npygame.font.init()\n\nKORINNA = []\nfor i in range(1, 65):\n\tKORINNA.append(pygame.font.SysFont(\"korinna regular\", i))\n\nHELVETICA = []\nfor i in range(1, 65):\n\tHELVETICA.append(pygame.font.SysFont(\"impact\", i))\n\t\nDIGITAL = []\nfor i in range(1, 65):\n\tDIGITAL.append(pygame.font.SysFont(\"DS-Digital\", i))\n################","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"222113656","text":"from typing import List, Union\n\nfrom pandas import DataFrame\nfrom pydantic import Field\n\nfrom weaverbird.render_variables import StepWithVariablesMixin\nfrom weaverbird.steps import BaseStep\nfrom weaverbird.types import ColumnName, DomainRetriever, PipelineExecutor, TemplatedVariable\n\n\nclass UnpivotStep(BaseStep):\n name = Field('unpivot', const=True)\n keep: List[ColumnName]\n unpivot: List[ColumnName]\n unpivot_column_name: ColumnName\n value_column_name: ColumnName\n dropna: bool\n\n def execute(\n self,\n df: DataFrame,\n domain_retriever: DomainRetriever = None,\n execute_pipeline: PipelineExecutor = None,\n ) -> DataFrame:\n df_melted = df.melt(\n id_vars=self.keep,\n value_vars=self.unpivot,\n var_name=self.unpivot_column_name,\n value_name=self.value_column_name,\n )\n return df_melted.dropna(subset=[self.value_column_name]) if self.dropna else df_melted\n\n\nclass UnpivotStepWithVariable(UnpivotStep, StepWithVariablesMixin):\n keep: Union[TemplatedVariable, List[TemplatedVariable]]\n unpivot: Union[TemplatedVariable, List[TemplatedVariable]]\n","sub_path":"server/weaverbird/steps/unpivot.py","file_name":"unpivot.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"488911794","text":"# ERPNext - web based ERP (http://erpnext.com)\n# Copyright (C) 2012 Web Notes Technologies Pvt Ltd\n# \n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n# Add Columns\n# ------------\ncolnames[colnames.index('Rate*')] = 'Rate' \ncol_idx['Rate'] = col_idx['Rate*']\ncol_idx.pop('Rate*')\ncolnames[colnames.index('Amount*')] = 'Amount' \ncol_idx['Amount'] = col_idx['Amount*']\ncol_idx.pop('Amount*')\n\ncolumns = [['Valuation Rate','Currency','150px',''],\n ['Valuation Amount','Currency','150px',''],\n ['Gross Profit (%)','Currrency','150px',''],\n ['Gross Profit','Currency','150px','']]\n\nfor c in columns:\n colnames.append(c[0])\n coltypes.append(c[1])\n colwidths.append(c[2])\n coloptions.append(c[3])\n col_idx[c[0]] = len(colnames)-1\n\nout, tot_amount, tot_val_amount, tot_gross_profit = [], 0, 0, 0\n\nfor r in res:\n tot_val_rate = 0\n packing_list_items = sql(\"select item_code, warehouse, qty from `tabDelivery Note Packing Detail` where parent = %s and parent_item = %s\", (r[col_idx['ID']], r[col_idx['Item Code']]))\n for d in packing_list_items:\n if d[1]:\n val_rate = sql(\"select valuation_rate from `tabStock Ledger Entry` where item_code = %s and warehouse = %s and voucher_type = 'Delivery Note' and voucher_no = %s and is_cancelled = 'No'\", (d[0], d[1], r[col_idx['ID']]))\n val_rate = val_rate and val_rate[0][0] or 0\n if r[col_idx['Quantity']]: tot_val_rate += (flt(val_rate) * flt(d[2]) / flt(r[col_idx['Quantity']]))\n else: tot_val_rate = 0\n\n r.append(fmt_money(tot_val_rate))\n\n val_amount = flt(tot_val_rate) * flt(r[col_idx['Quantity']])\n r.append(fmt_money(val_amount))\n\n gp = flt(r[col_idx['Amount']]) - flt(val_amount)\n \n if val_amount: gp_percent = gp * 100 / val_amount\n else: gp_percent = gp\n \n r.append(fmt_money(gp_percent))\n r.append(fmt_money(gp))\n out.append(r)\n\n tot_gross_profit += flt(gp)\n tot_amount += flt(r[col_idx['Amount']])\n tot_val_amount += flt(val_amount) \n\n# Add Total Row\n# --------------\nl_row = ['' for i in range(len(colnames))]\nl_row[col_idx['Quantity']] = '<b>TOTALS</b>'\nl_row[col_idx['Amount']] = fmt_money(tot_amount)\nl_row[col_idx['Valuation Amount']] = fmt_money(tot_val_amount)\nif tot_val_amount: l_row[col_idx['Gross Profit (%)']] = fmt_money((tot_amount - tot_val_amount) * 100 / tot_val_amount)\nelse: l_row[col_idx['Gross Profit (%)']] = fmt_money(tot_amount)\nl_row[col_idx['Gross Profit']] = fmt_money(tot_gross_profit)\nout.append(l_row)","sub_path":"erpnext/selling/search_criteria/gross_profit/gross_profit.py","file_name":"gross_profit.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"191066245","text":"\"\"\"empty message\n\nRevision ID: f64a274c2886\nRevises: 2e9655d9e64c\nCreate Date: 2019-10-23 00:25:39.436434\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = 'f64a274c2886'\ndown_revision = '4490c017f6e4'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # creating the extension should only occur once. No need to include for future trigram indicies\n op.execute('CREATE EXTENSION IF NOT EXISTS pg_trgm;')\n op.create_index(op.f('ix_artist_trgm_name'), 'Artist', ['name'], postgresql_using='gin',\n postgresql_ops={\n 'name': 'gin_trgm_ops',\n }, unique=False)\n op.create_index(op.f('ix_venue_trgm_name'), 'Venue', ['name'], postgresql_using='gin',\n postgresql_ops={\n 'name': 'gin_trgm_ops',\n }, unique=False)\n # ### commands auto generated by Alembic - please adjust! ###\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_artist_trgm_name'), table_name='Artist')\n op.drop_index(op.f('ix_venue_trgm_name'), table_name='Venue')\n # ### end Alembic commands ###\n","sub_path":"projects/01_fyyur/migrations/versions/f64a274c2886_.py","file_name":"f64a274c2886_.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"26214747","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtCore import QTimer, QRect, QDateTime\nfrom PyQt5.QtGui import QFont\nfrom PyQt5.QtWidgets import QMessageBox, QPushButton, QLabel\nfrom BankGUI.AccountCsv import get_account\nfrom ChangePin import Ui_change_pin_window\nfrom Deposit import Ui_deposit_window\nfrom Withdraw import Ui_withdraw_window\n\n\nclass UiMainMenu(object):\n\n def thank_you_window(self, main_menu):\n from ThankYou import UiThankYouMenu\n self.thank_you_menu = QtWidgets.QMainWindow()\n self.ui = UiThankYouMenu()\n self.ui.setupUi(self.thank_you_menu)\n self.log_in_window(main_menu)\n self.thank_you_menu.show()\n QTimer.singleShot(5000, self.thank_you_menu.close)\n\n def log_in_window(self, main_menu):\n from Login import UiLoginWindow\n self.LoginWindow = QtWidgets.QMainWindow()\n self.ui = UiLoginWindow()\n self.ui.setupUi(self.LoginWindow)\n main_menu.hide()\n self.LoginWindow.show()\n\n def deposit_window(self, user_index, username):\n self.deposit_window = QtWidgets.QMainWindow()\n self.ui = Ui_deposit_window()\n self.ui.setupUi(self.deposit_window, user_index, username)\n self.deposit_window.show()\n\n def withdraw_window(self, user_index, username):\n self.withdraw_window = QtWidgets.QMainWindow()\n self.ui = Ui_withdraw_window()\n self.ui.setupUi(self.withdraw_window, user_index, username)\n self.withdraw_window.show()\n\n def show_balance(self, user_index):\n balance = get_account()[user_index][3]\n message = QMessageBox()\n message.setWindowTitle(\"Balance Inquiry\")\n message.setText(f\"Your balance is {'₱{:,.2f}'.format(int(balance))}\")\n message.setIcon(QMessageBox.Information)\n message.exec_()\n\n def change_pin_window(self, user_index, username):\n self.change_pin_window = QtWidgets.QMainWindow()\n self.ui = Ui_change_pin_window()\n self.ui.setupUi(self.change_pin_window, user_index, username)\n self.change_pin_window.show()\n\n def user_transactions_window(self, user_index, username):\n from UserViewTransactions import Ui_User_View_Transaction\n self.User_View_Transaction = QtWidgets.QMainWindow()\n self.ui = Ui_User_View_Transaction()\n self.ui.setupUi(self.User_View_Transaction, user_index, username)\n self.User_View_Transaction.show()\n\n def showTime(self):\n current_time = QDateTime.currentDateTime().toString('hh:mm:ss ap\\ndddd yyyy MMMM dd')\n self.clock_label.setText(current_time)\n\n def setupUi(self, main_menu, user_index, username):\n main_menu.setObjectName(\"main_menu\")\n main_menu.resize(800, 600)\n main_menu.setStyleSheet(\"background-color: rgb(85, 116, 255);\\n\"\n \"background-color: rgb(0, 0, 127);\")\n self.centralwidget = QtWidgets.QWidget(main_menu)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.atm_label = QtWidgets.QLabel(self.centralwidget)\n self.atm_label.setGeometry(QtCore.QRect(20, 30, 211, 71))\n font = QtGui.QFont()\n font.setPointSize(72)\n font.setBold(True)\n font.setWeight(75)\n self.atm_label.setFont(font)\n self.atm_label.setStyleSheet(\"color: rgb(255, 255, 255);\")\n self.atm_label.setObjectName(\"atm_label\")\n timer = QTimer(self.centralwidget)\n timer.timeout.connect(self.showTime)\n timer.start(0)\n font4 = QFont()\n font4.setPointSize(18)\n font4.setBold(True)\n font4.setWeight(75)\n self.clock_label = QLabel(self.centralwidget)\n self.clock_label.setObjectName(u\"clock_label\")\n self.clock_label.setGeometry(QRect(260, 30, 401, 61))\n self.clock_label.setFont(font4)\n self.clock_label.setStyleSheet(u\"color: rgb(255, 255, 255);\")\n self.welcome_label = QtWidgets.QLabel(self.centralwidget)\n self.welcome_label.setGeometry(QtCore.QRect(20, 140, 101, 31))\n font = QtGui.QFont()\n font.setPointSize(16)\n font.setBold(True)\n font.setWeight(75)\n self.welcome_label.setFont(font)\n self.welcome_label.setStyleSheet(\"color: rgb(0, 0, 127);\\n\"\n \"color: rgb(85, 170, 255);\")\n self.welcome_label.setObjectName(\"welcome_label\")\n self.name_label = QtWidgets.QLabel(self.centralwidget)\n self.name_label.setGeometry(QtCore.QRect(20, 190, 231, 51))\n font = QtGui.QFont()\n font.setPointSize(14)\n font.setBold(True)\n font.setWeight(75)\n self.name_label.setFont(font)\n self.name_label.setStyleSheet(\"color: rgb(255, 255, 255);\")\n self.name_label.setObjectName(\"name_label\")\n self.name_label.setText(get_account()[user_index][0])\n self.withdraw_button = QPushButton(self.centralwidget, clicked=lambda: self.withdraw_window(user_index, username))\n self.withdraw_button.setGeometry(QtCore.QRect(530, 180, 251, 81))\n font = QtGui.QFont()\n font.setPointSize(22)\n font.setBold(True)\n font.setWeight(75)\n self.withdraw_button.setFont(font)\n self.withdraw_button.setStyleSheet(\"color: rgb(255, 255, 255);\\n\"\n \"background-color: rgb(85, 170, 255);\")\n self.withdraw_button.setObjectName(\"withdraw_button\")\n self.withdraw_button.clicked.connect(lambda: main_menu.hide())\n self.deposit_button = QPushButton(self.centralwidget, clicked=lambda: self.deposit_window(user_index, username))\n self.deposit_button.setGeometry(QtCore.QRect(260, 180, 251, 81))\n font = QtGui.QFont()\n font.setPointSize(22)\n font.setBold(True)\n font.setWeight(75)\n self.deposit_button.setFont(font)\n self.deposit_button.setStyleSheet(\"background-color: rgb(85, 170, 255);\\n\"\n \"color: rgb(255, 255, 255);\")\n self.deposit_button.setObjectName(\"deposit_button\")\n self.deposit_button.clicked.connect(lambda: main_menu.hide())\n self.changepin_button = QPushButton(self.centralwidget, clicked=lambda: self.change_pin_window(user_index, username))\n self.changepin_button.setGeometry(QtCore.QRect(530, 300, 251, 81))\n font = QtGui.QFont()\n font.setPointSize(22)\n font.setBold(True)\n font.setWeight(75)\n self.changepin_button.setFont(font)\n self.changepin_button.setStyleSheet(\"color: rgb(255, 255, 255);\\n\"\n \"background-color: rgb(85, 170, 255);\")\n self.changepin_button.setObjectName(\"changepin_button\")\n self.changepin_button.clicked.connect(lambda: main_menu.hide())\n self.balinquiry_button = QPushButton(self.centralwidget, clicked=lambda: self.show_balance(user_index))\n self.balinquiry_button.setGeometry(QtCore.QRect(260, 300, 251, 81))\n font = QtGui.QFont()\n font.setPointSize(18)\n font.setBold(True)\n font.setWeight(75)\n self.balinquiry_button.setFont(font)\n self.balinquiry_button.setStyleSheet(\"color: rgb(255, 255, 255);\\n\"\n \"background-color: rgb(85, 170, 255);\")\n self.balinquiry_button.setObjectName(\"balinquiry_button\")\n self.logo_label = QtWidgets.QLabel(self.centralwidget)\n self.logo_label.setGeometry(QtCore.QRect(680, 20, 91, 81))\n self.logo_label.setText(\"\")\n self.logo_label.setPixmap(QtGui.QPixmap(\"../../images/Bank logo 1.png\"))\n self.logo_label.setObjectName(\"logo_label\")\n self.exit_button = QPushButton(self.centralwidget, clicked=lambda: self.thank_you_window(main_menu))\n self.exit_button.setGeometry(QtCore.QRect(40, 410, 161, 71))\n font = QtGui.QFont()\n font.setFamily(\"MS Shell Dlg 2\")\n font.setPointSize(22)\n font.setBold(True)\n font.setItalic(False)\n font.setWeight(75)\n self.exit_button.setFont(font)\n self.exit_button.setStyleSheet(\"color: rgb(255, 255, 255);\\n\"\n \"background-color: rgb(170, 0, 0);\")\n self.exit_button.setObjectName(\"pushButton\")\n main_menu.setCentralWidget(self.centralwidget)\n self.statusbar = QtWidgets.QStatusBar(main_menu)\n self.statusbar.setObjectName(\"statusbar\")\n main_menu.setStatusBar(self.statusbar)\n self.view_transactions_button = QPushButton(self.centralwidget, clicked=lambda: self.user_transactions_window(user_index, username))\n self.view_transactions_button.clicked.connect(lambda: main_menu.hide())\n self.view_transactions_button.setObjectName(u\"view_transactions_button\")\n self.view_transactions_button.setGeometry(QRect(640, 150, 141, 21))\n font6 = QFont()\n font6.setPointSize(10)\n font6.setBold(False)\n font6.setWeight(50)\n self.view_transactions_button.setFont(font6)\n self.view_transactions_button.setStyleSheet(u\"color: rgb(255, 255, 255);\\n\"\n \"background-color: rgb(85, 170, 255);\")\n self.retranslateUi(main_menu)\n QtCore.QMetaObject.connectSlotsByName(main_menu)\n\n def retranslateUi(self, main_menu):\n _translate = QtCore.QCoreApplication.translate\n main_menu.setWindowTitle(_translate(\"main_menu\", \"Main Menu\"))\n self.atm_label.setText(_translate(\"main_menu\", \"ATM\"))\n self.welcome_label.setText(_translate(\"main_menu\", \"Welcome\"))\n self.withdraw_button.setText(_translate(\"main_menu\", \"WITHDRAW\"))\n self.deposit_button.setText(_translate(\"main_menu\", \"DEPOSIT\"))\n self.changepin_button.setText(_translate(\"main_menu\", \"CHANGE PIN\"))\n self.balinquiry_button.setText(_translate(\"main_menu\", \"BALANCE INQUIRY\"))\n self.exit_button.setText(_translate(\"main_menu\", \"LOGOUT\"))\n self.view_transactions_button.setText(_translate(\"main_menu\", \"View Transactions\"))\n\n\nif __name__ == \"__main__\":\n import sys\n\n app = QtWidgets.QApplication(sys.argv)\n main_menu = QtWidgets.QMainWindow()\n ui = UiMainMenu()\n ui.setupUi(main_menu, 0, \"user\")\n main_menu.show()\n sys.exit(app.exec_())\n","sub_path":"BankWithDatabase/UserMethods/MainMenu.py","file_name":"MainMenu.py","file_ext":"py","file_size_in_byte":10266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"278647166","text":"#!/usr/bin/env python\n#\n# tournament.py -- implementation of a Swiss-system tournament\n#\n\nimport psycopg2\n\n\ndef connect():\n \"\"\"Connect to the PostgreSQL database. Returns a database connection.\"\"\"\n return psycopg2.connect(\"dbname=tournament\")\n\n\ndef deleteMatches():\n \"\"\"Remove all the match records from the database.\"\"\"\n\n db = connect()\n c = db.cursor()\n c.execute(\"DELETE FROM matches;\")\n db.commit()\n db.close()\n\n\ndef deletePlayers():\n \"\"\"Remove all the player records from the database.\"\"\"\n\n db = connect()\n c = db.cursor()\n c.execute(\"DELETE FROM players;\")\n db.commit()\n db.close()\n\n\ndef countPlayers():\n \"\"\"Returns the number of players currently registered.\"\"\"\n\n db = connect()\n c = db.cursor()\n c.execute(\"SELECT count(*) FROM players;\")\n rows = c.fetchall()\n db.close()\n return rows[0][0]\n\n\ndef registerPlayer(name):\n \"\"\"Adds a player to the tournament database.\n\n The database assigns a unique serial id number for the player. (This\n should be handled by your SQL database schema, not in your Python code.)\n\n Args:\n name: the player's full name (need not be unique).\n \"\"\"\n\n db = connect()\n c = db.cursor()\n c.execute(\"INSERT INTO players (name) VALUES(%s)\", (name,))\n db.commit()\n db.close()\n\n\ndef playerStandings():\n \"\"\"Returns a list of the players and their win records, sorted by wins.\n\n The first entry in the list should be the player in first place, or a\n player tied for first place if there is currently a tie.\n\n Returns:\n A list of tuples, each of which contains (id, name, wins, matches):\n id: the player's unique id (assigned by the database)\n name: the player's full name (as registered)\n wins: the number of matches the player has won\n matches: the number of matches the player has played\n \"\"\"\n\n db = connect()\n c = db.cursor()\n c.execute(\"SELECT * FROM standings;\")\n results = c.fetchall()\n db.close()\n\n return results\n\n\ndef reportMatch(winner, loser):\n \"\"\"Records the outcome of a single match between two players.\n\n Args:\n winner: the id number of the player who won\n loser: the id number of the player who lost\n \"\"\"\n\n db = connect()\n c = db.cursor()\n c.execute(\n \"INSERT INTO matches(winner, loser) VALUES(%s, %s);\", (winner, loser))\n db.commit()\n db.close()\n\n\ndef removePreviousOpponents(player, matches):\n \"\"\"Returns a list of previous opponents for the player.\n\n Removes the corresponding matches from the 'matches' list.\n The 'matches' list contains tuples from selecting the entire\n 'matches' table.\n\n Returns:\n A list of unique player id's.\n \"\"\"\n\n previousOpponents = []\n for i, m in enumerate(matches):\n if player == matches[i][0]:\n previousOpponents.append(matches[i][1])\n matches.pop(i)\n elif player == matches[i][1]:\n previousOpponents.append(matches[i][0])\n matches.pop(i)\n\n return previousOpponents\n\n\ndef isNewOpponent(player, opponents):\n \"\"\"Return a True if player is not in the opponents list.\n\n player is a player id.\n\n Returns:\n false if the player is in the opponents list.\n \"\"\"\n\n try:\n opponents.index(player)\n isNewOpponent = False\n except ValueError:\n isNewOpponent = True\n\n return isNewOpponent\n\n\ndef swissPairings():\n \"\"\"Returns a list of pairs of players for the next round of a match.\n\n Assuming that there are an even number of players registered, each player\n appears exactly once in the pairings. Each player is paired with another\n player with an equal or nearly-equal win record, that is, a player\n adjacent to him or her in the standings.\n\n Returns:\n A list of tuples, each of which contains (id1, name1, id2, name2)\n id1: the first player's unique id\n name1: the first player's name\n id2: the second player's unique id\n name2: the second player's name\n \"\"\"\n\n # Need standings and matches to construct new pairings.\n standings = playerStandings()\n\n # Get the matches data.\n db = connect()\n c = db.cursor()\n c.execute(\"SELECT winner, loser FROM matches;\")\n matches = c.fetchall()\n\n # Generate and record the pairings\n pairings = []\n while len(standings) != 0:\n # Take next player from standings\n nextPlayer = standings[0]\n standings.pop(0)\n\n # Compile all his previous opponents. List of player ids.\n previousOpponents = removePreviousOpponents(nextPlayer, matches)\n\n # Go back to the standings to find the next opponent\n nextOpponent = None\n for i, p in enumerate(standings):\n if isNewOpponent(p[0], previousOpponents):\n nextOpponent = standings[i]\n standings.pop(i)\n break\n\n # Add pair to the schedule\n pairings.append(\n (nextPlayer[0], nextPlayer[1], nextOpponent[0], nextOpponent[1]))\n\n db.close\n\n return pairings\n","sub_path":"tournament.py","file_name":"tournament.py","file_ext":"py","file_size_in_byte":5055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"309760263","text":"# file which contains the spider used by scrapy for the information extraction\n\nimport scrapy\nimport itertools\nfrom yahoofinance_scrapyutils import *\n\n\n# get the company and column information\nCOMPANY_NAMES = get_companies(\"./company-names/sample_symbols.txt\")\nCOLUMN_NAMES = get_column_names(\"./column-names/default_column_names_no_units.txt\")\n\n\n# set the urls to be scraped\nURLS = ('https://ca.finance.yahoo.com/quote/' + ticker + '/key-statistics?p=' + ticker for ticker in COMPANY_NAMES)\n\n\n# define a spider class to be used to scrape information\nclass YahooFinanceSpider(scrapy.Spider):\n name = \"yahoo-finance\"\n start_urls = URLS\n \n def parse(self, response):\n company_name = response.url.split('=')[1] # gets company name from url\n company_column = zip(['Company'], [company_name]) # just here to be able to make generator\n column_names = (cn.get() for cn in response.xpath('//tr/td[1]/span/text()')) # get column names from response\n information = (info.get() for info in response.xpath('//tr/td[2]//text()')) # get data from response\n data = zip(column_names, information) # combine column names and data\n converted_data = (convert_data(dt) for dt in data) # convert units to numbers\n labeled_data = company_column # initialize final generator with company column\n for cdt in converted_data: # build final generator... see note below\n labeled_data = itertools.chain(labeled_data, cdt)\n filtered_data = (ldt for ldt in labeled_data if ldt[0] in COLUMN_NAMES) # get only the columns you want\n \n yield dict(filtered_data)\n \n\n\"\"\"\ni am not sure if i should make such extensive use of generators, but since we don't want to do anything with this \ninformation other than copy it to a file, i think it makes some sense. however, to get the speed improvements \nfrom using a generator, it makes the code a little convoluted because of how i create the table to be exported to \na csv file. \n\nbackground on table construction:\nfor a column name like `Shares short (Nov. 30, 2020)' with data `2.00', i actually split this up into\ntwo data points. the first is one with column name `Shares short' and data `2.00'; the other is with column name\n`Date: Shares short' and data `Nov. 30, 2020'. i hope this makes sense and makes for easier integration of data\nin the future, as these particular column names are dynamic, meaning they will change in a month or so. basically,\ni formatted it in a way such that i split the column name which changes over time to two column names which don't \nchange over time, and i made the changing part of the old column name to be the data part of the new column name.\n\nhow this affects code:\nthis table construction, unfortunately, makes the code using generators a bit trickier... and a bit inelegant, but\nperhaps it is faster. i have to basically zip everything in the convert_data function, and then i have a generator\nof zips which have to be chained to become a single generator so it can be outputted correctly to csv. i have to \nzip things because the convert_data function returns a single tuple in the cases which don't have a column name\nwhich is dynamic, but it returns *two* tuples in the case where the column name is dynamic (as explained above).\nzipping things basically abstracts away the difference by making them both of the zipped type. then we can link\nthem using itertools.\n\"\"\"","sub_path":"yahoofinance_scrapy.py","file_name":"yahoofinance_scrapy.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"517617574","text":"from pettingzoo import AECEnv\nfrom pettingzoo.utils.agent_selector import agent_selector\nfrom gym import spaces\nimport random\nimport rlcard\nfrom rlcard.utils.utils import print_card\nfrom rlcard.games.gin_rummy.player import GinRummyPlayer\nfrom rlcard.games.gin_rummy.utils import utils\nfrom rlcard.games.gin_rummy.utils.action_event import KnockAction, GinAction\nimport rlcard.games.gin_rummy.utils.melding as melding\nimport numpy as np\nfrom pettingzoo.utils import wrappers\n\n\ndef env(**kwargs):\n env = raw_env(**kwargs)\n env = wrappers.TerminateIllegalWrapper(env, illegal_reward=-1)\n env = wrappers.AssertOutOfBoundsWrapper(env)\n env = wrappers.NaNRandomWrapper(env)\n env = wrappers.OrderEnforcingWrapper(env)\n return env\n\n\nclass raw_env(AECEnv):\n\n metadata = {'render.modes': ['human']}\n\n def __init__(self, seed=None, knock_reward: float = 0.5, gin_reward: float = 1.0):\n super().__init__()\n self._knock_reward = knock_reward\n self._gin_reward = gin_reward\n self.env = rlcard.make('gin-rummy', config={\"seed\": seed})\n self.agents = ['player_0', 'player_1']\n self.num_agents = len(self.agents)\n self.has_reset = False\n\n self.observation_spaces = self._convert_to_dict([spaces.Box(low=0.0, high=1.0, shape=(5, 52), dtype=np.bool) for _ in range(self.num_agents)])\n self.action_spaces = self._convert_to_dict([spaces.Discrete(self.env.game.get_action_num()) for _ in range(self.num_agents)])\n\n self.agent_order = self.agents\n self._agent_selector = agent_selector(self.agent_order)\n self.env.game.judge.scorer.get_payoff = self._get_payoff\n\n def _int_to_name(self, ind):\n return self.agents[ind]\n\n def _name_to_int(self, name):\n return self.agents.index(name)\n\n def _convert_to_dict(self, list_of_list):\n return dict(zip(self.agents, list_of_list))\n\n def _get_payoff(self, player: GinRummyPlayer, game) -> float:\n going_out_action = game.round.going_out_action\n going_out_player_id = game.round.going_out_player_id\n if going_out_player_id == player.player_id and type(going_out_action) is KnockAction:\n payoff = self._knock_reward\n elif going_out_player_id == player.player_id and type(going_out_action) is GinAction:\n payoff = self._gin_reward\n else:\n hand = player.hand\n best_meld_clusters = melding.get_best_meld_clusters(hand=hand)\n best_meld_cluster = [] if not best_meld_clusters else best_meld_clusters[0]\n deadwood_count = utils.get_deadwood_count(hand, best_meld_cluster)\n payoff = -deadwood_count / 100\n return payoff\n\n def observe(self, agent):\n obs = self.env.get_state(self._name_to_int(agent))\n return obs['obs'].astype(np.bool)\n\n def step(self, action, observe=True):\n obs, next_player_id = self.env.step(action)\n next_player = self._int_to_name(next_player_id)\n self._last_obs = obs['obs']\n self.prev_player = self.agent_selection\n prev_player_ind = self.agent_order.index(self.prev_player)\n curr_player_ind = self.agent_order.index(next_player)\n if next_player == self.prev_player:\n self.agent_order.insert(0, self.agent_order.pop(-1))\n elif prev_player_ind == self.num_agents - 1:\n self.agent_order.remove(next_player)\n self.agent_order.insert(0, next_player)\n else:\n self.agent_order.remove(next_player)\n if curr_player_ind < prev_player_ind:\n self.agent_order.insert(0, self.agent_order.pop(-1))\n self.agent_order.insert(self.agent_order.index(self.prev_player) + 1, next_player)\n skip_agent = prev_player_ind + 1\n self._agent_selector.reinit(self.agent_order)\n for _ in range(skip_agent):\n self._agent_selector.next()\n if self.env.is_over():\n self.rewards = self._convert_to_dict(self.env.get_payoffs())\n self.infos[next_player]['legal_moves'] = [4]\n self.dones = self._convert_to_dict([True if self.env.is_over() else False for _ in range(self.num_agents)])\n else:\n self.infos[next_player]['legal_moves'] = obs['legal_actions']\n self.agent_selection = self._agent_selector.next()\n if observe:\n return obs['obs'].astype(np.bool) if obs else self._last_obs.astype(np.bool)\n\n def reset(self, observe=True):\n self.has_reset = True\n obs, player_id = self.env.reset()\n self.agent_order = [self._int_to_name(agent) for agent in [player_id, 0 if player_id == 1 else 1]]\n self._agent_selector.reinit(self.agent_order)\n self.agent_selection = self._agent_selector.reset()\n self.rewards = self._convert_to_dict(np.array([0.0, 0.0]))\n self.dones = self._convert_to_dict([False for _ in range(self.num_agents)])\n self.infos = self._convert_to_dict([{'legal_moves': []} for _ in range(self.num_agents)])\n self.infos[self._int_to_name(player_id)]['legal_moves'] = obs['legal_actions']\n self._last_obs = obs['obs']\n if observe:\n return obs['obs'].astype(np.bool)\n else:\n return\n\n def render(self, mode='human'):\n for player in self.agents:\n state = self.env.game.round.players[self._name_to_int(player)].hand\n print(\"\\n===== {}'s Hand =====\".format(player))\n print_card([c.__str__()[::-1] for c in state])\n state = self.env.game.get_state(0)\n print(\"\\n==== Top Discarded Card ====\")\n print_card([c.__str__() for c in state['top_discard']] if state else None)\n print('\\n')\n\n def close(self):\n pass\n","sub_path":"pettingzoo/classic/gin_rummy/gin_rummy.py","file_name":"gin_rummy.py","file_ext":"py","file_size_in_byte":5733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"286812492","text":"import pandas as pd\r\nimport numpy as np\r\nimport os\r\nimport glob\r\nimport random\r\n\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\ntrain = pd.read_csv('/data/dacon/practice/train/train.csv')\r\ntrain.tail()\r\nsubmission = pd.read_csv('/data/dacon/practice/sample_submission.csv')\r\nsubmission.tail()\r\n\r\ndef preprocess_data(data, is_train=True):\r\n\r\n temp = data.copy()\r\n temp = temp[['Hour','TARGET','DHI','DNI','WS','RH','T']]\r\n\r\n if is_train==True:\r\n\r\n temp['Target1'] = temp['TARGET'].shift(-48).fillna(method='ffill') #1day\r\n temp['Target2'] = temp['TARGET'].shift(-48*2).fillna(method='ffill') #2day\r\n temp = temp.dropna()\r\n\r\n return temp.iloc[:-96]\r\n\r\n elif is_train==False :\r\n \r\n temp = temp[['Hour','TARGET','DHI','DNI','WS','RH','T']]\r\n\r\n return temp.iloc[-48:,:]\r\n \r\ndf_train = preprocess_data(train)\r\ndf_train.iloc[:48]#첫째날\r\n\r\ntrain.iloc[48:96] #두번쨰날\r\ntrain.iloc[48+48:96+48]#셋째날\r\ndf_train.tail()\r\n\r\ndf_test = []\r\n\r\nfor i in range(81):\r\n file_path = '/data/dacon/practice/test/' + str(i) + '.csv'\r\n temp = pd.read_csv(file_path)\r\n temp = preprocess_data(temp, is_train=False)\r\n df_test.append(temp)\r\n\r\nX_test = pd.concat(df_test)\r\nX_test.shape\r\nX_test.head(48)\r\ndf_train.head()\r\ndf_train.iloc[-48:]\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nX_train_1, X_valid_1, Y_train_1, Y_valid_1 = train_test_split(df_train.iloc[:,:-2], df_train.iloc[:,:-2], test_size=0.3,random_state=0)\r\nX_train_2, X_valid_2, Y_train_2, Y_valid_2 = train_test_split(df_train.iloc[:,:-2], df_train.iloc[:,:-1], test_size=0.3,random_state=0)\r\n\r\nX_train_1.head()\r\nX_test.head()\r\nX_test.head()\r\n\r\nquantiles = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\r\n\r\nfrom lightlgbm import LGBMRegressor\r\n\r\ndef LGBM(q, X_train, Y_train, X_valid, Y_valid, X_test ):\r\n #(a) Modeling\r\n model = LGBMRegressor(objective = 'quantile', alpha =q ,n_estimators = 10000, bagging_fraction =0.7,\r\n learning_rate = 0.027, subsample =0.7)\r\n model.fit(X_train, Y_train, eval_metric = ['quantile'], eval_set = [(X_valid, Y_valid)],\r\n early_stopping_rounds=300, verbose=500)\r\n \r\n #(b) Predcitions\r\n pred = pd.Series(model.predict(X_test).round(2))\r\n return pred, model\r\n\r\n#Target \r\ndef train_data(X_train, Y_train, X_valid, Y_valid, X_test) :\r\n\r\n LGBM_models = []\r\n LGBM_actual_pred = pd.DataFrame()\r\n\r\n for q in quantiles:\r\n print(q)\r\n pred, model = LGBM(q, X_train, Y_train, X_valid, Y_valid, X_test)\r\n LGBM_models.append(model)\r\n LGBM_actual_pred = pd.concat([LGBM_actual_pred.pred], axis=1)\r\n\r\n LGBM_actual_pred.columns = quantiles\r\n return LGBM_models, LGBM_actual_pred\r\n\r\n\r\n#4.EVALUATE\r\n#Target1\r\nmodels_1, results_1 = train_data(X_train_1, Y_train_1, X_valid_1, Y_valid_1,X_test)\r\nresults_1.sort_index()[:48]\r\n\r\n#Target2\r\nmodels_2, results_2 = train_data(X_train_2, Y_train_2,X_valid_2, Y_valid_2, X_test)\r\nresults_2.sort_index()[:48]\r\n\r\nresults_1.sort_index().iloc[:48]\r\nresults_2.sort_index()\r\nprint(results_1.shape, results_2.shape)\r\n\r\n#submission에 값 집어넣기\r\nsubmission.loc[submission.id.str.contains(\"Day7\"), \"q_0.1\":] = results_1.sort_index().values\r\nsubmission.loc[submission.id.str.contains(\"Day8\"), \"q_0.1\":] = results_2.sort_index().values\r\nsubmission\r\n\r\nsubmission.iloc[:48] #47행까지 넣기(48개의 하루치데이터)\r\n\r\nsubmission.to_csv('./data/submission_v3.csv', index=False) #제출용데이터 생성","sub_path":"dacon/solar/py/dacon_solar_1_0120_LGBM.py","file_name":"dacon_solar_1_0120_LGBM.py","file_ext":"py","file_size_in_byte":3505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"259943264","text":"# Developed by Jinmo Rhee\r\n# all rights reserved by Jinmo Rhee\r\n# leeuack@jinmorhee.net, www.jinmorhee.net\r\n\r\n'''CumInCAD Crawler by Keywords'''\r\n# ----------------------------------------------------------------------------------------------------------------------\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nimport os\r\nimport re\r\nimport time\r\n# ----------------------------------------------------------------------------------------------------------------------\r\n\r\nfolder = \"raw_data/\"\r\nvalid_paper = 'all_valid_papers.csv'\r\n\r\n#please change the search words\r\nsearch_words = [\"arhcitecture\"]\r\n\r\n\r\ndef searchWord(w):\r\n '''check the word w is in the publication information'''\r\n return re.compile(r'\\b({0})\\b'.format(w), flags=re.IGNORECASE).search\r\n\r\ndef searchContainment(words, conents):\r\n '''check whether the contents have words or not'''\r\n for word in words:\r\n if searchWord(word)(conents) != None:\r\n print(word)\r\n return True\r\n return False\r\n\r\ndef getPapers(main_soup):\r\n '''find all papers link and return the list of papers'''\r\n form = main_soup.find('form', attrs={'name': 'main'})\r\n papers = form.find_all('a')[::2]\r\n return papers\r\n\r\ndef getPaperInfo(paper):\r\n '''extract information of the input paper, input is id of a paper'''\r\n data = []\r\n paper_site = str(paper).replace(\"<\", \"*\").replace(\">\", \"*\").split(\"*\")[1][8:-1] # generate paper url\r\n\r\n #scraping\r\n paper_request = requests.get(paper_site)\r\n main_soup = BeautifulSoup(paper_request.text, 'html.parser')\r\n paper_table_1 = main_soup.find_all('tr', attrs={'class': 'DATA'})\r\n score = 0\r\n\r\n for row in paper_table_1:\r\n cols = row.find_all('td')\r\n item = [ele.text.strip() for ele in cols]\r\n filter = searchContainment(search_words, item[0].lower()) # check a paper is relevant\r\n score += filter # score is how many words in contents are related to the keywords\r\n data.append(item)\r\n if score > 0:\r\n df = pd.DataFrame(data)\r\n filename = folder + paper_site.split(\"/\")[-1] + \".csv\" # make a new folder named as paper id\r\n df.to_csv(filename, sep=\",\", encoding='utf-8-sig') # save as csv file\r\n\r\ndef countPapers(folder):\r\n '''count the number of currently scraped paper'''\r\n return len(os.listdir(folder))\r\n\r\ndef main(total=15260): # the total number of the paper is changing, so users should check the total number of the paper before run this function\r\n '''wrapper function of scraper'''\r\n page_number = 0\r\n count = 0\r\n results_per_page = 20 # the default values of results per page is 20\r\n while page_number <= total:\r\n # access the main site, e.g. CumInCAD\r\n main_site = \"http://papers.cumincad.org/cgi-bin/works/Search?&first={}\".format(page_number)\r\n # the first page of archive\r\n print(page_number)\r\n main_request = requests.get(main_site)\r\n main_soup = BeautifulSoup(main_request.text, 'html.parser')\r\n # get the papers in the page\r\n papers = getPapers(main_soup)\r\n # extract paper info\r\n for paper in papers:\r\n start = time.time()\r\n getPaperInfo(paper)\r\n count += 1\r\n end = time.time()\r\n print(\"{}/{} {} papers, {} sec\".format(count, total, countPapers(folder), end - start))\r\n page_number += results_per_page # 20 is the hardcoded number \r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"81767754","text":"from importlib.util import find_spec\n\n\ntry:\n from kedro.framework.hooks import hook_impl\nexcept ModuleNotFoundError:\n\n def hook_impl(func):\n return func\n\n\nif find_spec(\"mlflow\"):\n from mlflow import log_metric, log_param\n\n class MLflowOutputsLoggerHook:\n @hook_impl\n def after_node_run(self, node, catalog, inputs, outputs):\n for name, value in outputs.items():\n if isinstance(value, str):\n log_param(name, value[:250])\n continue\n if isinstance(value, (float, int)):\n log_metric(name, float(value))\n continue\n if isinstance(value, (list, tuple)):\n if all([isinstance(e, str) for e in value]):\n log_param(name, \", \".join(value))\n continue\n for i, e in enumerate(value):\n if isinstance(e, (float, int)):\n log_metric(name, float(e), step=i)\n else:\n break\n\n\nelse:\n\n class MLflowOutputsLoggerHook:\n def after_node_run(self, node, catalog, inputs, outputs):\n pass\n","sub_path":"src/pipelinex/extras/hooks/mlflow_outputs_logger.py","file_name":"mlflow_outputs_logger.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"597321735","text":"import logging\n\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.conf import settings\nfrom django.template.loader import render_to_string\n\nfrom us_ignite.snippets.models import Snippet\n\nlogger = logging.getLogger('us_ignite.profiles')\n\n\ndef send_welcome_email(user, **kwargs):\n \"\"\"Sends a welcome email to the given ``User``\"\"\"\n if 'sender' in kwargs:\n logger.debug('Welcome email send via %s', kwargs['sender'])\n context = {\n 'user': user,\n 'object': Snippet.published.get_from_key('welcome-email')\n }\n _template = lambda t: 'profile/emails/welcome_%s' % t\n subject = render_to_string(_template('subject.txt'), context)\n subject = ''.join(subject.splitlines())\n body = render_to_string(_template('body.txt'), context)\n body_html = render_to_string(_template('body.html'), context)\n email = EmailMultiAlternatives(\n subject, body, settings.DEFAULT_FROM_EMAIL, [user.email])\n email.attach_alternative(body_html, \"text/html\")\n return email.send()\n","sub_path":"us_ignite/profiles/communications.py","file_name":"communications.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"393972256","text":"################################################################################\n################ Modelling of the twitter feeds ################################\n################################################################################\n\n### The modelling is done in\n## Step 1) Extract tweets only for selected ticker\n## Step 2) PreProcess the tweets i.e. Removing non-informative parts of tweets\n## Step 3) Combine market data for the selected ticker\n## Step 4) Decide on classification specifictations (number of classes, criterions..)\n## Step 5) Train and test models using for example 5 fold CV\n\n## Step 6) Go back to Step 2 to improve fit\n\n########################################################################################\n## This program will be in charge of modelling the input data ##\n## Input: Ticker and settings\n## Model will use a TweetProcessing class to filter out non-informative parts of tweets\n## Model will use fetchQuandl to get the market data\n########################################################################################\n\n##### General Modules ######\nimport math\nimport numpy as np\n\n### Nltk modules ##\nimport nltk\n\n## Word Processing ##\nfrom nltk.tokenize import sent_tokenize, word_tokenize\n\n# Stop words\nfrom nltk.corpus import stopwords\nstop_words = set(stopwords.words('english'))\nrem_list = [\"'\", '”', 'pic', 'twitter', 'com', \":\", \"!\", \"/\", \"´\", \"$\", \"-\", \"…\", \"?\", \"%\", \"&\", \"=\", \")\", '(',\n ']', '[', '\"', '’', '´', '`', '“', '+', '|', ';', 'ón', '–','.',',','it']\nstop_words.update(rem_list)\ntick_list = [\"AAPL\",\"Apple\",\"Appl\",\"GOOG\"]\nstop_words.update(tick_list)\nfrom sklearn.metrics import confusion_matrix\n\nimport itertools\nfrom nltk.collocations import BigramCollocationFinder\nfrom nltk.metrics import BigramAssocMeasures\n\n# Stemming\nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import sent_tokenize\n\n# Lemmatize\nfrom nltk.stem import WordNetLemmatizer\n\n### Learning algos\nfrom nltk.classify.scikitlearn import SklearnClassifier\n\nfrom sklearn.linear_model import Ridge\n\nimport pickle\n\nfrom textblob import TextBlob\n\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import CountVectorizer,TfidfTransformer\nfrom sklearn.metrics import accuracy_score,confusion_matrix\nfrom sklearn.naive_bayes import MultinomialNB, BernoulliNB\nfrom sklearn.linear_model import LogisticRegression, SGDClassifier\nfrom sklearn.svm import SVC, LinearSVC, NuSVC\nfrom sklearn.neural_network import MLPClassifier\n\n\nimport matplotlib.pyplot as plt\n\n## General modules\nimport random\nimport pandas as pd\nimport re\n\n## From program\nfrom Program.parameters import locationData,regex_str,emoticons_str\n\n####################################################################################\n\nclass models(object):\n def __init__(self,ticker):\n ## Inputs ticker\n self.fname = locationData + ticker + '_refined'\n ## Dictionary used as classification rule\n self.upper = 0.01\n self.lower = -0.01\n ## Used for looking for words ##\n self.article = ''\n self.word_features = []\n self.tokens_re = re.compile(r'(' + '|'.join(regex_str) + ')', re.VERBOSE | re.IGNORECASE)\n self.emoticon_re = re.compile(r'^' + emoticons_str + '$', re.VERBOSE | re.IGNORECASE)\n\n def getData(self):\n ## Get the dataframe [Date,text,return] created by TweetProcessing\n tweetdf = pd.read_pickle(self.fname)\n return tweetdf\n\n\n def classificationRule(self):\n print(\"---------- Classification Rule is using tweets for the Ticker -------\")\n ### Creates a document consisting of blocks of small articles\n ### that have are related to the return (this is done in TweetProcessing\n\n companyDf = self.getData()\n documents = []\n count_pos = 0\n count_neq = 0\n\n for ind in companyDf.index:\n txt_ind = companyDf.ix[ind, 'text']\n ret_ind = companyDf.ix[ind, 'Return']\n self.article = self.article + txt_ind\n if ret_ind < self.lower:\n documents.append((txt_ind, \"neg\"))\n count_neq += 1\n elif ret_ind > self.upper:\n documents.append((txt_ind, \"pos\"))\n count_pos += 1\n\n ## split document into training, validation and test set ##\n train_size = 0.80\n vali_size = 0.90\n test_size =1\n len_documents = len(documents)\n train_split = int(np.floor(len_documents*train_size))\n vali_split = int(np.floor(len_documents * vali_size))\n documents_train = documents[:train_split]\n documents_vali = documents[(train_split+1):vali_split]\n documents_test = documents[(vali_split+1):]\n\n ## Generate article\n self.article = \"\"\n for txt in documents_train:\n self.article = self.article + txt[0]\n\n print(\"------------- Status for Classification Rule --------------\")\n print(\"-> Documents is of size: \", len(documents))\n print(\"-> Number of negative days: \", count_neq)\n print(\"-> Number of Positive days: \", count_pos)\n print(\"-----------------------------------------------------------\")\n return documents_train,documents_vali,documents_test\n\n def AllWordsFiltering(self,article):\n ## Functions filters out non-informative words and puts them in\n ## in a list\n\n ## Function is responsible for text processing\n ## Methods such as tokenizing, stemming, sto words and such can be applied\n\n ## Most basic is to remove stop words ###\n tokenWord = self.tokens_re.findall(article)\n ps = PorterStemmer()\n lemmatizer = WordNetLemmatizer()\n words_token_woStop = []\n for w in tokenWord:\n w = ps.stem(w)\n w = lemmatizer.lemmatize(w)\n if(w.lower() not in stop_words) and ('http' not in w) and not re.search('^[0-9]+', w) and not re.search(r'(?:@[\\w]+)',w):\n words_token_woStop.append(w)\n\n return words_token_woStop\n\n def find_features(self,document):\n words = self.AllWordsFiltering(document)\n features = {}\n ## Go through the most popular words\n for w in self.word_features:\n ## If the popular word is in the document set, save\n features[w] = (w in words)\n\n return features\n\n def TrainModels(self):\n ### Input is two or more articles divided into a postive and negative\n documents_train, documents_vali, documents_test = self.classificationRule()\n # Document is list [(tweet,pos),(tweet2,neg),....]\n #print(documents)\n\n ## define training, validation and test set ###\n #print(self.article)\n\n ## Split article into words ###\n ## Should remove words that contain no information\n all_words = self.AllWordsFiltering(self.article)\n\n ### All words among all tweets\n all_words = nltk.FreqDist(all_words)\n self.word_features = [w[0] for w in all_words.most_common(1000)]\n featuresets_train = [(self.find_features(rev), category) for (rev, category) in documents_train]\n\n '''\n # Training\n documents_train = self.classificationRule(1) # 1 is for training set\n train_words = self.AllWordsFiltering(self.article)\n #print(train_words)\n train_words = nltk.FreqDist(train_words)\n print(train_words)\n print(\"length of train words: \", len(train_words))\n print(\" \")\n self.word_features = list(train_words.keys())\n featuresets_train = [(self.find_features(rev), category) for (rev, category) in documents_train]\n training_set = featuresets_train\n\n # Validation\n documents_validation = self.classificationRule(2) # 2 is for validation set\n validation_words = self.AllWordsFiltering(self.article)\n validation_words = nltk.FreqDist(validation_words)\n print(\"length of validation words: \", len(validation_words))\n print(\" \")\n self.word_features = list(validation_words.keys())\n featuresets_validation = [(self.find_features(rev), category) for (rev, category) in documents_validation]\n validation_set = featuresets_validation\n\n # Test\n documents_test = self.classificationRule(3) # 3 is for test set\n test_words = self.AllWordsFiltering(self.article)\n test_words = nltk.FreqDist(test_words)\n print(\"length of test words: \", len(test_words))\n print(\" \")\n self.word_features = list(test_words.keys())\n '''\n\n featuresets_vali = [(self.find_features(rev), category) for (rev, category) in documents_vali]\n featuresets_test = [(self.find_features(rev), category) for (rev, category) in documents_test]\n\n ## Naive bayes\n classifier = nltk.NaiveBayesClassifier.train(featuresets_train)\n print(\"Naive Bayes Algo for Validation set accuracy percent:\",(nltk.classify.accuracy(classifier, featuresets_vali)) * 100)\n #classifier.show_most_informative_features(15)\n print(\"Naive Bayes Algo for test set accuracy percent:\",(nltk.classify.accuracy(classifier, featuresets_test)) * 100)\n\n self.word_features = [w[0] for w in classifier.most_informative_features(100)]\n featuresets_train = [(self.find_features(rev), category) for (rev, category) in documents_train]\n featuresets_vali = [(self.find_features(rev), category) for (rev, category) in documents_vali]\n featuresets_test = [(self.find_features(rev), category) for (rev, category) in documents_test]\n classifier = nltk.NaiveBayesClassifier.train(featuresets_train)\n print(\"Naive Bayes Algo when careful selection on validation accuracy percent:\",\n (nltk.classify.accuracy(classifier, featuresets_vali)) * 100)\n print(\"Naive Bayes Algo when careful selection on test accuracy percent:\",\n (nltk.classify.accuracy(classifier, featuresets_test)) * 100)\n #classifier.show_most_informative_features(15)\n\n MNB_alpha = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100]\n #MNB_alpha = [1] # default\n MNB_best = 0\n MNB_best_alpha = []\n for i in range(len(MNB_alpha)):\n MNB_classifier = SklearnClassifier(MultinomialNB(alpha=MNB_alpha[i]))\n MNB_classifier.train(featuresets_train)\n MNB_temp = nltk.classify.accuracy(MNB_classifier, featuresets_vali) * 100\n if (MNB_best <= MNB_temp):\n MNB_best = MNB_temp\n MNB_best_alpha =MNB_alpha[i]\n print(\"MultinomialNB_classifier accuracy percent (Best):\", MNB_best, \", alpha =\", MNB_best_alpha)\n\n MNB_classifier = SklearnClassifier(MultinomialNB(alpha=MNB_best_alpha))\n MNB_classifier.train(featuresets_train)\n print(\"MultinomialNB_classifier accuracy percent (Test):\", nltk.classify.accuracy(MNB_classifier, featuresets_test) * 100)\n\n BernoulliNB_alpha = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100]\n #BernoulliNB_alpha = [1] # default\n BernoulliNB_best = 0\n BernoulliNB_best_alpha = []\n for i in range(len(BernoulliNB_alpha)):\n BernoulliNB_classifier = SklearnClassifier(BernoulliNB(alpha=BernoulliNB_alpha[i]))\n BernoulliNB_classifier.train(featuresets_train)\n BernoulliNB_temp = nltk.classify.accuracy(BernoulliNB_classifier, featuresets_vali) * 100\n if (BernoulliNB_best <= BernoulliNB_temp):\n BernoulliNB_best = BernoulliNB_temp\n BernoulliNB_best_alpha = BernoulliNB_alpha[i]\n print(\"BernoulliNB_classifier accuracy percent (Best):\", BernoulliNB_best, \", alpha =\", BernoulliNB_best_alpha)\n\n BernoulliNB_classifier = SklearnClassifier(BernoulliNB(alpha=BernoulliNB_best_alpha))\n BernoulliNB_classifier.train(featuresets_train)\n print(\"MultinomialNB_classifier accuracy percent (Test):\", nltk.classify.accuracy(BernoulliNB_classifier, featuresets_test) * 100)\n\n #LogisticRegression_C = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000]\n LogisticRegression_C = [1] # default\n LogisticRegression_best = 0\n LogisticRegression_best_C = []\n for i in range(len(LogisticRegression_C)):\n # default: penalty = \"l2\"\n LogisticRegression_classifier = SklearnClassifier(LogisticRegression(C=LogisticRegression_C[i]))\n LogisticRegression_classifier.train(featuresets_train)\n LogisticRegression_temp = nltk.classify.accuracy(LogisticRegression_classifier, featuresets_vali) * 100\n if (LogisticRegression_best <= LogisticRegression_temp):\n LogisticRegression_best = LogisticRegression_temp\n LogisticRegression_best_C = LogisticRegression_C[i]\n print(\"LogisticRegression_classifier accuracy percent (Best):\", LogisticRegression_best, \", C =\", LogisticRegression_best_C)\n\n SGDClassifier_alpha = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100]\n #SGDClassifier_alpha = [0.0001] # default\n SGDClassifier_best = 0\n SGDClassifier_best_alpha = []\n for i in range(len(SGDClassifier_alpha)):\n # default: loss = \"hinge\", penalty = \"l2\"\n SGDClassifier_classifier = SklearnClassifier(SGDClassifier(alpha=SGDClassifier_alpha[i]))\n SGDClassifier_classifier.train(featuresets_train)\n SGDClassifier_temp = nltk.classify.accuracy(SGDClassifier_classifier, featuresets_vali) * 100\n if (SGDClassifier_best <= SGDClassifier_temp):\n SGDClassifier_best = SGDClassifier_temp\n SGDClassifier_best_alpha = SGDClassifier_alpha[i]\n print(\"SGDClassifier_classifier accuracy percent (Best):\", SGDClassifier_best, \", alpha =\", SGDClassifier_best_alpha,\n \"loss = hinge, penalty = l2\")\n\n SGDClassifier_alpha = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100]\n #SGDClassifier_alpha = [0.0001] # default\n SGDClassifier_best = 0\n SGDClassifier_best_alpha = []\n for i in range(len(SGDClassifier_alpha)):\n SGDClassifier_classifier = SklearnClassifier(SGDClassifier(loss=\"log\",penalty=\"l2\",alpha=SGDClassifier_alpha[i]))\n SGDClassifier_classifier.train(featuresets_train)\n SGDClassifier_temp = nltk.classify.accuracy(SGDClassifier_classifier, featuresets_vali) * 100\n if (SGDClassifier_best <= SGDClassifier_temp):\n SGDClassifier_best = SGDClassifier_temp\n SGDClassifier_best_alpha = SGDClassifier_alpha[i]\n print(\"SGDClassifier_classifier accuracy percent (Best):\", SGDClassifier_best, \", alpha =\",\n SGDClassifier_best_alpha,\n \"loss = log, penalty = l2\")\n\n SGDClassifier_alpha = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100]\n #SGDClassifier_alpha = [0.0001] # default\n SGDClassifier_best = 0\n SGDClassifier_best_alpha = []\n for i in range(len(SGDClassifier_alpha)):\n SGDClassifier_classifier = SklearnClassifier(\n SGDClassifier(loss=\"perceptron\", penalty=\"l2\", alpha=SGDClassifier_alpha[i]))\n SGDClassifier_classifier.train(featuresets_train)\n SGDClassifier_temp = nltk.classify.accuracy(SGDClassifier_classifier, featuresets_vali) * 100\n if (SGDClassifier_best <= SGDClassifier_temp):\n SGDClassifier_best = SGDClassifier_temp\n SGDClassifier_best_alpha = SGDClassifier_alpha[i]\n print(\"SGDClassifier_classifier accuracy percent (Best):\", SGDClassifier_best, \", alpha =\",\n SGDClassifier_best_alpha,\n \"loss = perceptron, penalty = l2\")\n\n LinearSVC_C = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000]\n #LinearSVC_C = [1] # default\n LinearSVC_best = 0\n LinearSVC_best_C = []\n for i in range(len(LinearSVC_C)):\n # default: loss = \"squared_hinge\", penalty = \"l2\"\n LinearSVC_classifier = SklearnClassifier(LinearSVC(C=LinearSVC_C[i]))\n LinearSVC_classifier.train(featuresets_train)\n LinearSVC_temp = nltk.classify.accuracy(LinearSVC_classifier, featuresets_vali) * 100\n if (LinearSVC_best <= LinearSVC_temp):\n LinearSVC_best = LinearSVC_temp\n LinearSVC_best_C = LinearSVC_C[i]\n print(\"LinearSVC_classifier accuracy percent (Best):\", LinearSVC_best, \", C =\",\n LinearSVC_best_C, \"loss = squared_hinge, penalty = l2\")\n\n LinearSVC_C = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000]\n #LinearSVC_C = [1] # default\n LinearSVC_best = 0\n LinearSVC_best_C = []\n for i in range(len(LinearSVC_C)):\n # default: loss = \"squared_hinge\", penalty = \"l2\"\n LinearSVC_classifier = SklearnClassifier(LinearSVC(loss=\"hinge\",C=LinearSVC_C[i]))\n LinearSVC_classifier.train(featuresets_train)\n LinearSVC_temp = nltk.classify.accuracy(LinearSVC_classifier, featuresets_vali) * 100\n if (LinearSVC_best <= LinearSVC_temp):\n LinearSVC_best = LinearSVC_temp\n LinearSVC_best_C = LinearSVC_C[i]\n print(\"LinearSVC_classifier accuracy percent (Best):\", LinearSVC_best, \", C =\",\n LinearSVC_best_C, \"loss = hinge, penalty = l2\")\n\n # NuSVC rbf kernel\n NuSVC_gamma = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000]\n #NuSVC_gamma = ['auto'] # default: 1/n_features\n NuSVC_best_rbf = 0\n NuSVC_best_gamma = []\n for i in range(len(NuSVC_gamma)):\n # default: nu = 0.5\n NuSVC_classifier = SklearnClassifier(NuSVC(kernel='rbf',gamma=NuSVC_gamma[i]))\n NuSVC_classifier.train(featuresets_train)\n NuSVC_temp = nltk.classify.accuracy(NuSVC_classifier, featuresets_vali) * 100\n if (NuSVC_best_rbf <= NuSVC_temp):\n NuSVC_best_rbf = NuSVC_temp\n NuSVC_best_gamma = NuSVC_gamma[i]\n print(\"NuSVC_classifier accuracy percent (Best with rbf kernel):\", NuSVC_best_rbf, \", gamma =\",\n NuSVC_best_gamma)\n\n # NuSVC poly kernel\n NuSVC_degree = [1,2,3,4,5]\n #NuSVC_degree = [3] # default\n NuSVC_best_poly = 0\n NuSVC_best_degree = []\n for i in range(len(NuSVC_degree)):\n # default: nu = 0.5, gamma = \"auto\" (1/n_features)\n NuSVC_classifier = SklearnClassifier(NuSVC(kernel='poly',degree=NuSVC_degree[i]))\n NuSVC_classifier.train(featuresets_train)\n NuSVC_temp = nltk.classify.accuracy(NuSVC_classifier, featuresets_vali) * 100\n if (NuSVC_best_poly <= NuSVC_temp):\n NuSVC_best_poly = NuSVC_temp\n NuSVC_best_degree = NuSVC_degree[i]\n print(\"NuSVC_classifier accuracy percent (Best with poly kernel):\", NuSVC_best_poly, \", degree =\",\n NuSVC_best_degree)\n\n MLPClassifier_alpha = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100]\n #MLPClassifier_alpha = [0.0001] # default\n MLPClassifier_best = 0\n MLPClassifier_best_alpha = []\n for i in range(len(MLPClassifier_alpha)):\n # default: activation = \"relu\", solver = \"adam\"\n MLPClassifier_classifier = SklearnClassifier(MLPClassifier(alpha=MLPClassifier_alpha[i]))\n MLPClassifier_classifier.train(featuresets_train)\n MLPClassifier_temp = nltk.classify.accuracy(MLPClassifier_classifier, featuresets_vali) * 100\n if (MLPClassifier_best <= MLPClassifier_temp):\n MLPClassifier_best = MLPClassifier_temp\n MLPClassifier_best_alpha = MLPClassifier_alpha[i]\n print(\"MLPClassifier_classifier accuracy percent (Best):\", MLPClassifier_best, \", alpha =\",MLPClassifier_best_alpha)\n\n # Final chosen model\n\n print(\"\")\n print(\"Final chonsen model\")\n NuSVC_gamma = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000]\n # NuSVC_gamma = ['auto'] # default: 1/n_features\n NuSVC_best_rbf = 0\n NuSVC_best_gamma = []\n for i in range(len(NuSVC_gamma)):\n # default: nu = 0.5\n NuSVC_classifier = SklearnClassifier(NuSVC(kernel='rbf', gamma=NuSVC_gamma[i]))\n NuSVC_classifier.train(featuresets_train)\n NuSVC_temp = nltk.classify.accuracy(NuSVC_classifier, featuresets_test) * 100\n if (NuSVC_best_rbf <= NuSVC_temp):\n NuSVC_best_rbf = NuSVC_temp\n NuSVC_best_gamma = NuSVC_gamma[i]\n print(\"NuSVC_classifier accuracy percent (Best with rbf kernel):\", NuSVC_best_rbf, \", gamma =\",\n NuSVC_best_gamma)\n\n############ test functions #############\ntest = models(\"JPM\")\ntest.TrainModels()\n","sub_path":"Program/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":20689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"6407657","text":"from tkinter import *\nfrom tkinter import filedialog, messagebox\nfrom ParseModel.ParseUpgrade import *\nfrom Util import GlobalVar\nfrom Util.GetTestData import GetTestData\n\n\nclass JTFuncWindow():\n def __init__(self,para,msg,tts,photo,upgrade,reboot, parameter, mainwindow):\n self.frame_jt_para = para\n self.frame_jt_msg = msg\n self.frame_jt_upgrade = upgrade\n self.frame_jt_tts = tts\n self.frame_jt_photo = photo\n self.frame_jt_reboot = reboot\n self.frame_parameter = parameter\n self.mainwindow = mainwindow\n self.jt_FuncWindow()\n self.upgrade_file = None\n\n def jt_FuncWindow(self):\n self.frame_msg = StringVar()\n self.frame_flag = StringVar()\n self.frame_voice = StringVar()\n self.frame_photo = StringVar()\n # 终端信息\n self.frame_jt_para_querypara = Button(self.frame_jt_para,text=\"查询终端参数\",command=self.query_para,bd=5,width=10)\n self.frame_jt_para_querypara.grid(row=0,column=0,ipadx=20,ipady=5,padx=20,pady=10,sticky=W)\n self.frame_jt_para_setpara = Button(self.frame_jt_para,text=\"【点击】设置参数\",command=self.window_para,bd=5,width=10)\n self.frame_jt_para_setpara.grid(row=0,column=1,ipadx=20,ipady=5,pady=10,padx=20,sticky=W)\n self.frame_jt_attr_queryattr = Button(self.frame_jt_para,text=\"查询终端属性\",command=self.query_attr,bd=5,width=10)\n self.frame_jt_attr_queryattr.grid(row=1,column=0,ipadx=20,ipady=5,pady=10,padx=20,sticky=W)\n # 构造报文\n self.frame_jt_msg_title = Label(self.frame_jt_msg,text=\"构造报文:\")\n self.frame_jt_msg_title.grid(row=0,column=0,ipadx=20,ipady=5,padx=5,pady=5,sticky=W)\n self.frame_jt_msg_value = Entry(self.frame_jt_msg,textvariable=self.frame_msg,width=18,bd=5)\n self.frame_jt_msg_value.grid(row=0,column=1,ipadx=20,ipady=5,padx=20,pady=5,sticky=W)\n self.frame_jt_msg_example = Label(self.frame_jt_msg,text=\"例如:7E 08 05 *** 0D 7E\",fg=\"red\")\n self.frame_jt_msg_example.grid(row=1,column=1,ipadx=20, sticky=W)\n self.frame_jt_msg_exe = Button(self.frame_jt_msg,text=\"发 送\",command=self.send_msg,bd=5)\n self.frame_jt_msg_exe.grid(row=2,column=1,ipadx=20,ipady=5,padx=20,pady=5,sticky=W)\n # 语音播报\n self.frame_jt_tts_flag = Label(self.frame_jt_tts,text=\"TTS标识:\")\n self.frame_jt_tts_flag.grid(row=0,column=0,ipadx=20,ipady=5,padx=5,pady=5,sticky=W)\n self.frame_jt_tts_flagvalue = Entry(self.frame_jt_tts,textvariable=self.frame_flag,width=18,bd=5)\n self.frame_jt_tts_flagvalue.grid(row=0,column=1,ipadx=20,ipady=5,padx=20,pady=5,sticky=W)\n self.frame_jt_tts_voice = Label(self.frame_jt_tts,text=\"语音内容:\")\n self.frame_jt_tts_voice.grid(row=1,column=0,ipadx=20,ipady=5,padx=5,pady=5,sticky=W)\n self.frame_jt_tts_voicevalue = Entry(self.frame_jt_tts,textvariable=self.frame_voice,width=18,bd=5)\n self.frame_jt_tts_voicevalue.grid(row=1,column=1,ipadx=20,ipady=5,padx=20,pady=5,sticky=W)\n self.frame_jt_tts_exe = Button(self.frame_jt_tts,text=\"播 报\",command=self.send_tts,bd=5)\n self.frame_jt_tts_exe.grid(row=2,column=1,ipadx=20,ipady=5,padx=20,pady=5,sticky=W)\n # 立即拍照\n self.frame_jt_photo_type = Label(self.frame_jt_photo,text=\"类 型:\")\n self.frame_jt_photo_type.grid(row=0,column=0,ipadx=20,ipady=5,padx=5,pady=5,sticky=W)\n girls1 = [(\"DSM\", 1), ('ADAS', 2)]\n self.photo_channel = IntVar()\n self.photo_channel.set(1)\n for girl, num in girls1:\n Radiobutton(self.frame_jt_photo, text=girl, variable=self.photo_channel, value=num).grid(row=0, column=num,\n ipadx=7, ipady=5, pady=6, sticky=W)\n self.frame_jt_photo_exe = Button(self.frame_jt_photo,text=\"拍 照\",command=self.take_photo,bd=5)\n self.frame_jt_photo_exe.grid(row=1,column=1,columnspan=2,ipadx=20,ipady=5,padx=30,pady=5,sticky=W)\n # 升级操作\n self.frame_jt_upgrade_para = Button(self.frame_jt_upgrade,text=\"【点击】升级窗口\",command=self.window_upgrade,width=17,bd=5)\n self.frame_jt_upgrade_para.grid(row=0,column=0,ipadx=10, ipady=5,padx=90, pady=30, sticky=W)\n # 重启操作\n self.frame_jt_reboot_exe = Button(self.frame_jt_reboot,text=\"设备重启\",command=self.reboot,width=17,bd=5)\n self.frame_jt_reboot_exe.grid(row=0,column=0,ipadx=10, ipady=5,padx=90, pady=30, sticky=W)\n\n # 参数操作\n self.frame_su_para_case = Label(self.frame_parameter, text=\"用例:\")\n self.frame_su_para_case.grid(row=0, column=0, pady=15, sticky=W)\n self.frame_su_para_select = Button(self.frame_parameter, text=\"选择用例\", command=self.select_case_file, bd=5,\n width=15)\n self.frame_su_para_select.grid(row=1, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)\n self.frame_su_para_exe = Button(self.frame_parameter, text=\"执行用例\", command=self.case_exe, bd=5, width=15)\n self.frame_su_para_exe.grid(row=1, column=1, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)\n\n # 选择用例文件\n def select_case_file(self):\n self.casefile = filedialog.askopenfilename()\n self.casefilename = os.path.split(self.casefile)[-1]\n if self.casefilename:\n self.frame_su_para_case.config(text=\"用例:\" + self.casefilename)\n else:\n self.frame_su_para_case.config(text=\"未选择任何用例\")\n\n # 执行用例文件\n def case_exe(self):\n case = GetTestData(self.casefile)\n case.open()\n test_point, data = case.get_excel_data()\n logger.debug('—————— ' + test_point + ' ——————')\n send_queue.put(data)\n\n # 参数设置窗口\n def window_para(self):\n self.window_setpara = Toplevel(self.mainwindow)\n self.ww = self.window_setpara.winfo_screenwidth()\n self.wh = self.window_setpara.winfo_screenheight()\n self.mw = (self.ww - 400) / 2\n self.mh = (self.wh - 400) / 2\n self.window_setpara.geometry(\"%dx%d+%d+%d\" % (400, 400, self.mw, self.mh))\n self.window_setpara.title(\"设置参数\")\n\n self.frame_ip = StringVar()\n self.frame_port = StringVar()\n self.frame_limitspeed = StringVar()\n self.frame_adasspeed = StringVar()\n self.frame_volum = StringVar()\n self.frame_volum.set('06')\n # self.frame_mode = StringVar()\n\n self.frame_jt_para_ip = Label(self.window_setpara, text=\"IP地址:\", width=10)\n self.frame_jt_para_ip.grid(row=0, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)\n self.frame_jt_para_ipvalue = Entry(self.window_setpara, textvariable=self.frame_ip, width=17, bd=5)\n self.frame_jt_para_ipvalue.grid(row=0, column=1,columnspan=2, ipadx=20, ipady=5, pady=5, padx=20, sticky=W)\n self.frame_jt_para_port = Label(self.window_setpara, text=\"端口号:\", width=10)\n self.frame_jt_para_port.grid(row=1, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)\n self.frame_jt_para_portvalue = Entry(self.window_setpara, textvariable=self.frame_port, width=17, bd=5)\n self.frame_jt_para_portvalue.grid(row=1, column=1,columnspan=2, ipadx=20, ipady=5, pady=5, padx=20, sticky=W)\n self.frame_jt_para_limitspeed = Label(self.window_setpara, text=\"最高速度:\", width=10)\n self.frame_jt_para_limitspeed.grid(row=2, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)\n self.frame_jt_para_limitspeedvalue = Entry(self.window_setpara, textvariable=self.frame_limitspeed, width=17,bd=5)\n self.frame_jt_para_limitspeedvalue.grid(row=2, column=1,columnspan=2, ipadx=20, ipady=5, pady=5, padx=20, sticky=W)\n self.frame_jt_para_adasspeed = Label(self.window_setpara, text=\"ADAS告警速度:\", width=10)\n self.frame_jt_para_adasspeed.grid(row=3, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)\n self.frame_jt_para_adasspeedvalue = Entry(self.window_setpara, textvariable=self.frame_adasspeed, width=17,bd=5)\n self.frame_jt_para_adasspeedvalue.grid(row=3, column=1,columnspan=2, ipadx=20, ipady=5, pady=5, padx=20, sticky=W)\n self.frame_jt_para_volum = Label(self.window_setpara, text=\"音量:\", width=10)\n self.frame_jt_para_volum.grid(row=4, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)\n self.frame_jt_para_volumnvalue = Scale(self.window_setpara,from_=0,to=8,orient=HORIZONTAL,variable=self.frame_volum,tickinterval=1,length=130)\n self.frame_jt_para_volumnvalue.grid(row=4,column=1,columnspan=2,ipadx=20, ipady=5, pady=5, padx=20,sticky=W)\n self.frame_jt_para_mode = Label(self.window_setpara, text=\"模式:\", width=10)\n self.frame_jt_para_mode.grid(row=5, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)\n girls1 = [(\"行车\", 1), ('测试', 2)]\n self.mode_value = IntVar()\n self.mode_value.set(1)\n for girl, num in girls1:\n Radiobutton(self.window_setpara, text=girl, variable=self.mode_value, value=num).grid(row=5, column=num,\n ipadx=7, ipady=5, pady=6, sticky=W)\n self.frame_jt_para_exe = Button(self.window_setpara, text=\"设 置\", command=self.set_para, bd=5)\n self.frame_jt_para_exe.grid(row=6, column=1,columnspan=2, ipadx=20, ipady=5, pady=5, padx=20, sticky=W)\n\n # 升级窗口\n def window_upgrade(self):\n self.window_upgrade = Toplevel(self.mainwindow)\n self.ww = self.window_upgrade.winfo_screenwidth()\n self.wh = self.window_upgrade.winfo_screenheight()\n self.mw = (self.ww - 400) / 2\n self.mh = (self.wh - 450) / 2\n self.window_upgrade.geometry(\"%dx%d+%d+%d\" % (400, 450, self.mw, self.mh))\n self.window_upgrade.title(\"升级操作\")\n # self.window_upgrade.attributes(\"-toolwindow\", 1)\n self.window_upgrade.wm_attributes(\"-topmost\", 2)\n\n self.frame_upgradeflag = StringVar()\n self.frame_upgradetype = StringVar()\n self.frame_upgradeurl = StringVar()\n self.frame_hardware = StringVar()\n self.frame_fireware = StringVar()\n self.frame_software = StringVar()\n\n self.frame_jt_upgrade_flag = Label(self.window_upgrade, text=\"升级标志:\", width=10)\n self.frame_jt_upgrade_flag.grid(row=0, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)\n girls1 = [(\"升级\", 1), ('不升级', 2)]\n self.upgrade_flag = IntVar()\n self.upgrade_flag.set(1)\n for girl, num in girls1:\n Radiobutton(self.window_upgrade, text=girl, variable=self.upgrade_flag, value=num).grid(row=0, column=num,\n ipadx=7, ipady=5, pady=6, sticky=W)\n self.frame_jt_upgrade_type = Label(self.window_upgrade, text=\"升级类型:\", width=10)\n self.frame_jt_upgrade_type.grid(row=1, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)\n girls2 = [(\"应用升级\", 1), ('固件升级', 2)]\n self.upgrade_type = IntVar()\n self.upgrade_type.set(1)\n for girl, num in girls2:\n Radiobutton(self.window_upgrade, text=girl, variable=self.upgrade_type, value=num).grid(row=1, column=num,\n ipadx=7, ipady=5,\n pady=6, sticky=W)\n self.frame_jt_upgrade_url = Label(self.window_upgrade, text=\"升级包下载地址:\", width=10)\n self.frame_jt_upgrade_url.grid(row=2, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)\n self.frame_jt_upgrade_urlvalue = Entry(self.window_upgrade, textvariable=self.frame_upgradeurl, width=17,bd=5)\n self.frame_jt_upgrade_urlvalue.grid(row=2, column=1,columnspan=2, ipadx=20, ipady=5, pady=5, padx=20, sticky=W)\n self.frame_jt_upgrade_example = Label(self.window_upgrade,text=\"例如:http://jumping512.imwork.net:28388/Package.zip\",fg=\"red\")\n self.frame_jt_upgrade_example.grid(row=3, column=0,columnspan=3, padx=15, sticky=W)\n self.frame_jt_upgrade_hardware = Label(self.window_upgrade, text=\"硬件版本号:\", width=10)\n self.frame_jt_upgrade_hardware.grid(row=4, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)\n self.frame_jt_upgrade_hardwarevalue = Entry(self.window_upgrade, textvariable=self.frame_hardware, width=17,bd=5)\n self.frame_jt_upgrade_hardwarevalue.grid(row=4, column=1,columnspan=2, ipadx=20, ipady=5, pady=5, padx=20, sticky=W)\n self.frame_jt_upgrade_fireware = Label(self.window_upgrade, text=\"固件版本号:\", width=10)\n self.frame_jt_upgrade_fireware.grid(row=5, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)\n self.frame_jt_upgrade_firewarevalue = Entry(self.window_upgrade, textvariable=self.frame_fireware, width=17,bd=5)\n self.frame_jt_upgrade_firewarevalue.grid(row=5, column=1, columnspan=2, ipadx=20, ipady=5, pady=5, padx=20,sticky=W)\n self.frame_jt_upgrade_software = Label(self.window_upgrade, text=\"软件版本号:\", width=10)\n self.frame_jt_upgrade_software.grid(row=6, column=0, ipadx=20, ipady=5, padx=5, pady=5, sticky=W)\n self.frame_jt_upgrade_softwarevalue = Entry(self.window_upgrade, textvariable=self.frame_software, width=17,bd=5)\n self.frame_jt_upgrade_softwarevalue.grid(row=6, column=1, columnspan=2, ipadx=20, ipady=5, pady=5, padx=20,sticky=W)\n self.frame_jt_upgrade_package = Label(self.window_upgrade,text=\"升级包:\")\n self.frame_jt_upgrade_package.grid(row=7,column=0,columnspan=3, padx=20,ipadx=5,ipady=5, pady=5,sticky=W)\n self.frame_jt_upgrade_select = Button(self.window_upgrade,text=\"选择升级包\",command=self.select_package,bd=5)\n self.frame_jt_upgrade_select.grid(row=8,column=0,ipadx=15, ipady=5, pady=5, padx=20,sticky=W)\n self.frame_jt_upgrade_exe = Button(self.window_upgrade, text=\"升 级\", command=self.start_upgrade, bd=5)\n self.frame_jt_upgrade_exe.grid(row=8, column=1,columnspan=2, ipadx=20, ipady=5, pady=5, padx=20, sticky=W)\n\n def set_para(self):\n txt = '修改参数 : '\n list_num = 0\n self.ip = self.frame_ip.get()\n self.port = self.frame_port.get()\n self.limitspeed = self.frame_limitspeed.get()\n self.adasspeed = self.frame_adasspeed.get()\n self.volum = self.frame_volum.get()\n self.mode = self.mode_value.get()\n if self.mode == 1:\n self.mode = '01'\n elif self.mode == 2:\n self.mode = '02'\n msg_body = ''\n if self.ip:\n list_num += 1\n ip_len = len(self.ip)\n msg_body += '00000013' + num2big(ip_len, 1) + str2hex(self.ip, ip_len)\n txt += '服务器 {} '.format(self.ip)\n if self.port:\n list_num += 1\n msg_body += '00000018' + '04' + num2big(int(self.port), 4)\n txt += '端口号 {} '.format(self.port)\n if self.limitspeed:\n list_num += 1\n msg_body += '00000055' + '04' + num2big(int(self.limitspeed), 4)\n txt += '最高速度 {} '.format(self.limitspeed)\n if self.adasspeed:\n list_num += 1\n msg_body += '0000F091' + '01' + num2big(int(self.adasspeed), 1)\n txt += 'ADAS激活速度 {} '.format(self.adasspeed)\n if self.volum:\n list_num += 1\n msg_body += '0000F092' + '01' + num2big(int(self.volum), 1)\n txt += '告警音量 {} '.format(self.volum)\n if self.mode:\n list_num += 1\n msg_body += '0000F094' + '01' + num2big(int(self.mode), 1)\n txt += '工作模式 {} '.format(self.mode)\n if list_num:\n msg_body = num2big(list_num, 1) + msg_body\n body = '8103' + num2big(int(len(msg_body) / 2), 2) + GlobalVar.DEVICEID + \\\n num2big(GlobalVar.get_serial_no()) + msg_body\n data = '7E' + body + calc_check_code(body) + '7E'\n logger.debug('—————— 设置终端参数 ——————')\n logger.debug('—————— ' + txt + ' ——————')\n send_queue.put(data)\n # self.window_setpara.destroy()\n\n # 查询参数\n def query_para(self):\n logger.debug('—————— 查询终端参数 ——————')\n body = '8104' + '0000' + GlobalVar.DEVICEID + num2big(GlobalVar.get_serial_no())\n data = '7E' + body + calc_check_code(body) + '7E'\n send_queue.put(data)\n\n # 查询属性\n def query_attr(self):\n logger.debug('—————— 查询终端属性 ——————')\n body = '8107' + '0000' + GlobalVar.DEVICEID + num2big(GlobalVar.get_serial_no())\n data = '7E' + body + calc_check_code(body) + '7E'\n send_queue.put(data)\n\n # 构造报文\n def send_msg(self):\n self.msg = self.frame_msg.get()\n send_queue.put(self.msg)\n\n # 语音播报\n def send_tts(self):\n self.flag = self.frame_flag.get()\n self.voice = self.frame_voice.get()\n if self.voice:\n if self.flag:\n tts_flag_ = num2big(int(self.flag), 1)\n else:\n tts_flag_ = '08'\n msg_body = tts_flag_ + byte2str(self.voice.encode('gbk'))\n body = '8300' + num2big(int(len(msg_body) / 2)) + GlobalVar.DEVICEID + \\\n num2big(GlobalVar.get_serial_no()) + msg_body\n data = '7E' + body + calc_check_code(body) + '7E'\n send_queue.put(data)\n\n # 立即拍照\n def take_photo(self):\n self.photo = self.photo_channel.get()\n if self.photo == 1:\n self.photo = '00'\n elif self.photo == 2:\n self.photo ='01'\n if self.photo:\n msg_body = num2big(int(self.photo), 1) + '00' * 11\n body = '8801' + '000C' + GlobalVar.DEVICEID + num2big(GlobalVar.get_serial_no()) + msg_body\n data = '7E' + body + calc_check_code(body) + '7E'\n send_queue.put(data)\n\n # 设备重启\n def reboot(self):\n body = '8F01' + '0000' + GlobalVar.DEVICEID + num2big(GlobalVar.get_serial_no())\n data = '7E' + body + calc_check_code(body) + '7E'\n send_queue.put(data)\n\n # 选择升级包\n def select_package(self):\n self.upgrade_file = filedialog.askopenfilename()\n file_name = os.path.split(self.upgrade_file)[-1]\n if file_name:\n self.frame_jt_upgrade_package.configure(text=\"升级包:\" + file_name)\n else:\n self.frame_jt_upgrade_package.configure(text=\"未选择任何升级包。\")\n\n # 执行升级\n def start_upgrade(self):\n upgrade_flag = self.upgrade_flag.get()\n upgrade_type = self.upgrade_type.get()\n upgrade_url = self.frame_upgradeurl.get()\n up_hardware = self.frame_hardware.get()\n up_firmware = self.frame_fireware.get()\n up_software = self.frame_software.get()\n active_upgrade_ = True\n if upgrade_flag and upgrade_type and upgrade_url and self.upgrade_file:\n upgrade_jt808(self.upgrade_file, upgrade_flag, upgrade_type, up_hardware, up_firmware, up_software,\n upgrade_url, active_upgrade_)\n # else:\n # messagebox.showerror(title=\"error\", message=\"Parameter Error\")\n # self.window_upgrade.destroy()\n","sub_path":"Util/Gui_JT808.py","file_name":"Gui_JT808.py","file_ext":"py","file_size_in_byte":19706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"464297845","text":"#!/usr/bin/env python\nimport sys\n\nfrom tornado import testing\nfrom tornado import escape\nfrom tornado import concurrent\nfrom tornado import httpclient\n\nimport asyncrandom\n\nif sys.version_info[0] < 3:\n from mock import patch\n from mock import Mock\n from StringIO import StringIO\nelse:\n from unittest.mock import patch\n from unittest.mock import Mock\n from io import StringIO\n\n\ndef fetch_mock(status_code, body_data):\n\n def side_effect(request, **kwargs):\n if request is not httpclient.HTTPRequest:\n request = httpclient.HTTPRequest(request)\n\n body = StringIO(escape.json_encode(body_data))\n response = httpclient.HTTPResponse(request, status_code, None, body)\n future = concurrent.Future()\n future.set_result(response)\n return future\n\n fetch_mock = Mock(side_effect=side_effect)\n return fetch_mock\n\n\nFETCH_METHOD = \"tornado.httpclient.AsyncHTTPClient.fetch\"\n\n\nclass TestWithMock(testing.AsyncTestCase):\n\n @patch(FETCH_METHOD, fetch_mock(404, None))\n @testing.gen_test\n def test_not_found(self):\n with self.assertRaises(httpclient.HTTPError) as e:\n yield asyncrandom.fetch()\n httpclient.AsyncHTTPClient.fetch.assert_called_with(\n \"https://qrng.anu.edu.au/API/jsonI.php?length=1&type=uint8\")\n self.assertEqual(e.exception.code, 404)\n\n @patch(FETCH_METHOD, fetch_mock(500, None))\n @testing.gen_test\n def test_server_error(self):\n with self.assertRaises(httpclient.HTTPError) as e:\n yield asyncrandom.fetch()\n httpclient.AsyncHTTPClient.fetch.assert_called_with(\n \"https://qrng.anu.edu.au/API/jsonI.php?length=1&type=uint8\")\n self.assertEqual(e.exception.code, 500)\n\n @patch(FETCH_METHOD, fetch_mock(200, {\"success\": True, \"data\": [42]}))\n @testing.gen_test\n def test_success_single_uint8(self):\n value = yield asyncrandom.fetch()\n httpclient.AsyncHTTPClient.fetch.assert_called_with(\n \"https://qrng.anu.edu.au/API/jsonI.php?length=1&type=uint8\")\n self.assertEqual(value, 42)\n\n @patch(FETCH_METHOD, fetch_mock(200, {\"success\": True, \"data\": [100, 101]}))\n @testing.gen_test\n def test_success_multiple_uint8(self):\n values = yield asyncrandom.fetch(length=2)\n httpclient.AsyncHTTPClient.fetch.assert_called_with(\n \"https://qrng.anu.edu.au/API/jsonI.php?length=2&type=uint8\")\n self.assertListEqual(values, [100, 101])\n\n @patch(FETCH_METHOD, fetch_mock(200, {\"success\": True, \"data\": [34500]}))\n @testing.gen_test\n def test_success_single_uint16(self):\n value = yield asyncrandom.fetch(\n int_type=asyncrandom.IntegerType.UINT16)\n httpclient.AsyncHTTPClient.fetch.assert_called_with(\n \"https://qrng.anu.edu.au/API/jsonI.php?length=1&type=uint16\")\n self.assertEqual(value, 34500)\n\n @patch(FETCH_METHOD, fetch_mock(\n 200, {\"success\": True, \"data\": [3450, 10001]}))\n @testing.gen_test\n def test_success_multiple_uint16(self):\n values = yield asyncrandom.fetch(\n length=2, int_type=asyncrandom.IntegerType.UINT16)\n\n httpclient.AsyncHTTPClient.fetch.assert_called_with(\n \"https://qrng.anu.edu.au/API/jsonI.php?length=2&type=uint16\")\n self.assertListEqual(values, [3450, 10001])\n\n @patch(FETCH_METHOD, fetch_mock(200, {\"success\": False}))\n @testing.gen_test\n def test_unsuccessful(self):\n with self.assertRaises(ValueError):\n yield asyncrandom.fetch()\n\n httpclient.AsyncHTTPClient.fetch.assert_called_with(\n \"https://qrng.anu.edu.au/API/jsonI.php?length=1&type=uint8\")\n\n @patch(FETCH_METHOD, fetch_mock(200, {\"success\": False}))\n @testing.gen_test\n def test_negative_length(self):\n with self.assertRaises(TypeError):\n yield asyncrandom.fetch(length=-1)\n\n\n@testing.unittest.skipUnless(__name__ == \"__main__\", \"skipping external tests\")\nclass TestRealAPI(testing.AsyncTestCase):\n # Skip tests against the real API unless the file has been called explcitly\n # from the command line.\n # If the tests are run through e.g. nose or setup.py, these tests will not\n # run.\n\n @testing.gen_test(timeout=10)\n def test_single_uint8(self):\n value = yield asyncrandom.fetch()\n self.assertIsInstance(value, int)\n self.assertLessEqual(value, 255)\n\n @testing.gen_test(timeout=10)\n def test_multiple_uint8(self):\n values = yield asyncrandom.fetch(length=20)\n self.assertIsInstance(values, list)\n self.assertEqual(len(values), 20)\n for random_num in values:\n self.assertLessEqual(random_num, 255)\n\n @testing.gen_test(timeout=10)\n def test_single_uint16(self):\n value = yield asyncrandom.fetch(\n int_type=asyncrandom.IntegerType.UINT16)\n self.assertIsInstance(value, int)\n self.assertLessEqual(value, 65535)\n\n @testing.gen_test(timeout=10)\n def test_multiple_uint16(self):\n values = yield asyncrandom.fetch(\n length=20, int_type=asyncrandom.IntegerType.UINT16)\n self.assertIsInstance(values, list)\n self.assertEqual(len(values), 20)\n for random_num in values:\n self.assertLessEqual(random_num, 65535)\n\n @testing.gen_test\n def test_incorrect_length_value(self):\n with self.assertRaises(TypeError):\n yield asyncrandom.fetch(length=\"1\")\n\n @testing.gen_test\n def test_incorrect_type_value(self):\n with self.assertRaises(TypeError):\n yield asyncrandom.fetch(int_type=\"uint8\")\n\n\nif __name__ == \"__main__\":\n testing.unittest.main()\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"489899126","text":"# -*- coding: utf-8 -*-\n\nfrom helviservice.plugins import Plugin\nfrom minio.error import ResponseError\n\nimport yaml\nimport os\nimport logging\n\nlog = logging.getLogger(name=__name__)\n\nclass LoadDialogsPlugin(Plugin):\n \"\"\"Load dialogs\n \"\"\"\n \n name = \"LoadDialogs\" \n\n def __init__(self, *args, **kwargs):\n super(Plugin, self).__init__(*args, **kwargs)\n\n def setup(self, config):\n \"\"\"Load dialogs\"\"\"\n\n langs = os.getenv('LANGS').split(',')\n \n for lang in langs:\n # List all object paths in bucket that begin with my-prefixname.\n intents = config['minio'].list_objects('helvi', lang + '/dialogs',\n recursive=True)\n\n dialogs = {}\n\n for intent in intents: \n try:\n bucket = intent.bucket_name\n intent_file = intent.object_name\n config['minio'].fget_object(bucket, intent_file, '/data/' + intent_file)\n \n with open('/data/' + intent_file, 'r', encoding='utf-8') as yaml_data:\n data = yaml.load(yaml_data)\n dialogs[intent_file] = data\n\n except ResponseError as err:\n print('{\"status\": \"error\", \"error\": \"' + err +'\"}')\n\n config['dialogs-' + lang] = dialogs\n\n return config\n ","sub_path":"bot/bootstrap/dialogs.py","file_name":"dialogs.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"388769645","text":"import math\n\ndef prime(p):\n for i in range(2, math.floor(p**0.5) + 1):\n if p % i == 0:\n return False\n return True\n\nprimes = [i for i in range(2, 21) if prime(i)]\ncoef = [1] * len(primes)\n\ndef maxcoef(n, p):\n ans = 0\n while n % p == 0:\n ans += 1\n n /= p\n return ans\n\nfor i, p in enumerate(primes):\n for n in range(2, 20):\n coef[i] = max(coef[i], maxcoef(n, p))\n\nans = 1\nfor p, c in zip(primes, coef):\n ans *= p ** c\n\nprint(ans)\n\n","sub_path":"live/p005.py","file_name":"p005.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"492934862","text":"#coding:utf-8\nimport requests\nimport re\nimport urlparse\nfrom bs4 import BeautifulSoup\n\ndef download(url):\n user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' #模拟浏览器\n headers = {'User-Agent': user_agent}\n response=requests.get(url,headers=headers)\n if response.status_code==200:\n response.encoding=\"utf-8\" #设置编码\n return response.text\n else:\n return None\n\ndef gettitle(pagedata):\n soup=BeautifulSoup(pagedata,\"html.parser\") #解析\n list1= soup.find_all(\"h1\")\n list2=soup.find_all(\"h2\")\n if len(list1)!=0 and len(list2)!=0:\n return (list1[0].text,list2[0].text)\n elif len(list1)!=0 and len(list2)==0:\n return list1[0].text\n else:\n return None\n\ndef getcontent(pagedata):\n soup=BeautifulSoup(pagedata,\"html.parser\") #解析\n summary= soup.find_all(\"div\",class_=\"lemma-summary\")\n if len(summary)!=0:\n return summary[0].get_text()\n else:\n return None\n\ndef geturllist(pagedata):\n urllist=set() #集合\n soup = BeautifulSoup(pagedata, \"html.parser\") # 解析\n links=soup.find_all(\"a\",href=re.compile(r\"/item/.*\"))\n for link in links:\n url=\"https://baike.baidu.com\"\n url+=link[\"href\"]\n urllist.add(url) #加入集合\n\n return urllist\n\n\npagedata= download(\"https://baike.baidu.com/item/Python/407313\")\nprint (geturllist(pagedata))\n#print gettitle(pagedata)[0],gettitle(pagedata)[1]\n","sub_path":"baidubaike/3提取百度百科url.py","file_name":"3提取百度百科url.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"50939757","text":"from flask import Flask, render_template\nfrom flask_assets import Bundle, Environment\nfrom flask_bootstrap import Bootstrap\n\n# create app\napp = Flask(__name__)\n\n# setup app bootstrap\nBootstrap(app)\nassets = Environment(app)\n\n# setup app assets\nassets.url = app.static_url_path\nscss = Bundle('scss/main.scss', filters='pyscss', output='build/all.css')\nassets.register('scss_all', scss)\n\n@app.route('/')\ndef index():\n return render_template('index.html', posts=[])\n\n\napp.run(host='0.0.0.0', port=5000)\n","sub_path":"frontend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"159804002","text":"class CooSparseMatrix:\n def __init__(self, ijx_list, shape):\n if isinstance(shape, tuple) and len(shape) == 2 \\\n and isinstance(shape[0], int) and isinstance(shape[1], int) \\\n and 0 < shape[0] and 0 < shape[1]:\n self._shape = shape\n else:\n raise TypeError('Invalid shape.')\n self.data = dict()\n for ijx in ijx_list:\n if isinstance(ijx, tuple) and len(ijx) == 3 \\\n and isinstance(ijx[0], int) and isinstance(ijx[1], int) \\\n and 0 <= ijx[0] < self._shape[0] and 0 <= ijx[1] < self._shape[1]:\n if ijx[:2] in self.data.keys():\n raise TypeError('Two elements with same indexes (%d, %d).' % ijx[:2])\n elif ijx[2] != 0:\n self.data[ijx[:2]] = ijx[2]\n else:\n raise TypeError('Invalid unit.')\n\n def __getitem__(self, key):\n if isinstance(key, tuple):\n if len(key) == 2 \\\n and isinstance(key[0], int) and isinstance(key[1], int) \\\n and 0 <= key[0] < self._shape[0] and 0 <= key[1] < self._shape[1]:\n if key in self.data:\n return self.data[key]\n else:\n return 0\n else:\n raise TypeError('Invalid index.')\n else:\n if isinstance(key, int) and 0 <= key < self._shape[0]:\n return CooSparseMatrix([key+(value,) for key, value in self.data.items() if elem[0][0] == key],\n (1, self._shape[1]))\n else:\n raise TypeError('Invalid index.')\n\n def __setitem__(self, key, value):\n if isinstance(key, tuple) and len(key) == 2 \\\n and isinstance(key[0], int) and isinstance(key[1], int) \\\n and 0 <= key[0] < self._shape[0] and 0 <= key[1] < self._shape[1]:\n if value != 0:\n self.data[key] = value\n elif key in self.data.keys():\n del self.data[key]\n else:\n raise TypeError('Invalid index.')\n\n def __add__(self, m):\n if isinstance(m, CooSparseMatrix) and self._shape == m.shape:\n return CooSparseMatrix([key+(value+m[key],) for key, value in self.data.items()] +\n [key+(value,) for key, value in m.data.items() if key not in self.data],\n self._shape)\n else:\n raise TypeError('Invalid operands.')\n\n def __sub__(self, m):\n if isinstance(m, CooSparseMatrix) and self._shape == m.shape:\n return CooSparseMatrix([key+(value-m[key],) for key, value in self.data.items()] +\n [key+(-value,) for key, value in m.data.items() if key not in self.data],\n self._shape)\n else:\n raise TypeError('Invalid operands.')\n\n def __mul__(self, n):\n if isinstance(n, int) or isinstance(n, float):\n if n == 0:\n return CooSparseMatrix([], self._shape)\n else:\n return CooSparseMatrix([key+(value*n,) for key, value in self.data.items()], self._shape)\n else:\n raise TypeError('Invalid operands.')\n\n def __rmul__(self, n):\n if isinstance(n, int) or isinstance(n, float):\n if n == 0:\n return CooSparseMatrix([], self._shape)\n else:\n return CooSparseMatrix([key+(value*n,) for key, value in self.data.items()], self._shape)\n else:\n raise TypeError('Invalid operands.')\n\n def to_list(self):\n return [key+(value,) for key, value in self.data.items()]\n\n @property\n def shape(self):\n 'Shape of matrix.'\n return self._shape\n\n @shape.setter\n def shape(self, new_shape):\n if isinstance(new_shape, tuple) and len(new_shape) == 2 \\\n and isinstance(new_shape[0], int) and isinstance(new_shape[1], int) \\\n and new_shape[0]*new_shape[1] == self._shape[0]*self._shape[1]:\n values = list(self.data.values())\n keys = [i*self._shape[1] + j for i, j in self.data.keys()]\n keys = [(key//new_shape[1], key%new_shape[1]) for key in keys]\n self.data.clear()\n for i in range(len(keys)):\n self.data[keys[i]] = values[i]\n self._shape = new_shape\n else:\n raise TypeError('Invalid assigment.')\n\n @property\n def T(self):\n 'Transposed matrix.'\n return CooSparseMatrix([key[::-1]+(value,) for key, value in self.data.items()], self._shape[::-1])\n\n\nif __name__ == '__main__':\n matrix1 = CooSparseMatrix([(500, 0, 1), (500, 1, 2), (499, 999, 3)], shape=(1000, 1000))\n print(matrix1.to_list())\n matrix1.shape = (100, 10000)\n print(matrix1.to_list())\n","sub_path":"third_year/autumn/prac/0/sparse_matrix.py","file_name":"sparse_matrix.py","file_ext":"py","file_size_in_byte":4899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"345576386","text":"__author__ = \"Szabolcs Szekér <szeker@dcs.uni-pannon.hu>\"\r\n__version__ = \"1.0\"\r\n\r\n\"\"\"\r\nIn this file, an example is presented to:\r\n- import the datasets,\r\n- run the different control group selection methods \r\n (greedy 1:1 PSM with two types of setting the calliper size, nearest neighbour matching, Mahalanobis matching, stratified matching and WNNEM method),\r\n- to evaluate the similarity of the selected control group to the case group \r\n (individual balance, SMD, DDI, NNI, GDI).\r\n \r\nThe WNNEM method is published in ...\r\n\r\nIn case of using the datasets or applying the WNNEM method, please cite the article above.\r\n\r\nFor more details in DDI, NNI and GDI indexes please see:\r\nS. Szekér and Á. Vathy-Fogarassy,\r\nHow Can the Similarity of the Case and Control Groups be Measured in Case-Control Studies?\r\n2019 IEEE International Work Conference on Bioinspired Intelligence (IWOBI), Budapest, Hungary, 2019, pp. 33-40.\r\ndoi: 10.1109/IWOBI47054.2019.9114390.\r\n\"\"\"\r\n\r\n# %%\r\n\r\nimport sys\r\nsys.path.insert(1, 'Scripts')\r\n\r\nimport warnings\r\nimport numpy as np\r\nimport pandas as pd\r\nimport wnnem\r\nimport psm\r\nimport other_methods as om\r\nimport dissim\r\nimport time\r\nimport datetime\r\n\r\n# %%\r\n\r\n# display deprecation warnings\r\nwarnings.simplefilter('always', DeprecationWarning)\r\n\r\n# %%\r\n \r\ndef create_output_file(case, population, ovar, col_list, write_to_file = True):\r\n \r\n tmp = population.copy()\r\n \r\n for col in col_list:\r\n tmp[col] = np.NaN\r\n \r\n for i, row in tmp.iterrows():\r\n try:\r\n tmp.loc[i, col] = case.loc[case[col] == i].index.astype(int)[0]\r\n except IndexError:\r\n pass\r\n \r\n otpt = pd.concat([case, tmp])\r\n \r\n if 'lp_t' in otpt.columns:\r\n del otpt['lp_t']\r\n if 'p_t' in otpt.columns:\r\n del otpt['p_t']\r\n otpt.index.name = '_id'\r\n \r\n if write_to_file:\r\n ts = time.time()\r\n timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y_%m_%d_%H_%M_%S')\r\n otpt.sort_index(axis=0).to_csv('results_{}.csv'.format(timestamp), sep=';', decimal=',')\r\n \r\n return otpt\r\n\r\n\r\n# %%\r\n\r\n# N is the number of records or patients (rows) \r\nM = 1000\r\n# M is the number of attributes or observerd variables (columns)\r\nN = 10\r\n\r\n# index is the name of the index column\r\nindex = '_id'\r\n\r\nX = pd.read_csv('Datasets/example_dataset_scenarioI.csv', sep=';', decimal=',', encoding='utf-8')\r\nX.set_index(index, inplace=True)\r\n\r\novar = [x for x in list(X) if 'x' in x]\r\nX, r_weights = psm.calculate_ps(X, 'treated', ovar)\r\ntreated = X[X['treated'] == 1]\r\nuntreated = X[X['treated'] == 0]\r\n\r\nprint('Case group: {} (No. treated)'.format(len(treated)))\r\nprint('Population: {} (No. untreated)'.format(len(untreated)))\r\n\r\npsm_control, caliper = psm.match(treated, untreated, 'ps', pair_name='psm_pair', index='_id')\r\nprint('Control group by PSM: {} ({:.2f}%)'.format(len(psm_control), len(psm_control) / len(treated) * 100))\r\n\r\nwnnem_control = wnnem.match(treated, untreated, ovar, r_weights, pair_name='wnnem_pair', index='_id')\r\nprint('Control group by WNNEM: {} ({:.2f}%)'.format(len(wnnem_control), len(wnnem_control) / len(treated) * 100))\r\n\r\nss_control = om.SM(treated, untreated, ovar, pair_name='ss_pair')\r\nprint('Control group by SS: {} ({:.2f}%)'.format(len(ss_control), len(ss_control) / len(treated) * 100))\r\n\r\nnn_control = om.NN(treated, untreated, ovar, pair_name='nn_pair', dist='mahalanobis', index='_id')\r\nprint('Control group by NN: {} ({:.2f}%)'.format(len(nn_control), len(nn_control) / len(treated) * 100))\r\n\r\ncategorical = ovar\r\ngroupby = 'treated'\r\nnonnormal = None\r\n\r\nprint('\\nCalculating individual balances')\r\nbalance = dissim.calculate_individual_balance(treated, wnnem_control, ovar, categorical, groupby, nonnormal)\r\nprint(balance)\r\n\r\nprint('\\nEvaluating WNNEM')\r\n\r\nranges = [None for i in range(N)]\r\nbins = [2 for i in range(N)]\r\n\r\nddi = dissim.DDI(treated, wnnem_control, ovar, ranges, bins)\r\nprint('DDI: {:.3f} (lower is better)'.format(ddi))\r\n\r\nattribute_types = ['b' for i in range(N)]\r\n\r\nnni = dissim.NNI(treated, untreated, ovar, attribute_types, pair_name='wnnem_pair')\r\nprint('NNI: {:.3f} (lower is better)'.format(nni))\r\n\r\ngdi = dissim.GDI(treated, untreated, ovar, attribute_types, pair_name='wnnem_pair', weights=r_weights)\r\nprint('GDI: {:.3f} (lower is better)'.format(gdi))\r\n\r\nprint('\\nEvaluating PSM')\r\n\r\nddi = dissim.DDI(treated, psm_control, ovar, ranges, bins)\r\nprint('DDI: {:.3f} (lower is better)'.format(ddi))\r\n\r\nnni = dissim.NNI(treated, untreated, ovar, attribute_types, pair_name='psm_pair')\r\nprint('NNI: {:.3f} (lower is better)'.format(nni))\r\n\r\ngdi = dissim.GDI(treated, untreated, ovar, attribute_types, pair_name='psm_pair', weights=r_weights)\r\nprint('GDI: {:.3f} (lower is better)'.format(gdi))\r\n\r\nprint('\\nEvaluating SS')\r\n\r\nddi = dissim.DDI(treated, ss_control, ovar, ranges, bins)\r\nprint('DDI: {:.3f} (lower is better)'.format(ddi))\r\n\r\nprint('\\nEvaluating NN')\r\n\r\nddi = dissim.DDI(treated, nn_control, ovar, ranges, bins)\r\nprint('DDI: {:.3f} (lower is better)'.format(ddi))\r\n\r\nnni = dissim.NNI(treated, untreated, ovar, attribute_types, pair_name='nn_pair')\r\nprint('NNI: {:.3f} (lower is better)'.format(nni))\r\n\r\ngdi = dissim.GDI(treated, untreated, ovar, attribute_types, pair_name='nn_pair', weights=r_weights)\r\nprint('GDI: {:.3f} (lower is better)'.format(gdi))\r\n\r\nprint('\\nCalculating SMD\\n')\r\n\r\ntest = pd.DataFrame()\r\ntest = test.rename(columns={test.index.name:'var'})\r\n\r\ntest['bef_SMD'] = dissim.calculate_SMD(X, 'treated', ovar)\r\n\r\ntmp = pd.concat([treated, psm_control])\r\ntest['psm_SMD'] = dissim.calculate_SMD(tmp, 'treated', ovar)\r\n\r\ntmp = pd.concat([treated, wnnem_control])\r\ntest['wnnem_SMD'] = dissim.calculate_SMD(tmp, 'treated', ovar)\r\n\r\ntmp = pd.concat([treated, ss_control])\r\ntest['ss_SMD'] = dissim.calculate_SMD(tmp, 'treated', ovar)\r\n\r\ntmp = pd.concat([treated, nn_control])\r\ntest['nn_SMD'] = dissim.calculate_SMD(tmp, 'treated', ovar)\r\n\r\ntest['psm_diff'] = abs(test['psm_SMD'] - test['bef_SMD'])\r\ntest['wnnem_diff'] = abs(test['wnnem_SMD'] - test['bef_SMD'])\r\n\r\nprint(test)\r\n\r\nneeded = ['wnnem_pair', 'psm_pair', 'ss_pair', 'nn_pair']\r\notpt = create_output_file(treated, untreated, ovar, needed, False)\r\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":6213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"57882979","text":"import sys\nsys.path.append(\"..\")\nimport numpy as np\nimport montecarlo\nimport montecarlo_sym\nimport markovsparse as markov\nimport markovsparse_sym as markov_sym\n\n\nN=16\nsteps=20*N\n\nprint(u\"\"\"\n===============================================================\nexperiment 3:: density of MC,MC-sym,Markov,Markov-sym\n\"\"\")\n\navg={}\nstd={}\nprob={}\n\nprint('... mc:')\navg['mc'],std['mc']=montecarlo.montecarlo('1'*N,steps=steps,num_averages=10000)\nprint('... mc-sym:')\navg['mc-sym'],std['mc-sym']=montecarlo_sym.montecarlo('1'*N,steps=steps,num_averages=10000)\nprint('... markov:')\navg['markov'],prob['markov']=markov.markov({'1'*N:1},steps=steps)\nprint('... markov-sym:')\navg['markov-sym'],prob['markov-sym']=markov_sym.markov({'1'*N:1},steps=steps)\n\nwith open('output_exp3_montecarlo.dat','w') as f:\n for k in range(steps):\n f.write('%d %f %f %f %f\\n' % (k,avg['mc'][k],std['mc'][k],avg['mc-sym'][k],std['mc-sym'][k]))\n\nwith open('output_exp3_markov.dat','w') as g:\n for k in range(steps):\n g.write('%d %f %f\\n' % (k,avg['markov'][k],avg['markov-sym'][k]))\n","sub_path":"experiments_sparse/exp3_montecarlo_markov.py","file_name":"exp3_montecarlo_markov.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"210298801","text":"import requests\nimport os\nimport time\n# Api - https://api.cpfcnpj.com.br\nprint(\"\\033[1;37m\")\nos.system(\"clear\")\nos.system(\"figlet FullD\")\ncpf_input = input(\"CPF: \")\nif len(cpf_input) !=11:\n print(\"ERROR!!\")\n time.sleep(3)\n os.system(\"python3 cpf.py\")\n\ncpf=requests.get(\"https://api.cpfcnpj.com.br/5ae973d7a997af13f0aaf2bf60e65803/9/{}\".format(cpf_input))\n\ncpf_data=cpf.json()\n\nif \"erro\" not in cpf_data:\n os.system(\"clear\")\n print(\"-=-=--=-=-=-=-=-=-=-=-=-=-=-=-\")\n print(\"CPF: {}\".format(cpf_data[\"cpf\"]))\n print(\"Status: {}\".format(cpf_data[\"status\"]))\n print(\"SEXO: {}\".format(cpf_data[\"genero\"]))\n print(\"SITUAÇÃO: {}\".format(cpf_data[\"situacao\"]))\n print(\"Nome Da mãe: {}\".format(cpf_data[\"mae\"]))\n print(\"SALDO: {}\".format(cpf_data[\"saldo\"]))\n print(\"NASCIMENTO: {}\".format(cpf_data[\"nascimento\"]))\n print(\"Delay: {}\".format(cpf_data[\"delay\"]))\n print(\"-------------------------------\")\nprint(\"\\033[1;37m[\\033[1;32m1\\033[1;37m]Nova Consulta\\n\\033[1;37m[\\033[1;32m2\\033[1;37m]Menu\")\nop = input(\">>> \")\n\nif op == \"1\":\n os.system(\"python3 cpf2.py\")\nif op == \"2\":\n os.system(\"python3 main.py\")\nelse:\n os.system(\"python3 cpf2.py\")","sub_path":"cpf2.py","file_name":"cpf2.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"505936133","text":"import struct\nimport zlib\nfrom spock import utils\nfrom spock.mcp import mcdata, nbt\nfrom spock.mcp.mcdata import (\n MC_BOOL, MC_UBYTE, MC_BYTE, MC_USHORT, MC_SHORT, MC_UINT, MC_INT,\n MC_LONG, MC_FLOAT, MC_DOUBLE, MC_STRING, MC_VARINT, MC_SLOT, MC_META\n)\n\n#Unpack/Pack functions return None on error\n\n# Minecraft varints are 32-bit signed values\n# packed into Google Protobuf varints\ndef unpack_varint(bbuff):\n total = 0\n shift = 0\n val = 0x80\n while val&0x80:\n val = struct.unpack('B', bbuff.read(1))[0]\n total |= ((val&0x7F)<<shift)\n shift += 7\n if total >= (1<<32):\n return None\n if total&(1<<31):\n total = total - (1<<32)\n return total\n\ndef pack_varint(val):\n if val >= (1<<31) or val < -(1<<31):\n return None\n o = b''\n if val < 0:\n val = (1<<32)+val\n while val>=0x80:\n bits = val&0x7F\n val >>= 7\n o += struct.pack('B', (0x80|bits))\n bits = val&0x7F\n o += struct.pack('B', bits)\n return o\n\n# Slots are dictionaries that hold info about\n# inventory items, they also have funky\n# enchantment data stored in gziped NBT structs\ndef unpack_slot(bbuff):\n slot = {}\n slot['id'] = unpack(MC_SHORT, bbuff)\n if slot['id'] != -1:\n slot['amount'] = unpack(MC_BYTE, bbuff)\n slot['damage'] = unpack(MC_SHORT, bbuff)\n length = unpack(MC_SHORT, bbuff)\n if length > 0:\n data = bbuff.recv(length)\n try:\n ench_bbuff = utils.BoundBuffer(\n #Adding 16 to the window bits field tells zlib\n #to take care of the gzip headers for us\n zlib.decompress(data, 16+zlib.MAX_WBITS)\n )\n assert(unpack(MC_BYTE, ench_bbuff) == nbt.TAG_COMPOUND)\n name = nbt.TAG_String(buffer = ench_bbuff)\n ench = nbt.TAG_Compound(buffer = ench_bbuff)\n ench.name = name\n slot['enchants'] = ench\n except:\n slot['enchant_data'] = data\n return slot\n\ndef pack_slot(slot):\n o = pack(MC_SHORT, data['id'])\n if data['id'] != -1:\n o += pack(MC_BYTE, data['amount'])\n o += pack(MC_SHORT, data['damage'])\n if 'enchantment_data' in data:\n o += pack(MC_SHORT, len(data['enchant_data']))\n o += data['enchant_data']\n elif 'enchants' in data:\n ench = data['enchants']\n bbuff = utils.BoundBuffer()\n TAG_Byte(ench.id)._render_buffer(bbuff)\n TAG_String(ench.name)._render_buffer(bbuff)\n ench._render_buffer(bbuff)\n #Python zlib.compress doesn't provide wbits for some reason\n #So we'll use a compression object instead, no biggie\n compress = zlib.compressobj(wbits = 16+zlib.MAX_WBITS)\n ench = compress.compress(bbuff.flush())\n ench += compress.flush()\n o += pack(MC_SHORT, len(ench))\n o += ench\n else:\n o += pack(MC_SHORT, -1)\n return o\n\n# Metadata is a dictionary list thing that \n# holds metadata about entities. Currently \n# implemented as a list/tuple thing, might \n# switch to dicts\nmetadata_lookup = MC_BYTE, MC_SHORT, MC_INT, MC_FLOAT, MC_STRING, MC_SLOT\n\ndef unpack_metadata(bbuff):\n metadata = []\n head = unpack(MC_UBYTE, bbuff)\n while head != 127:\n key = head & 0x1F # Lower 5 bits\n typ = head >> 5 # Upper 3 bits\n if typ < len(metadata_lookup) and typ >= 0:\n val = unpack(metadata_lookup[typ], bbuff)\n elif typ == 6:\n val = [unpack(MC_INT, bbuff) for i in range(3)]\n else:\n return None\n metadata.append((key, (typ, val)))\n head = unpack(MC_UBYTE, bbuff)\n return metadata\n\ndef pack_metadata(metadata):\n o = b''\n for key, tmp in data:\n typ, val = tmp\n o += pack(MC_UBYTE, (typ << 5)|key)\n if typ < len(metadata_lookup) and typ >= 0:\n o += pack(metadata_lookup[typ], bbuff)\n elif typ == 6:\n for i in range(3):\n o += pack(MC_INT, val[i])\n else:\n return None\n o += pack(MC_BYTE, 127)\n return o\n\nendian = '>'\n\ndef unpack(data_type, bbuff):\n if data_type < len(mcdata.data_structs):\n format = mcdata.data_structs[data_type]\n return struct.unpack(endian+format[0], bbuff.recv(format[1]))[0]\n elif data_type == MC_VARINT:\n return unpack_varint(bbuff)\n elif data_type == MC_STRING:\n return bbuff.recv(unpack(MC_VARINT, bbuff)).decode('utf-8')\n elif data_type == MC_SLOT:\n return unpack_slot(bbuff)\n elif data_type == MC_META:\n return unpack_metadata(bbuff)\n else:\n return None\n\ndef pack(data_type, data):\n if data_type < len(mcdata.data_structs):\n format = mcdata.data_structs[data_type]\n return struct.pack(endian+format[0], data)\n elif data_type == MC_VARINT:\n return pack_varint(data)\n elif data_type == MC_STRING:\n data = data.encode('utf-8')\n return pack(MC_VARINT, len(data)) + data\n elif data_type == MC_SLOT:\n return pack_slot(data)\n elif data_type == MC_META:\n return pack_metadata(data)\n else:\n return None","sub_path":"spock/mcp/datautils.py","file_name":"datautils.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"14919202","text":"extensions = {\n \"Text Files\":[\".doc\",\".docx\",\".log\",\".msg\",\".odt\",\".pages\",\".rtf\",\".tex\",\".tif\",\".tiff\",\".txt\",\".wpd\",\".wps\"],\n \"Data Files\":[\".csv\",\".dat\",\".ged\",\".key\",\".keychain\",\".pps\",\".ppt\",\".pptx\",\".sdf\",\".tar\",\".tax2016\",\".tax2019\",\".vcf\",\".xml\"],\n \"Audio Files\":[\".aif\",\".iff\",\".m3u\",\".m4a\",\".mid\",\".mp3\",\".mpa\",\".wav\",\".wma\"],\n \"Video Files\":[\".3g2\",\".3gp\",\".asf\",\".avi\",\".flv\",\".m4v\",\".mov\",\".mp4\",\".mpg\",\".rm\",\".srt\",\".swf\",\".vob\",\".wmv\"],\n \"3D Image Files\":[\".3dm\",\".3ds\",\".max\",\".obj\"],\n \"Raster Image Files\":[\".bmp\",\".dds\",\".gif\",\".heic\",\".jpg\",\".png\",\".psd\",\".pspimage\",\".tga\",\".thm\",\".yuv\",\".jpeg\"],\n \"Vector Image Files\":[\".ai\",\".eps\",\".svg\"],\n \"Page Layout Files\":[\".indd\",\".pct\",\".pdf\"],\n \"Spreadsheet Files\":[\".xlr\",\".xls\",\".xlsx\"],\n \"Database Files\":[\".accdb\",\".db\",\".dbf\",\".mdb\",\".pdb\",\".sql\"],\n \"Executable Files\":[\".apk\",\".app\",\".bat\",\".cgi\",\".com\",\".exe\",\".gadget\",\".jar\",\".wsf\"],\n \"Game Files\":[\".b\",\".dem\",\".gam\",\".nes\",\".rom\",\".sav\"],\n \"CAD Files\":[\".dwg\",\".dxf\"],\n \"GIS Files\":[\".gpx\",\".kml\",\".kmz\"],\n \"Web Files\":[\".asp\",\".aspx\",\".cer\",\".cfm\",\".crdownload\",\".csr\",\".css\",\".dcr\",\".htm\",\".html\",\".js\",\".jsp\",\".php\",\".rss\",\".xhtml\"],\n \"Plugin Files\":[\".crx\",\".plugin\"],\n \"Font Files\":[\".fnt\",\".fon\",\".otf\",\".ttf\"],\n \"System Files\":[\".cab\",\".cpl\",\".cur\",\".deskthemepack\",\".dll\",\".dmp\",\".drv\",\".icns\",\".ico\",\".lnk\",\".sys\"],\n \"Settings Files\":[\".cfg\",\".ini\",\".prf\"],\n \"Encoded Files\":[\".hqx\",\".mim\",\".uue\"],\n \"Compressed Files\":[\".7z\",\".cbr\",\".deb\",\".gz\",\".pkg\",\".rar\",\".rpm\",\".sitx\",\".tar.gz\",\".zip\",\".zipx\"],\n \"Disk Image Files\":[\".bin\",\".cue\",\".dmg\",\".iso\",\".mdf\",\".toast\",\".vcd\"],\n \"Developer Files\":[\".c\",\".class\",\".cpp\",\".cs\",\".dtd\",\".fla\",\".h\",\".java\",\".lua\",\".m\",\".pl\",\".py\",\".sh\",\".sln\",\".swift\",\".vb\",\".vcxproj\",\".xcodeproj\"],\n \"Backup Files\":[\".bak\",\".tmp\"],\n \"Misc Files\":[\".ics\",\".msi\",\".part\",\".torrent\"],\n\n}\n\ndef getExtensionCategory(extension):\n extension = extension.lower()\n category = list(filter(lambda cat: extension in cat[1], extensions.items()))\n if len(category) == 0:\n return None\n else:\n return category[0][0]","sub_path":"Automations/messy-folder-cleaner/file_extensions.py","file_name":"file_extensions.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"336242921","text":"from keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers import Dropout\nfrom model_bulider import ModelBuilder\n\n\nclass LSTMModelBuilder(ModelBuilder):\n def __init__(self, X_train, y_train, neurons, epochs, batch_size, lstm_layers):\n super().__init__(X_train, y_train)\n self.__neurons = neurons\n self.__epochs = epochs\n self.__batch_size = batch_size\n self.__lstm_layers = lstm_layers\n\n def build_and_execute_model(self, *args, **kwargs):\n # Initialising the RNN\n regressor = Sequential()\n\n # Adding the first LSTM layer and some Dropout regularisation\n regressor.add(LSTM(units=self.__neurons, return_sequences=True,\n input_shape=(self._X_train.shape[1], self._X_train.shape[2])))\n regressor.add(Dropout(0.2))\n\n for i in range(0, self.__lstm_layers - 2): # 2 are added anyways beginning and end..\n regressor.add(LSTM(units=self.__neurons, return_sequences=True))\n regressor.add(Dropout(0.2))\n\n # Adding LSTM layer and some Dropout regularisation\n regressor.add(LSTM(units=self.__neurons))\n regressor.add(Dropout(0.2))\n\n # Adding the output layer\n regressor.add(Dense(units=1))\n\n # Compiling the RNN\n regressor.compile(optimizer='adam', loss='mean_squared_error')\n\n # Fitting the RNN to the Training set\n regressor.fit(self._X_train, self._y_train, epochs=self.__epochs, batch_size=self.__batch_size)\n\n return regressor\n","sub_path":"Aashish/deep_learning/lstm_model_builder.py","file_name":"lstm_model_builder.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"471708599","text":"# class to pull together all signal simulation and plot on a chart\nimport matplotlib.pyplot as plt\nfrom sample_simulation import *\nfrom signal_generator import *\nfrom ADC_clock import *\n\n\"\"\"\nNotes for Matplotlib usage:\n- plt.plot([x vals], [y vals], 'format str', [x2 vals], [y2 vals], 'format str')\n- plt.ylabel('y axis label'), plt.xlabel('x axis label')\n- plt.title('Title')\n- plt.axis([min_x, max_x, miny, max_y])\n- plt.subplot('xyz') \n where x = numrows\n y = numcolumns\n z = plot_number\n- plot.figure(n) # creates a new figure\n- plot.grid(True)\n- plot.show()\n\"\"\"\n\n\nclass Plotter:\n\n def __init__(self, starting_amplitude, wave_frequency, adc_sample_rate, sample_num, simulation_time):\n self.starting_amp = starting_amplitude\n self.wave_freq = wave_frequency\n self.sampling_rate = adc_sample_rate\n self.sample_number = sample_num\n self.sim_time = simulation_time\n self.sim_y_val = []\n self.sim_sample_val = []\n\n def plot_sine(self):\n # clear plot lists\n self.sim_y_val = []\n self.sim_sample_val = []\n\n plt.title('Sine Wave Plot')\n plt.xlabel('Time (s)')\n plt.ylabel('Amplitude (V)')\n plt.grid(True)\n plt.axis([0, self.sim_time, (-1 * self.starting_amp), self.starting_amp])\n sine = SignalGenerator.transient_sine(self.starting_amp, self.sim_time, self.wave_freq,\n float(1 / (self.wave_freq * 10)))\n simulation_results = SampleSimulator.sine(self.sampling_rate, self.sample_number, self.sim_time,\n self.starting_amp, self.wave_freq)\n # simulation results need to be formatted to plot\n for sample_list in simulation_results[0]:\n for sample in sample_list:\n self.sim_sample_val.append(sample)\n for y_val_list in simulation_results[1]:\n for y_val in y_val_list:\n self.sim_y_val.append(y_val)\n # create list of adc sampling for plot\n\n plt.plot(sine[0], sine[1], 'g', self.sim_sample_val, self.sim_y_val, 'rx')\n plt.show()\n\n\n########################################################################################################################\nif __name__ == '__main__':\n plotter = Plotter(1, 1, 10, 10, 5)\n plotter.plot_sine()\n","sub_path":"Simulation/ADC12 sampling/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"20810074","text":"'''不断除以 5, 是因为每间隔 5 个数有一个数可以被 5 整除,\n然后在这些可被 5 整除的数中, 每间隔 5 个数又有一个可以被 25 整除,\n故要再除一次, ... 直到结果为 0, 表示没有能继续被 5 整除的数了.'''\nclass Solution(object):\n def trailingZeroes(self, n):\n count=0\n while n:\n count+=n/5\n n/=5\n return count\n","sub_path":"python/阶乘后的零.py","file_name":"阶乘后的零.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"376836414","text":"from main import appli\nfrom flask import render_template, request, redirect, url_for, json\nimport requests\n\napi_server_add = 'http://api-server:4000/adition'\napi_server_sub = 'http://api-server:4000/subtraction'\nexercises = requests.get(url=api_server_add)\n\n\n@appli.errorhandler(404)\ndef error_404(error):\n return render_template('404.html', error=error)\n\n\n@appli.route('/cal')\ndef cal():\n return render_template('cal.html', title='Calender Page')\n\n\n@appli.route('/sub')\ndef sub():\n return render_template('sub.html', title='Subtract Page')\n\n\n@appli.route('/sub', methods=['POST'])\ndef submit_sub():\n global exercises\n num1 = request.form.get('num1')\n num2 = request.form.get('num2')\n ip = request.remote_addr\n jason = {\n 'num1': int(num1),\n 'num2': int(num2),\n 'ip': ip\n }\n result = requests.post(url=api_server_sub, json=jason)\n exercises = requests.get(url=api_server_sub)\n data = result.json()\n return render_template('sub.html', title='Subtract Page', num1=num1, num2=num2, result=data['result'])\n\n\n@appli.route('/add')\ndef add():\n return render_template('add.html', title='Add Page')\n\n\n@appli.route('/delete', methods=['POST'])\ndef delete():\n id = request.form.get('id')\n req = {'id': id}\n res = requests.delete(api_server_add, json=req)\n return redirect(url_for('home2'))\n\n\n@appli.route('/delete')\ndef delete_page():\n global exercises\n data = exercises.json()\n return render_template('delete.html', title='Delete Page', exercises=data)\n\n\n@appli.route('/add', methods=['POST'])\ndef submit_add():\n global exercises\n num1 = request.form.get('num1')\n num2 = request.form.get('num2')\n ip = request.remote_addr\n jason = {\n 'num1': int(num1),\n 'num2': int(num2),\n 'ip': ip\n }\n result = requests.post(url=api_server_add, json=jason)\n exercises = requests.get(url=api_server_add)\n data = result.json()\n return render_template('add.html', title='Add Page', num1=num1, num2=num2, result=data['result'])\n\n\n@appli.route('/')\ndef home2():\n global exercises\n exercises = requests.get(url=api_server_add)\n return redirect(url_for('home'))\n\n\n@appli.route('/home')\ndef home():\n global exercises\n data = exercises.json()\n return render_template('homepage.html', title='Home Page', exercises=data)\n\n","sub_path":"frontend/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"140733811","text":"import os\nfrom readpara import read_para\n\ndef syten_envi (argv):\n fname = argv[1]\n\n # Write memory usage\n jname = read_para (fname, 'name', str, '=')\n #os.environ['SYTEN_MEMORY_SAMPLER'] = jname+'.mem'\n\n #os.environ['SYTEN_DEFAULT_TPO_TRUNCATE'] = 'p'\n os.environ['SYTENDIR'] = os.environ['SYTENDIRREAL']\n\n symm = read_para (fname, 'symm', str, '=')\n if '-gc' in argv or symm == 'su2gc':\n os.environ['SYTENDIR'] = os.environ['SYTENDIRGCREAL']\n\n cplx = read_para (fname, 'complex', str, '=', ('no'))\n if '-cplx' in argv or cplx == 'yes':\n os.environ['SYTENDIR'] = os.environ['SYTENDIRCPLX']\n\n","sub_path":"environ.py","file_name":"environ.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"323939556","text":"\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.\nimport os, sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport skimage.io\nfrom skimage.transform import resize\nfrom imgaug import augmenters as iaa\nfrom tqdm import tqdm\nimport PIL\nfrom PIL import Image, ImageOps\nimport cv2\nfrom sklearn.utils import class_weight, shuffle\nfrom keras.losses import binary_crossentropy\nfrom keras.applications.resnet50 import preprocess_input\nimport keras.backend as K\nimport tensorflow as tf\nfrom sklearn.metrics import f1_score, fbeta_score\nfrom keras.utils import Sequence\nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\n\nWORKERS = 2\nCHANNEL = 3\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nIMG_SIZE = 512\nNUM_CLASSES = 5\nSEED = 77\nTRAIN_NUM = 1000 # use 1000 when you just want to explore new idea, use -1 for full train\ndf_train = pd.read_csv('../input/aptos2019-blindness-detection/train.csv')\ndf_test = pd.read_csv('../input/aptos2019-blindness-detection/test.csv')\n\nx = df_train['id_code']\ny = df_train['diagnosis']\n\nx, y = shuffle(x, y, random_state=SEED)\n\ntrain_x, valid_x, train_y, valid_y = train_test_split(x, y, test_size=0.15,\n stratify=y, random_state=SEED)\nprint(train_x.shape, train_y.shape, valid_x.shape, valid_y.shape)\ntrain_y.hist()\nvalid_y.hist()\n### %time\nfig = plt.figure(figsize=(25, 16))\n# display 10 images from each class\nfor class_id in sorted(train_y.unique()):\n for i, (idx, row) in enumerate(df_train.loc[df_train['diagnosis'] == class_id].sample(5, random_state=SEED).iterrows()):\n ax = fig.add_subplot(5, 5, class_id * 5 + i + 1, xticks=[], yticks=[])\n path=f\"../input/aptos2019-blindness-detection/train_images/{row['id_code']}.png\"\n image = cv2.imread(path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n\n plt.imshow(image)\n ax.set_title('Label: %d-%d-%s' % (class_id, idx, row['id_code']) )\n \n\n### %time\nfig = plt.figure(figsize=(25, 16))\nfor class_id in sorted(train_y.unique()):\n for i, (idx, row) in enumerate(df_train.loc[df_train['diagnosis'] == class_id].sample(5, random_state=SEED).iterrows()):\n ax = fig.add_subplot(5, 5, class_id * 5 + i + 1, xticks=[], yticks=[])\n path=f\"../input/aptos2019-blindness-detection/train_images/{row['id_code']}.png\"\n image = cv2.imread(path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n# image=cv2.addWeighted ( image, 0 , cv2.GaussianBlur( image , (0 ,0 ) , 10) ,-4 ,128)\n image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n\n plt.imshow(image, cmap='gray')\n ax.set_title('Label: %d-%d-%s' % (class_id, idx, row['id_code']) )\ndpi = 80 #inch\n\n# path=f\"../input/aptos2019-blindness-detection/train_images/5c7ab966a3ee.png\" # notice upper part\npath=f\"../input/aptos2019-blindness-detection/train_images/cd54d022e37d.png\" # lower-right, this still looks not so severe, can be class3\nimage = cv2.imread(path)\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nheight, width = image.shape\nprint(height, width)\n\nSCALE=2\nfigsize = (width / float(dpi))/SCALE, (height / float(dpi))/SCALE\n\nfig = plt.figure(figsize=figsize)\nplt.imshow(image, cmap='gray')\n### %time\nfig = plt.figure(figsize=(25, 16))\nfor class_id in sorted(train_y.unique()):\n for i, (idx, row) in enumerate(df_train.loc[df_train['diagnosis'] == class_id].sample(5, random_state=SEED).iterrows()):\n ax = fig.add_subplot(5, 5, class_id * 5 + i + 1, xticks=[], yticks=[])\n path=f\"../input/aptos2019-blindness-detection/train_images/{row['id_code']}.png\"\n image = cv2.imread(path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n# image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n image=cv2.addWeighted ( image,4, cv2.GaussianBlur( image , (0,0) , IMG_SIZE/10) ,-4 ,128) # the trick is to add this line\n\n plt.imshow(image, cmap='gray')\n ax.set_title('Label: %d-%d-%s' % (class_id, idx, row['id_code']) )\ndef crop_image1(img,tol=7):\n # img is image data\n # tol is tolerance\n \n mask = img>tol\n return img[np.ix_(mask.any(1),mask.any(0))]\n\ndef crop_image_from_gray(img,tol=7):\n if img.ndim ==2:\n mask = img>tol\n return img[np.ix_(mask.any(1),mask.any(0))]\n elif img.ndim==3:\n gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n mask = gray_img>tol\n \n check_shape = img[:,:,0][np.ix_(mask.any(1),mask.any(0))].shape[0]\n if (check_shape == 0): # image is too dark so that we crop out everything,\n return img # return original image\n else:\n img1=img[:,:,0][np.ix_(mask.any(1),mask.any(0))]\n img2=img[:,:,1][np.ix_(mask.any(1),mask.any(0))]\n img3=img[:,:,2][np.ix_(mask.any(1),mask.any(0))]\n # print(img1.shape,img2.shape,img3.shape)\n img = np.stack([img1,img2,img3],axis=-1)\n # print(img.shape)\n return img\n\n# OLD version of image color cropping, use crop_image_from_gray instead\n# The above code work only for 1-channel. Here is my simple extension for 3-channels image\ndef crop_image(img,tol=7):\n if img.ndim ==2:\n mask = img>tol\n return img[np.ix_(mask.any(1),mask.any(0))]\n elif img.ndim==3:\n h,w,_=img.shape\n# print(h,w)\n img1=cv2.resize(crop_image1(img[:,:,0]),(w,h))\n img2=cv2.resize(crop_image1(img[:,:,1]),(w,h))\n img3=cv2.resize(crop_image1(img[:,:,2]),(w,h))\n \n# print(img1.shape,img2.shape,img3.shape)\n img[:,:,0]=img1\n img[:,:,1]=img2\n img[:,:,2]=img3\n return img\n\n'''all of these do not work'''\n\ndef crop_image2(image,threshold=5):\n if len(image.shape) == 3:\n flatImage = np.max(image, 2)\n else:\n flatImage = image\n assert len(flatImage.shape) == 2\n\n rows = np.where(np.max(flatImage, 0) > threshold)[0]\n if rows.size:\n cols = np.where(np.max(flatImage, 1) > threshold)[0]\n image = image[cols[0]: cols[-1] + 1, rows[0]: rows[-1] + 1]\n else:\n image = image[:1, :1]\n\n return image\n\ndef crop_image3(image):\n mask = image > 0\n\n # Coordinates of non-black pixels.\n coords = np.argwhere(mask)\n\n # Bounding box of non-black pixels.\n x0, y0 = coords.min(axis=0)\n x1, y1 = coords.max(axis=0) + 1 # slices are exclusive at the top\n \n # Get the contents of the bounding box.\n cropped = image[x0:x1, y0:y1]\n return cropped\n\ndef crop_image4(image):\n _,thresh = cv2.threshold(image,1,255,cv2.THRESH_BINARY)\n contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n cnt = contours[0]\n x,y,w,h = cv2.boundingRect(cnt)\n crop = image[y:y+h,x:x+w]\n return crop\n\n\ndef load_ben_color(path, sigmaX=10):\n image = cv2.imread(path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image = crop_image_from_gray(image)\n image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n image=cv2.addWeighted ( image,4, cv2.GaussianBlur( image , (0,0) , sigmaX) ,-4 ,128)\n \n return image\n### %time\n\nNUM_SAMP=7\nfig = plt.figure(figsize=(25, 16))\nfor class_id in sorted(train_y.unique()):\n for i, (idx, row) in enumerate(df_train.loc[df_train['diagnosis'] == class_id].sample(NUM_SAMP, random_state=SEED).iterrows()):\n ax = fig.add_subplot(5, NUM_SAMP, class_id * NUM_SAMP + i + 1, xticks=[], yticks=[])\n path=f\"../input/aptos2019-blindness-detection/train_images/{row['id_code']}.png\"\n image = load_ben_color(path,sigmaX=30)\n\n plt.imshow(image)\n ax.set_title('%d-%d-%s' % (class_id, idx, row['id_code']) )\ndef circle_crop(img, sigmaX=10): \n \"\"\"\n Create circular crop around image centre \n \"\"\" \n \n img = cv2.imread(img)\n img = crop_image_from_gray(img) \n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n \n height, width, depth = img.shape \n \n x = int(width/2)\n y = int(height/2)\n r = np.amin((x,y))\n \n circle_img = np.zeros((height, width), np.uint8)\n cv2.circle(circle_img, (x,y), int(r), 1, thickness=-1)\n img = cv2.bitwise_and(img, img, mask=circle_img)\n img = crop_image_from_gray(img)\n img=cv2.addWeighted ( img,4, cv2.GaussianBlur( img , (0,0) , sigmaX) ,-4 ,128)\n return img \n### %time\n## try circle crop\nNUM_SAMP=7\nfig = plt.figure(figsize=(25, 16))\nfor class_id in sorted(train_y.unique()):\n for i, (idx, row) in enumerate(df_train.loc[df_train['diagnosis'] == class_id].sample(NUM_SAMP, random_state=SEED).iterrows()):\n ax = fig.add_subplot(5, NUM_SAMP, class_id * NUM_SAMP + i + 1, xticks=[], yticks=[])\n path=f\"../input/aptos2019-blindness-detection/train_images/{row['id_code']}.png\"\n image = circle_crop(path,sigmaX=30)\n\n plt.imshow(image)\n ax.set_title('%d-%d-%s' % (class_id, idx, row['id_code']) )\ndpi = 80 #inch\n\n# path=f\"../input/aptos2019-blindness-detection/train_images/5c7ab966a3ee.png\" # notice upper part\npath=f\"../input/aptos2019-blindness-detection/train_images/cd54d022e37d.png\" # lower-right, can be class3\nimage = load_ben_color(path,sigmaX=10)\n\nheight, width = IMG_SIZE, IMG_SIZE\nprint(height, width)\n\nSCALE=1\nfigsize = (width / float(dpi))/SCALE, (height / float(dpi))/SCALE\n\nfig = plt.figure(figsize=figsize)\nplt.imshow(image, cmap='gray')\n### %time\nNUM_SAMP=10\nfig = plt.figure(figsize=(25, 16))\nfor jj in range(5):\n for i, (idx, row) in enumerate(df_test.sample(NUM_SAMP,random_state=SEED+jj).iterrows()):\n ax = fig.add_subplot(5, NUM_SAMP, jj * NUM_SAMP + i + 1, xticks=[], yticks=[])\n path=f\"../input/aptos2019-blindness-detection/test_images/{row['id_code']}.png\"\n image = load_ben_color(path,sigmaX=30)\n \n plt.imshow(image)\n ax.set_title('%d-%s' % (idx, row['id_code']) )\n### %time\n'''Bonus : sigmaX=50'''\nNUM_SAMP=10\nfig = plt.figure(figsize=(25, 16))\nfor jj in range(5):\n for i, (idx, row) in enumerate(df_test.sample(NUM_SAMP,random_state=SEED+jj).iterrows()):\n ax = fig.add_subplot(5, NUM_SAMP, jj * NUM_SAMP + i + 1, xticks=[], yticks=[])\n path=f\"../input/aptos2019-blindness-detection/test_images/{row['id_code']}.png\"\n image = load_ben_color(path,sigmaX=50)\n\n plt.imshow(image, cmap='gray')\n ax.set_title('%d-%s' % (idx, row['id_code']) )\n'''\n# This is the old imperfect 'by-channel' color cropping code\n# this code can cause different crop among 3 channels\n\n# try cropping color image with the fixed function\n# path=f\"../input/aptos2019-blindness-detection/train_images/5c7ab966a3ee.png\"\npath=f\"../input/aptos2019-blindness-detection/train_images/cd54d022e37d.png\"\nimage = cv2.imread(path)\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\nimage = crop_image(image)\n# image = crop_image_from_gray(image)\nimage = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\nimage=cv2.addWeighted ( image,4, cv2.GaussianBlur( image , (0,0) , 10) ,-4 ,128)\n\nheight, width = IMG_SIZE, IMG_SIZE\nprint(height, width)\n\nSCALE=1\nfigsize = (width / float(dpi))/SCALE, (height / float(dpi))/SCALE\n\nfig = plt.figure(figsize=figsize)\nplt.imshow(image)\n'''\n### ls ../input/diabetic-retinopathy-resized/\n### ls ../input/diabetic-retinopathy-resized/resized_train/resized_train | head\ndf_old = pd.read_csv('../input/diabetic-retinopathy-resized/trainLabels.csv')\n\ndf_old.head()\nNUM_SAMP=10\nfig = plt.figure(figsize=(25, 16))\nfor class_id in sorted(train_y.unique()):\n for i, (idx, row) in enumerate(df_old.loc[df_old['level'] == class_id].sample(NUM_SAMP, random_state=SEED).iterrows()):\n ax = fig.add_subplot(5, NUM_SAMP, class_id * NUM_SAMP + i + 1, xticks=[], yticks=[])\n path=f\"../input/diabetic-retinopathy-resized/resized_train/resized_train/{row['image']}.jpeg\"\n image = load_ben_color(path,sigmaX=30)\n\n plt.imshow(image)\n ax.set_title('%d-%d-%s' % (class_id, idx, row['image']) )\nNUM_SAMP=10\nfig = plt.figure(figsize=(25, 16))\nfor class_id in sorted(train_y.unique()):\n for i, (idx, row) in enumerate(df_old.loc[df_old['level'] == class_id].sample(NUM_SAMP, random_state=SEED).iterrows()):\n ax = fig.add_subplot(5, NUM_SAMP, class_id * NUM_SAMP + i + 1, xticks=[], yticks=[])\n path=f\"../input/diabetic-retinopathy-resized/resized_train/resized_train/{row['image']}.jpeg\"\n image = cv2.imread(path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n# image = crop_image_from_gray(image)\n image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n# image=cv2.addWeighted ( image,4, cv2.GaussianBlur( image , (0,0) , IMG_SIZE/10) ,-4 ,128)\n\n plt.imshow(image, cmap='gray')\n ax.set_title('%d-%d-%s' % (class_id, idx, row['image']) )\ndpi = 80 #inch\n\npath=f\"../input/diabetic-retinopathy-resized/resized_train/resized_train/31590_right.jpeg\" # too many vessels?\n# path=f\"../input/diabetic-retinopathy-resized/resized_train/resized_train/18017_left.jpeg\" # details are lost\nimage = load_ben_color(path,sigmaX=30)\n# image = cv2.imread(path)\n# image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n# image = crop_image1(image)\n# image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n# image=cv2.addWeighted ( image,4, cv2.GaussianBlur( image , (0,0) , IMG_SIZE/10) ,-4 ,128)\n\nheight, width = IMG_SIZE, IMG_SIZE\nprint(height, width)\n\nSCALE=1\nfigsize = (width / float(dpi))/SCALE, (height / float(dpi))/SCALE\n\nfig = plt.figure(figsize=figsize)\nplt.imshow(image, cmap='gray')\n### ls ../input/retinopathy-train-2015/rescaled_train_896/rescaled_train_896/ | head\ndpi = 80 #inch\n\npath_jpg=f\"../input/diabetic-retinopathy-resized/resized_train/resized_train/18017_left.jpeg\" # too many vessels?\npath_png=f\"../input/retinopathy-train-2015/rescaled_train_896/rescaled_train_896/18017_left.png\" # details are lost\nimage = cv2.imread(path_png)\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\nimage = crop_image(image)\nimage = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n\nimage2 = cv2.imread(path_jpg)\nimage2 = cv2.cvtColor(image2, cv2.COLOR_BGR2RGB)\nimage2 = crop_image(image2)\nimage2 = cv2.resize(image2, (IMG_SIZE, IMG_SIZE))\n\n\nheight, width = IMG_SIZE, IMG_SIZE\nprint(height, width)\n\nSCALE=1/4\nfigsize = (width / float(dpi))/SCALE, (height / float(dpi))/SCALE\n\nfig = plt.figure(figsize=figsize)\nax = fig.add_subplot(2, 2, 1, xticks=[], yticks=[])\nax.set_title('png format original' )\nplt.imshow(image, cmap='gray')\nax = fig.add_subplot(2, 2, 2, xticks=[], yticks=[])\nax.set_title('jpg format original' )\nplt.imshow(image2, cmap='gray')\n\nimage = load_ben_color(path_png,sigmaX=30)\nimage2 = load_ben_color(path_jpg,sigmaX=30)\nax = fig.add_subplot(2, 2, 3, xticks=[], yticks=[])\nax.set_title('png format transformed' )\nplt.imshow(image, cmap='gray')\nax = fig.add_subplot(2, 2, 4, xticks=[], yticks=[])\nax.set_title('jpg format transformed' )\nplt.imshow(image2, cmap='gray')\n\n","sub_path":"sources/aptos-eye-preprocessing-in-diabetic-retinopathy.py","file_name":"aptos-eye-preprocessing-in-diabetic-retinopathy.py","file_ext":"py","file_size_in_byte":15473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"443492919","text":"#!/usr/bin/env python\n#\n# Copyright 2014 Quantopian, 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\nimport sys\nimport os\nfrom pathlib import Path\n\n# ensure the current directory is on sys.path\n# so versioneer can be imported when pip uses\n# PEP 517/518 build rules.\n# https://github.com/python-versioneer/python-versioneer/issues/193\nsys.path.append(Path(__file__).resolve(strict=True).parent.as_posix())\nimport versioneer # noqa: E402\nfrom setuptools import Extension, find_packages, setup # noqa: E402\n\n\nclass LazyBuildExtCommandClass(dict):\n \"\"\"\n Lazy command class that defers operations requiring Cython and numpy until\n they've actually been downloaded and installed by setup_requires.\n \"\"\"\n\n def __contains__(self, key):\n return key == \"build_ext\" or super(LazyBuildExtCommandClass, self).__contains__(\n key\n )\n\n def __setitem__(self, key, value):\n if key == \"build_ext\":\n raise AssertionError(\"build_ext overridden!\")\n super(LazyBuildExtCommandClass, self).__setitem__(key, value)\n\n def __getitem__(self, key):\n if key != \"build_ext\":\n return super(LazyBuildExtCommandClass, self).__getitem__(key)\n\n from Cython.Distutils import build_ext as cython_build_ext\n import numpy\n\n # Cython_build_ext isn't a new-style class in Py2.\n class build_ext(cython_build_ext, object):\n \"\"\"\n Custom build_ext command that lazily adds numpy's include_dir to\n extensions.\n \"\"\"\n\n def build_extensions(self):\n \"\"\"\n Lazily append numpy's include directory to Extension includes.\n\n This is done here rather than at module scope because setup.py\n may be run before numpy has been installed, in which case\n importing numpy and calling `numpy.get_include()` will fail.\n \"\"\"\n numpy_incl = numpy.get_include()\n for ext in self.extensions:\n ext.include_dirs.append(numpy_incl)\n\n super(build_ext, self).build_extensions()\n\n return build_ext\n\n\ndef window_specialization(typename):\n \"\"\"Make an extension for an AdjustedArrayWindow specialization.\"\"\"\n return Extension(\n name=f\"zipline.lib._{typename}window\",\n sources=[f\"src/zipline/lib/_{typename}window.pyx\"],\n depends=[\"src/zipline/lib/_windowtemplate.pxi\"],\n define_macros=[(\"NPY_NO_DEPRECATED_API\", \"NPY_1_7_API_VERSION\")],\n )\n\n\next_options = dict(\n compiler_directives=dict(profile=True, language_level=\"3\"),\n annotate=True,\n)\next_modules = [\n Extension(\n name=\"zipline.assets._assets\",\n sources=[\"src/zipline/assets/_assets.pyx\"],\n define_macros=[(\"NPY_NO_DEPRECATED_API\", \"NPY_1_7_API_VERSION\")],\n ),\n Extension(\n name=\"zipline.assets.continuous_futures\",\n sources=[\"src/zipline/assets/continuous_futures.pyx\"],\n define_macros=[(\"NPY_NO_DEPRECATED_API\", \"NPY_1_7_API_VERSION\")],\n ),\n Extension(\n name=\"zipline.lib.adjustment\",\n sources=[\"src/zipline/lib/adjustment.pyx\"],\n define_macros=[(\"NPY_NO_DEPRECATED_API\", \"NPY_1_7_API_VERSION\")],\n ),\n Extension(\n name=\"zipline.lib._factorize\",\n sources=[\"src/zipline/lib/_factorize.pyx\"],\n define_macros=[(\"NPY_NO_DEPRECATED_API\", \"NPY_1_7_API_VERSION\")],\n ),\n window_specialization(\"float64\"),\n window_specialization(\"int64\"),\n window_specialization(\"int64\"),\n window_specialization(\"uint8\"),\n window_specialization(\"label\"),\n Extension(\n name=\"zipline.lib.rank\",\n sources=[\"src/zipline/lib/rank.pyx\"],\n define_macros=[(\"NPY_NO_DEPRECATED_API\", \"NPY_1_7_API_VERSION\")],\n ),\n Extension(\n name=\"zipline.data._equities\",\n sources=[\"src/zipline/data/_equities.pyx\"],\n define_macros=[(\"NPY_NO_DEPRECATED_API\", \"NPY_1_7_API_VERSION\")],\n ),\n Extension(\n name=\"zipline.data._adjustments\",\n sources=[\"src/zipline/data/_adjustments.pyx\"],\n define_macros=[(\"NPY_NO_DEPRECATED_API\", \"NPY_1_7_API_VERSION\")],\n ),\n Extension(\n name=\"zipline._protocol\",\n sources=[\"src/zipline/_protocol.pyx\"],\n define_macros=[(\"NPY_NO_DEPRECATED_API\", \"NPY_1_7_API_VERSION\")],\n ),\n Extension(\n name=\"zipline.finance._finance_ext\",\n sources=[\"src/zipline/finance/_finance_ext.pyx\"],\n define_macros=[(\"NPY_NO_DEPRECATED_API\", \"NPY_1_7_API_VERSION\")],\n ),\n Extension(\n name=\"zipline.gens.sim_engine\",\n sources=[\"src/zipline/gens/sim_engine.pyx\"],\n define_macros=[(\"NPY_NO_DEPRECATED_API\", \"NPY_1_7_API_VERSION\")],\n ),\n Extension(\n name=\"zipline.data._minute_bar_internal\",\n sources=[\"src/zipline/data/_minute_bar_internal.pyx\"],\n define_macros=[(\"NPY_NO_DEPRECATED_API\", \"NPY_1_7_API_VERSION\")],\n ),\n Extension(\n name=\"zipline.data._resample\",\n sources=[\"src/zipline/data/_resample.pyx\"],\n define_macros=[(\"NPY_NO_DEPRECATED_API\", \"NPY_1_7_API_VERSION\")],\n ),\n]\nfor ext_module in ext_modules:\n ext_module.cython_directives = dict(language_level=\"3\")\n\nversion = versioneer.get_version()\n\nsetup(\n version=version,\n cmdclass=LazyBuildExtCommandClass(versioneer.get_cmdclass()),\n entry_points={\n \"console_scripts\": [\n \"zipline = zipline.__main__:main\",\n ],\n },\n # packages=find_packages(include=[\"src/zipline\"]),\n ext_modules=ext_modules,\n # package_dir={'': 'src'},\n # packages=find_packages(where='src'),\n package_data={\n root.replace(os.sep, \".\"): [\"*.pyi\", \"*.pyx\", \"*.pxi\", \"*.pxd\"]\n for root, dirnames, filenames in os.walk(\"src/zipline\")\n if \"__pycache__\" not in root\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":6323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"242612027","text":"from main_site.models import News\nfrom rest_framework import serializers\n\nclass NewsSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = News\n fields = [\n 'news_id',\n 'title',\n 'author',\n 'context', \n 'news_url', \n 'img_url', \n 'post_date', \n 'create_date',\n ]","sub_path":"scrapyNBANews/nba_news_site/main_site/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"51"} +{"seq_id":"139020327","text":"# -*- coding: utf-8 -*-\n\"\"\"\nhelper functions to load in the data\n\"\"\"\nimport json\nimport os\nimport requests\n\ndef load_unique_vals():\n folder = os.path.dirname(os.path.abspath(__file__)) + '/data'\n file = os.path.join(folder, 'unique_vals.json')\n\n with open(file, 'r') as json_data:\n unique_vals = json.load(json_data)\n\n return unique_vals\n\ndef add_search_inputs(params, search_args):\n if not search_args:\n return params\n\n if len(search_args) == 1 and type(search_args[0]) == str:\n params['reason_for_search'] = search_args\n return params\n elif len(search_args) == 1 and type(search_args[0]) == list:\n params['reason_for_search'] = search_args[0]\n return params\n elif len(search_args) == 2 and type(search_args[1]) == bool:\n if type(search_args[0]) == str:\n params['reason_for_search'] = [search_args[0]]\n params['contraband_found'] = search_args[1]\n return params\n elif type(search_args[0]) == list:\n params['reason_for_search'] = search_args[0]\n params['contraband_found'] = search_args[1]\n return params\n elif search_args == [None]:\n params['reason_for_search'] = []\n return params\n\ndef make_api_call(end_point_type, params):\n if os.environ.get('FLASK_ENV') == 'development':\n username = os.environ['SIGNIN']\n password = os.environ['PASSWORD']\n base_url = 'http://www.police-project-test.xyz/api/v1/'\n api_url = f'{base_url}{end_point_type}'\n request = requests.get(api_url, params=params, auth=(username, password))\n return request.json()\n elif os.environ.get('FLASK_ENV') == 'production':\n base_url = 'http://www.policexray.com/api/v1/'\n api_url = f'{base_url}{end_point_type}'\n request = requests.get(api_url, params=params)\n return request.json()\n","sub_path":"main_app/dashboards/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"196127524","text":"import tkinter as Tkinter\nimport ctypes\nuser32 = ctypes.windll.user32\nh = user32.GetSystemMetrics(0)\nw = user32.GetSystemMetrics(1)\nscreensize = user32.GetSystemMetrics(1)\nsafecolor = \"#64FE2E\"\nroot = Tkinter.Tk()\nroot.title(\"Cd ejecter by pruthvi\")\ndef center_window(w=350, h=30):\n ws = root.winfo_screenwidth()\n hs = root.winfo_screenheight()\n x = (ws/2) - (w/2)\n y = (hs/2) - (h/2)\n root.geometry('%dx%d+%d+%d' % (w, h, x, y))\ndef Opencd():\n ctypes.windll.WINMM.mciSendStringW(u\"set cdaudio door open\", None, 0, None)\n ejectbutton[\"bg\"] = safecolor\n\nejectbutton = Tkinter.Button(root, text =\"Eject cd\", command = Opencd,bg=\"red\")\nroot.configure(background='black')\nejectbutton.pack()\ncenter_window()\nroot.mainloop()","sub_path":"eject.py","file_name":"eject.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"47086725","text":"import os\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom operator import itemgetter\nimport datetime\nimport itertools\n\nfrom ImportFunctions import *\n\ninput_path = \"../input/\"\nout_path = \"../output/\"\noutname = \"complaints.csv\"\n\nfiles = [input_path + f for f in os.listdir(input_path)]\n\ncmpl_data = pd.DataFrame()\ncmpl_metadata = pd.DataFrame()\ncmpl_out = \"complaints.csv\"\n\ninv_data = pd.DataFrame()\ninv_metadata = pd.DataFrame()\ninv_out = \"investigators.csv\"\n\nfor f in files:\n df = ReadMessy(f)\n df.insert(0, \"CRID\", (df[\"Number:\"]\n .fillna(method='ffill')\n .astype(int)))\n cmpl_df = (df[~df[\"Number:\"].isnull()]\n .dropna(how='all', axis=0)\n .dropna(how='all',axis=1)\n .drop('Number:', axis=1))\n\n cmpl_df.columns = [\"CRID\", \"Beat\", \"Location.Code\", \"Address.Number\", \"Street\", \"Apartment.Number\", \"City.State\", \"Incident.Datetime\", \"Complaint.Date\", \"Closed.Date\"]\n cmpl_data = (cmpl_data\n .append(cmpl_df)\n .reset_index(drop=True))\n \n cmpl_md = metadata_dataset(cmpl_df, f, cmpl_out) \n cmpl_metadata = (cmpl_metadata\n .append(cmpl_md)\n .reset_index(drop=True))\n\n inv_df = (df[df[\"Number:\"].isnull()]\n .dropna(how='all', axis=0)\n .dropna(how='all',axis=1)\n .drop('Beat:', axis=1))\n inv_df.columns = [\"CRID\", \"Full.Name\", \"Assignment\", \"Rank\", \"Star\", \"Appointed.Date\"]\n inv_data = (inv_data\n .append(inv_df)\n .reset_index(drop=True))\n \n inv_md = metadata_dataset(inv_df, f, inv_out)\n inv_metadata = (inv_metadata\n .append(inv_md)\n .reset_index(drop=True))\n\ncmpl_metadata.to_csv(\"../output/\" + \"metadata_\" + cmpl_out, index = False)\ncmpl_data.to_csv(\"../output/\" + cmpl_out , index = False)\ninv_metadata.to_csv(\"../output/\" + \"metadata_\" + inv_out, index = False)\ninv_data.to_csv(\"../output/\" + inv_out , index = False)\n","sub_path":"cpd-test/individual/p046957_complaints-cpd-2016-nov/complaints/import/src/import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"188433189","text":"import sys\nimport unittest\n\ntest_modules = [\"test_data_loader\", \"test_data_manager\", \"test_download_tar\", \"test_get_dates_umich\", \"test_tar_extract\"]\n\nsuite = unittest.TestSuite()\n\nfor t in test_modules:\n print(\"adding tests in \\\"\" + t + \"\\\"\")\n suite.addTest(unittest.defaultTestLoader.loadTestsFromName(t))\n\nresult = not unittest.TextTestRunner().run(suite).wasSuccessful()\nsys.exit(result) # Throw exit code 1 if tests failed","sub_path":"test/run_tests.py","file_name":"run_tests.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"331854222","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass SparkJobListViewResponse(Model):\n \"\"\"SparkJobListViewResponse.\n\n :param n_jobs:\n :type n_jobs: int\n :param spark_jobs:\n :type spark_jobs: list[~azure.synapse.models.SparkJob]\n \"\"\"\n\n _attribute_map = {\n 'n_jobs': {'key': 'nJobs', 'type': 'int'},\n 'spark_jobs': {'key': 'sparkJobs', 'type': '[SparkJob]'},\n }\n\n def __init__(self, **kwargs):\n super(SparkJobListViewResponse, self).__init__(**kwargs)\n self.n_jobs = kwargs.get('n_jobs', None)\n self.spark_jobs = kwargs.get('spark_jobs', None)\n","sub_path":"src/synapse/azext_synapse/vendored_sdks/azure_synapse/models/spark_job_list_view_response.py","file_name":"spark_job_list_view_response.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"68914412","text":"import os\nfrom sqlalchemy import create_engine, MetaData, text\n\n\ndef start():\n dburi = os.getenv(\"DBURI\", \"sqlite:///:memory:\")\n engine = create_engine(dburi, echo=False, future=True)\n with engine.connect() as conn:\n meta = MetaData(engine)\n engine.echo = True\n meta.reflect(views=True)\n t = text('select * from pg_catalog.pg_stat_activity where usename=:uname')\n res = conn.execute(t, {\"uname\": \"postgres\"})\n for i in res:\n print(i)\n\n\nif __name__ == \"__main__\":\n start()","sub_path":"probak/sqlalchemy_proba0.py","file_name":"sqlalchemy_proba0.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"440662520","text":"from colorama import Fore, init;import threading, os, platform;from queue import Queue;import tkinter;from tkinter import filedialog;from tkinter import messagebox;import time, string, subprocess, requests, random, ctypes, webbrowser;import pypresence;from pypresence import Presence\nnow = time.time()\ninit()\nroot = tkinter.Tk()\nroot.withdraw()\nviews = 0\nerrors = 0\nversion = '1.0'\nRED = Fore.LIGHTRED_EX\nWHITE = Fore.LIGHTWHITE_EX\nlogo = f\"\"\"\n\n{WHITE} ____ ____ ______ __ __ {RED} .___________. __ __ .______ _______ \n{WHITE} \\ \\ / / / __ \\ | | | |{RED} | || | | | | _ \\ | ____|\n{WHITE} \\ \\/ / | | | | | | | |{RED} `---| |----`| | | | | |_) | | |__ \n{WHITE} \\_ _/ | | | | | | | |{RED} | | | | | | | _ < | __| \n{WHITE} | | | `--' | | `--' |{RED} | | | `--' | | |_) | | |____ \n{WHITE} |__| \\______/ \\______/ {RED} |__| \\______/ |______/ |_______|\n \n {WHITE} Made by 0x72 (version: {version})\n\n\"\"\"\n\ndef logo_print():\n print(f\"{logo}\")\ndef clear():\n try:\n os.system('cls')\n except:\n os.system('clear')\ndef update_title(new_title):\n ctypes.windll.kernel32.SetConsoleTitleW(f'{new_title}')\n\nerr = False\nclient_id = '696453816609931385'\nRPC = Presence(client_id=client_id)\ntry:\n RPC.connect()\n RPC.update(large_image='logo', large_text='Made by 0x72',details='Main Menu', start=now)\nexcept (pypresence.InvalidPipe, pypresence.InvalidID, pypresence.PyPresenceException):\n err = True\nclear()\nupdate_title('Youtube Livestream View Bot | Made by 0x72')\nlogo_print()\nprint(f\"{RED} [{WHITE}YOUTUBE{RED}]{WHITE} https://github.com/robert169/\\n\")\nprint(f\"{RED} [{WHITE}1{RED}]{WHITE} Livestream View Bot\")\nprint(f\"{RED} [{WHITE}2{RED}]{WHITE} Download Proxies\")\nprint(f\"{RED} [{WHITE}3{RED}]{WHITE} Discord\")\ntry:menu_choose = int(input(f\"{RED}\\n [{WHITE}?{RED}]{WHITE} \"))\nexcept:os._exit(0)\n\n\ndef get_Session(proxies):\n api_sender = requests.session()\n prxi = proxies.split(\":\")\n if len(prxi) == 2:\n api_sender.proxies = {\"https\": proxies}\n \n return api_sender\n elif len(prxi) == 4:\n api_sender.proxies = {\"https\": f\"http://{prxi[2]}:{prxi[3]}@{prxi[0]}:{prxi[1]}\"}\n return api_sender\n else:\n api_sender = \"broken\"\n return api_sender\ndef GetProxies():\n \n file = filedialog.askopenfile(parent=root, mode='rb', title='Choose a proxy file (http/s)',\n filetype=((\"txt\", \"*.txt\"), (\"All files\", \"*.txt\")))\n if file is not None:\n try:\n loadedFile = open(file.name).readlines()\n arrange = [lines.replace(\"\\n\", \"\") for lines in loadedFile]\n except ValueError:\n try:\n loadedFilee = open(file.name, encoding=\"utf-8\", errors='ignore').readlines()\n arrange1 = [lines.replace(\"\\n\", \"\") for lines in loadedFilee]\n except ValueError:\n print(WHITE + \"Cannot open file, Unsupported encoding.\")\n else:\n return arrange1\n else:\n return arrange\n else:\n os._exit(0)\nif menu_choose == 3:discord_link = requests.get('https://robert832.me/discord').text;os.system(f'start {discord_link}');os._exit(0)\nelif menu_choose == 2:proxy_link1 = \"https://proxyscrape.com/free-proxy-list\";proxy_link2 = \"https://advanced.name/freeproxy\";os.system(f'start {proxy_link1} | start {proxy_link2}');os._exit(0)\nelif menu_choose == 1:\n clear();logo_print()\n try:\n RPC.update(large_image='logo', large_text='Made by 0x72',details='Selecting Stream ID', start=now)\n except:\n pass\n update_title('Youtube Livestream View Bot | Select Stream ID | Made by 0x72')\n print(f\"{RED}\\n [?]{WHITE} Stream ID:\", end=' ')\n id_stream = str(input('')).replace('\\n', '').replace(' ', '').strip()\n if len(id_stream) < 5:print('Invalid Stream ID');time.sleep(2);os._exit(0)\n else:pass\n try:\n RPC.update(large_image='logo', large_text='Made by 0x72',details='Selecting Threads', start=now)\n except:\n pass\n update_title('Youtube Livestream View Bot | Select Threads | Made by 0x72')\n print(f\"{RED}\\n [?]{WHITE} Threads:\", end=' ')\n try:treduri = int(input(''))\n except:print('Threads must be only int!');time.sleep(2);os._exit(0)\n try:\n RPC.update(large_image='logo',large_text='Made by 0x72', details='Selecting Proxy File', start=now)\n except:\n pass\n update_title('Youtube Livestream View Bot | Select Proxy File | Made by 0x72')\n print(f\"{RED}\\n [?]{WHITE} Select proxy file (http/s only)\")\n proxies = GetProxies()\n try:\n RPC.update(large_image='logo', large_text='Made by 0x72',details='Sending Views', start=now)\n except:\n pass\n update_title('Youtube Livestream View Bot | Sending Views | Made by 0x72')\n print(f\"{RED}\\n [*]{WHITE} Sending views (wait a few minutes to load proxies)\")\n time.sleep(2)\nelse:os._exit(0)\n\n\ndef discord_rich():\n if err == False:\n try:\n RPC.update(large_image='logo', large_text='Made by 0x72', details=f\"Views: {views}\", start=now)\n except:\n pass\n \n time.sleep(1)\n threading.Thread(target=discord_rich, args=()).start()\n\ndef ecran():\n while 1:\n update_title(f'YouTube Livestream View Bot | Views: {views} | Errors: {errors} | Made by 0x72')\n time.sleep(3)\ndef send_views():\n global views, errors\n while 1:\n try:\n sess = get_Session(random.choice(proxies))\n headers={'Host':'m.youtube.com', 'Proxy-Connection':'keep-alive', 'User-Agent':'Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1 Mobile/15E148 Safari/604.1', 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language':'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7', 'Accept-Encoding':'gzip, deflate'}\n resp = sess.get(f'https://m.youtube.com/watch?v={id_stream}', headers=headers)\n raspuns = resp.text.split('videostatsWatchtimeUrl\\\\\":{\\\\\"baseUrl\\\\\":\\\\\"')[1].split('\\\\\"}')[0].replace('\\\\\\\\u0026', '&').replace('%2C', ',').replace('\\\\/', '/')\n cl = raspuns.split('cl=')[1].split('&')[0];ei = raspuns.split('ei=')[1].split('&')[0];of = raspuns.split('of=')[1].split('&')[0];vm = raspuns.split('vm=')[1].split('&')[0]\n headers={'Host':'s.youtube.com', 'Proxy-Connection':'keep-alive', 'User-Agent':'Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1 Mobile/15E148 Safari/604.1', 'Accept':'image/png,image/svg+xml,image/*;q=0.8,video/*;q=0.8,*/*;q=0.5', 'Accept-Language':'ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3', 'Referer':f'https://m.youtube.com/watch?v={id_stream}'}\n sess.get(f'https://s.youtube.com/api/stats/watchtime?ns=yt&el=detailpage&cpn=isWmmj2C9Y2vULKF&docid={id_stream}&ver=2&cmt=7334&ei={ei}&fmt=133&fs=0&rt=1003&of={of}&euri&lact=4418&live=dvr&cl={cl}&state=playing&vm={vm}&volume=100&c=MWEB&cver=2.20200313.03.00&cplayer=UNIPLAYER&cbrand=apple&cbr=Safari%20Mobile&cbrver=12.1.15E148&cmodel=iphone&cos=iPhone&cosver=12_2&cplatform=MOBILE&delay=5&hl=ru&cr=GB&rtn=1303&afmt=140&lio=1556394045.182&idpj=&ldpj=&rti=1003&muted=0&st=7334&et=7634', headers=headers)\n views += 1;time.sleep(15)\n except:errors+=1\ntry:\n discord_rich()\n threading.Thread(target=(ecran), args=[]).start()\nexcept KeyboardInterrupt:\n print('\\nBye');time.sleep(2);os._exit(0)\nexcept Exception as e:\n input(f'Something went wrong: {e}')\n os._exit(0)\nif __name__ == \"__main__\":\n num = 0\n while 1:\n time.sleep(15)\n if num < treduri:\n num += 1\n try:threading.Thread(target=send_views).start()\n except KeyboardInterrupt:print('\\nBye');time.sleep(2);os._exit(0)\n except: pass\n","sub_path":"youtube.py","file_name":"youtube.py","file_ext":"py","file_size_in_byte":8064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"242289967","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 28 10:00:29 2017\nhttps://www.hackerrank.com/challenges/candies\n@author: Nandu\n\"\"\"\n#==============================================================================\n# #read input from file\n# inArray = [line.rstrip('\\n') for line in open('input07.txt')]\n# numberOfChildren = int(inArray[0].strip())\n# line =1\n# childrenRating = []\n# for i in range(0,numberOfChildren):\n# childrenRating.append(int(inArray[line].strip()))\n# line += 1\n#==============================================================================\n\nnumberOfChildren = int(input())\nchildrenRating = []\nfor i in range(0,numberOfChildren):\n childrenRating.append(int(input()))\n \ndecCount = 0\nchildrenCandies = [0] * numberOfChildren\n \n#initialize candy for first 2 children\nif childrenRating[1] < childrenRating[0] :\n decCount = 1\nelif childrenRating[1] > childrenRating[0]:\n childrenCandies[0] = 1\n childrenCandies[1] = 2\nelif childrenRating[1] == childrenRating[0]:\n childrenCandies[0] = 1\n childrenCandies[1] = 1\n\n#when a minimum is found we go from minimum to the peak before the minimum\n#we update each children with one more candy than the previous one\ndef updateChildrenCandies(i):\n global childrenCandies\n global childrenRating\n global decCount\n k = i-2\n childrenCandies[i-1] = 1 \n for _ in range(decCount-1):\n if(childrenRating[k] == childrenRating[k+1]):\n childrenCandies[k] = 1\n else:\n childrenCandies[k] = childrenCandies[k+1] + 1\n k -= 1\n #check if peak already has a greater value.\n #else update the peak\n if(childrenCandies[k] <= childrenCandies[k+1]):\n childrenCandies[k] = childrenCandies[k+1] + 1 \n \n\n\nfor i in range(2,numberOfChildren):\n #if decreasing increment the decreasing count\n #after reaching minimum we update candies for them\n if childrenRating[i] < childrenRating[i-1] :\n decCount += 1\n #if already reached the end of the children list, we cannot wait for increase\n if(i == numberOfChildren - 1):\n updateChildrenCandies(i+1)\n #if increasing\n elif childrenRating[i] > childrenRating[i-1]:\n #if this increase is after decrease, we crossed a minimum.\n #update the candies for minumum to the peak on the other side.\n if(decCount > 0):\n updateChildrenCandies(i)\n decCount = 0\n #update the current candy more than the previous value\n childrenCandies[i] = childrenCandies[i-1] + 1\n #if the same value as previous\n elif childrenRating[i] == childrenRating[i-1]:\n #if same value in between decreasing slope\n if(decCount>0):\n decCount += 1\n if(i == numberOfChildren - 1):\n updateChildrenCandies(i+1)\n #if same value in between increasing slope\n else:\n childrenCandies[i] = 1\n\nprint(sum(childrenCandies))\n","sub_path":"HackerRank/Algorithm/DynamicProgramming/candies/candies.py","file_name":"candies.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"142055404","text":"\n\n\n########################################################\n# Instructions:\n# 1 - Insert instance file in input_files directory\n# 2 - Run file_reader\n# 3 - Enter file name containing the extension\n########################################################\n\n\nimport os\nimport graph_instance\nimport grasp\n\n#-------------------------------------------------------\n\ndef input_path():\n file_name = raw_input(\"Enter name of instance file: \")\n load(\"input_files/\"+file_name, file_name)\n\ndef load(file_source, file_name):\n if os.path.exists(file_source):\n with open(file_source, 'r') as file_object:\n try:\n getInfos(file_object, file_name)\n return True\n except:\n print(\"Fail during algorithm run. Cancel this execution and reopen the program!\\n\")\n input_path()\n else:\n print(\"Name file not exist. Try again!\\n\")\n input_path()\n\ndef getInfos(f, file_name):\n content = [x.strip() for x in f.readlines()] # Read lines ignoring '\\n'\n first_line = content[:1]\n first_line = first_line[0].split()\n\n # Get garages, trips and garages capacities from file first line\n garages = int(first_line[0])\n capacities = []\n for g in range(garages):\n capacities.append(int(first_line[2+g]))\n trips = int(first_line[1])\n\n # Print infos\n print(\"\\nGarages(#k): \"+str(garages)+\" | Trips: \"+str(trips))\n print(\"Capacities\")\n for g in range(len(capacities)):\n print(\"K=\"+str(g)+\" : \"+str(capacities[g]))\n print(\"\\n\")\n\n table_lines = []\n for line in content:\n table_lines.append(line.split())\n\n graph_setted = graph_instance.set(table_lines)\n grasp.setParams(graph_setted, garages, capacities, trips, file_name)\n\n# -----------------\n\ninput_path()\n","sub_path":"solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"276343693","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright 2014 The BCE Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the license.txt file.\n#\n\nfrom bce.locale.lang_id import *\n\nTRANSLATION_TABLE = {\n LANG_ID_PE_HEADER: \"发生了一个解析错误 (错误代码: $1,注释:$2):\",\n LANG_ID_PE_NO_NOTE: \"没有关于此错误的详细注解。\",\n LANG_ID_PE_MEXP_UNTOKENIZABLE: \"无法将此数学表达式符号化\",\n LANG_ID_PE_MEXP_UNTOKENIZABLE_INVALID_POS: \"此处的字符无法被符号化。\",\n LANG_ID_PE_MEXP_DUPLICATED_DECIMAL_DOT: \"重复的小数点\",\n LANG_ID_PE_MEXP_DUPLICATED_DECIMAL_DOT_PREV: \"这里是前一个小数点。\",\n LANG_ID_PE_MEXP_DUPLICATED_DECIMAL_DOT_DUP: \"这里是重复的小数点。\",\n LANG_ID_PE_MEXP_PARENTHESIS_MISMATCH: \"括号不匹配\",\n LANG_ID_PE_MEXP_PARENTHESIS_MISMATCH_NO_LEFT: \"没有与此括号匹配的左括号。\",\n LANG_ID_PE_MEXP_PARENTHESIS_MISMATCH_NO_RIGHT: \"没有与此括号匹配的右括号。\",\n LANG_ID_PE_MEXP_PARENTHESIS_MISMATCH_SHOULD_BE: \"这个括号应该改为 '$1'。\",\n LANG_ID_PE_MEXP_PARENTHESIS_MISMATCH_INCORRECT: \"与此括号相匹配的那个括号是错误的。\",\n LANG_ID_PE_MEXP_MISSING_OPERATOR: \"缺少运算符\",\n LANG_ID_PE_MEXP_MISSING_OPERATOR_MUL_BEFORE: \"在这前面应该有一个乘号(*)。\",\n LANG_ID_PE_MEXP_MISSING_OPERATOR_MUL_AFTER: \"在这后面应该有一个乘号(*)。\",\n LANG_ID_PE_MEXP_MISSING_OPERAND: \"缺少操作数\",\n LANG_ID_PE_MEXP_MISSING_OPERAND_LEFT: \"缺少左操作数。\",\n LANG_ID_PE_MEXP_MISSING_OPERAND_RIGHT: \"缺少右操作数。\",\n LANG_ID_PE_MEXP_NO_CONTENT: \"无内容\",\n LANG_ID_PE_MEXP_NO_CONTENT_NOTE: \"在它们之间没有内容。\",\n LANG_ID_PE_MEXP_SEPARATOR_MISPLACED: \"误放分隔符\",\n LANG_ID_PE_MEXP_UNSUPPORTED_FUNCTION: \"不支持的函数\",\n LANG_ID_PE_MEXP_UNSUPPORTED_FUNCTION_NOTE: \"这个函数现在还没有被支持。\",\n LANG_ID_PE_MEXP_ARG_COUNT_MISMATCH: \"参数个数不匹配\",\n LANG_ID_PE_MEXP_ARG_COUNT_MISMATCH_REQB: \"该函数需要 $1 个参数,但只提供了 $2 个。\",\n LANG_ID_PE_MEXP_SEPARATOR_MISPLACED_OUT: \"分隔符只能用在括号内。\",\n LANG_ID_PE_MEXP_SEPARATOR_MISPLACED_NOT_FN: \"分隔符只能用于分隔函数参数。\",\n LANG_ID_PE_MEXP_RPNCC_DIVIDE_ZERO: \"除数为零\",\n LANG_ID_PE_MEXP_RPNCC_DOMAIN_ERROR: \"定义域错误\",\n LANG_ID_PE_MEXP_RPNCC_DOMAIN_ERROR_POW_1: \"对于运算 a ^ b,当 b < 0 时,a 不应为零。\",\n LANG_ID_PE_MEXP_RPNCC_DOMAIN_ERROR_POW_2: \"对于函数 pow(a, b),当 b < 0 时,a 不应为零。\",\n LANG_ID_PE_MEXP_RPNCC_RAISED_WHEN_DO: \"在执行此运算时发生错误。\",\n LANG_ID_PE_MEXP_RPNCC_DOMAIN_ERROR_SQRT: \"对于函数 sqrt(x),定义域必须满足 x >= 0。\",\n LANG_ID_PE_MEXP_INVALID_SYMBOL_NAME: \"无效的未知数符号\",\n LANG_ID_PE_MEXP_PROTECTED_SYMBOL_HEADER: \"'$1' 是被保留的前缀,不能使用。\",\n LANG_ID_PE_MEXP_USELESS_LEADING_ZERO: \"无用的前导零\",\n LANG_ID_PE_MEXP_USELESS_LEADING_ZERO_NOTE: \"这些前导零是无用的,需要被删除。\",\n LANG_ID_PE_ML_EPR_MEXP: \"对该数学表达式进行解释运算时发生错误。\",\n LANG_ID_PE_ML_EPR_ED: \"对该电子描述符进行解释时发生错误。\",\n LANG_ID_PE_ML_PARENTHESIS_MISMATCH: \"括号不匹配\",\n LANG_ID_PE_ML_PARENTHESIS_MISMATCH_NO_RIGHT: \"没有与此括号匹配的右括号。\",\n LANG_ID_PE_ML_PARENTHESIS_MISMATCH_NO_LEFT: \"没有与此括号匹配的左括号。\",\n LANG_ID_PE_ML_PARENTHESIS_MISMATCH_INCORRECT: \"这个括号是错误的,应该改为 '$1'.\",\n LANG_ID_PE_ML_NO_CONTENT: \"无内容\",\n LANG_ID_PE_ML_NO_CONTENT_ABBREVIATION: \"这两个表示缩写的中括号之间没有内容。\",\n LANG_ID_PE_ML_NO_CONTENT_MEXP: \"这两个表示数学表达式的大括号之间没有内容。\",\n LANG_ID_PE_ML_NO_CONTENT_PARENTHESIS: \"这两个括号之间没有内容。\",\n LANG_ID_PE_ML_NO_CONTENT_DOT: \"这两个逗点之间没有内容。\",\n LANG_ID_PE_ML_UNTOKENIZABLE: \"无法将此分子式符号化\",\n LANG_ID_PE_ML_UNTOKENIZABLE_INVALID_POS: \"此处的字符无法被符号化。\",\n LANG_ID_PE_ML_UNEXPECTED_TOKEN: \"未预料到的负号\",\n LANG_ID_PE_ML_UNEXPECTED_TOKEN_HERE: \"此处的符号是没有被预料到的,它无法被解释。\",\n LANG_ID_PE_ML_UNSUPPORTED_ABBR: \"不支持的缩写\",\n LANG_ID_PE_ML_UNSUPPORTED_ABBR_NOTE: \"这个缩写现在还没有被支持。\",\n LANG_ID_PE_ML_INVALID_SUFFIX: \"无效的后缀\",\n LANG_ID_PE_ML_INVALID_SUFFIX_NUM: \"该数应该为正整数。\",\n LANG_ID_PE_ML_INVALID_SUFFIX_MEXP: \"该数学表达式的值不应小于等于零。\",\n LANG_ID_PE_ML_INVALID_PREFIX: \"无效的前缀\",\n LANG_ID_PE_ML_INVALID_PREFIX_NUM: \"该数应该为正整数。\",\n LANG_ID_PE_ML_INVALID_PREFIX_MEXP: \"该数学表达式的值不应小于等于零。\",\n LANG_ID_PE_ML_NO_CONTENT_EXPR_MOLECULE: \"该分子内不含任何原子或电子,或者是它们已经被消去。\",\n LANG_ID_PE_ML_NO_CONTENT_EXPR_PARENTHESIS: \"这个括号内的表达式中不含任何原子或电子,或者是他们已经被消去。\",\n LANG_ID_PE_ML_NO_CONTENT_ED: \"在这两个尖括号之间没有内容。\",\n LANG_ID_PE_ML_ED_LENGTH_NOT_ENOUGH: \"长度不够\",\n LANG_ID_PE_ML_ED_LENGTH_NOT_ENOUGH_NOTE: \"电子表达式的长度至少为 2 个字符。\",\n LANG_ID_PE_ML_ED_NO_ELECTRICAL: \"无电性符号\",\n LANG_ID_PE_ML_ED_NO_ELECTRICAL_NOTE: \"在此处后面应该有符号 'e+' 或 'e-' 来描述电性。\",\n LANG_ID_PE_ML_ED_INVALID_ELECTRICAL: \"无效的电性符号\",\n LANG_ID_PE_ML_ED_INVALID_ELECTRICAL_NOTE: \"该电性符号是无效的,它应该为 'e+' 或者 'e-'。\",\n LANG_ID_PE_ML_ED_INVALID: \"无效的电子描述符\",\n LANG_ID_PE_ML_ED_INVALID_NOTE: \"该电子描述符是无效的。\",\n LANG_ID_PE_ML_USELESS_PREFIX: \"无用的前缀\",\n LANG_ID_PE_ML_USELESS_SUFFIX: \"无用的后缀\",\n LANG_ID_PE_ML_USELESS_PREFIX_NUM: \"���前缀数等于 1 时,该前缀应该忽略不写。\",\n LANG_ID_PE_ML_USELESS_PREFIX_MEXP: \"当作为前缀的数学表达式等于 1 时,该表达式应该忽略不写。\",\n LANG_ID_PE_ML_USELESS_SUFFIX_NUM: \"当后缀数等于 1 时,该前缀应该忽略不写。\",\n LANG_ID_PE_ML_USELESS_SUFFIX_MEXP: \"当作为后缀的数学表达式等于 1 时,该表达式应该忽略不写。\",\n LANG_ID_PE_ML_USELESS_LEADING_ZERO: \"无用的前导零\",\n LANG_ID_PE_ML_USELESS_LEADING_ZERO_NOTE: \"这些前导零是无用的,需要被删除。\",\n LANG_ID_PE_ML_INVALID_ATOM_COUNT: \"无效的原子个数\",\n LANG_ID_PE_ML_INVALID_ATOM_COUNT_EST: \"在此分子中,原子 '$1' 的个数为零。\",\n LANG_ID_PE_CE_PARENTHESIS_MISMATCH: \"括号不匹配\",\n LANG_ID_PE_CE_PARENTHESIS_MISMATCH_LEFT: \"没有与此括号匹配的左括号。\",\n LANG_ID_PE_CE_PARENTHESIS_MISMATCH_RIGHT: \"没有与此括号匹配的右括号。\",\n LANG_ID_PE_CE_NO_CONTENT: \"无内容\",\n LANG_ID_PE_CE_NO_CONTENT_NOTE: \"在这两个字符之间没有内容。\",\n LANG_ID_PE_CE_DUPLICATED_EQUAL: \"等号重复\",\n LANG_ID_PE_CE_DUPLICATED_EQUAL_PREV: \"这是前一个等号。\",\n LANG_ID_PE_CE_DUPLICATED_EQUAL_DUP: \"这是重复的等号。\",\n LANG_ID_PE_CE_MIXED_FORM: \"形式混杂\",\n LANG_ID_PE_CE_MIXED_FORM_NOTE: \"该表达式混合了 '正常' 形式的表达式和 '自动决策位置' 的形式。\",\n LANG_ID_PE_CE_NO_CONTENT_BEFORE: \"在此之前无内容\",\n LANG_ID_PE_CE_TOO_FEW_MOLECULES: \"分子太少\",\n LANG_ID_PE_CE_TOO_FEW_MOLECULES_ONE: \"在此表达式中只有一个分子。\",\n LANG_ID_PE_CE_NO_EQUAL: \"没有等号\",\n LANG_ID_PE_CE_NO_EQUAL_NOTE: \"在此分子中没有等号。\",\n LANG_ID_PE_CE_PARSE_MOLECULE: \"解释该分子式时发生错误\",\n LANG_ID_LE_HEADER: \"发生了一个逻辑错误 (错误代码: $1,注释:$2):\",\n LANG_ID_LE_WRONG_SIDE: \"错位\",\n LANG_ID_LE_WRONG_SIDE_LEFT: \"等号左侧的 '$1' 分子应该被放到等号右侧。\",\n LANG_ID_LE_WRONG_SIDE_RIGHT: \"等号右侧的 '$1' 分子应该被放到等号左侧。\",\n LANG_ID_LE_ALL_EST: \"全部元素都被消去\",\n LANG_ID_LE_ALL_EST_NOTE: \"所有的分子都被消去(因为经计算,它们的配平系数均为零),您可能输入了一个错误的表达式。\",\n LANG_ID_LE_NO_MOLECULE: \"无分子\",\n LANG_ID_LE_NO_MOLECULE_LEFT: \"等号左侧无分子。\",\n LANG_ID_LE_NO_MOLECULE_RIGHT: \"等号右侧无分子。\",\n LANG_ID_LE_ZERO_COEFFICIENT: \"配平系数为零\",\n LANG_ID_LE_ZERO_COEFFICIENT_NOTE: \"'$1' 分子应该被删去,因为它的配平系数为零。\",\n LANG_ID_LE_AS_MULTIPLE_ANSWER: \"'自动决策位置' 形式的表达式具有多解\",\n LANG_ID_LE_AS_MULTIPLE_ANSWER_NOTE: \"您所输入的表达式具有多解,无法决策它们应该在等号的那一边。\",\n LANG_ID_IAS_BANNER: \"BalanceCE 交互式外壳 (版本 $1.$2.$3)\\n\" +\n \"版权所有 (C) 2014 BCE 的全部作者,保留所有权利。\\n\\n\" +\n \"输入您的化学方程式或表达式并按下回车(Enter)键,或者输入 'exit' 退出程序。\\n\",\n LANG_ID_IAS_E_PYV: \"不支持的 Python 运行时的版本。\",\n LANG_ID_IAS_E_UA_FILE_NOT_FOUND: \"用户自定义缩写字典文件未被找到。\",\n LANG_ID_IAS_E_UA_NO_PERMISSION: \"无法访问用户自定义缩写字典文件。\",\n LANG_ID_IAS_E_INCORRECT_SYNTAX: \"用户自定义缩写字典文件可能包含语法错误。\",\n LANG_ID_IAS_E_IV_CH: \"表达式中存在非法字符。\",\n LANG_ID_LE_CONFLICT_EQ: \"冲突的配平结果\",\n LANG_ID_LE_CONFLICT_EQ_NOTE: \"配平结果存在冲突,您可能输入了一个错误的表达式。\",\n}\n","sub_path":"bce/locale/chinese_simplified/translation.py","file_name":"translation.py","file_ext":"py","file_size_in_byte":9904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"624549301","text":"import sublime\nimport sublime_plugin\nimport xml.etree.ElementTree as ET\nfrom io import StringIO\n\n\nclass FileWrapper:\n def __init__(self, source):\n self.source = source\n self.lineno = -1\n\n def read(self, bytes):\n self.lineno += 1\n s = self.source.readline()\n return s\n\n\nclass XPathGenerateCommand(sublime_plugin.TextCommand):\n xml_tree = None\n line_map = None\n parent_map = None\n\n def run(self, edit):\n selections = self.view.sel()\n response = \"\"\n path = self.xpath_generate(selections[0])\n if path != None:\n response = \"/\".join(path)\n sublime.set_clipboard(response)\n sublime.status_message('XPath: {0}'.format(response))\n\n def xpath_generate(self, region):\n if not self.xml_tree:\n self.line_map = {}\n xml_raw = self.view.substr(sublime.Region(0, self.view.size()))\n xml_raw_io = FileWrapper(StringIO(xml_raw))\n\n try:\n context = ET.iterparse(xml_raw_io, events=(\"start\", \"end\"))\n context = iter(context)\n event, self.xml_tree = next(context)\n\n for event, elem in context:\n if xml_raw_io.lineno not in self.line_map:\n self.line_map[xml_raw_io.lineno] = [elem]\n elif elem not in self.line_map[xml_raw_io.lineno]:\n self.line_map[xml_raw_io.lineno].append(elem)\n\n self.parent_map = dict((c, p) for p in self.xml_tree.getiterator() for c in p)\n except Exception as e:\n sublime.error_message(str(e))\n return\n\n tag = None\n if region.a > 0:\n pt_str = self.view.substr(region.a - 1)\n while region.a > 0 and pt_str != \":\" and pt_str != \"<\" and pt_str != \"/\":\n region.a -= 1\n pt_str = self.view.substr(region.a - 1)\n region.b = region.a\n pt_str = self.view.substr(region.b)\n while pt_str != \"/\" and pt_str != \">\" and pt_str != \" \" and pt_str != \"\\t\" and pt_str != \"\\n\":\n region.b += 1\n pt_str = self.view.substr(region.b)\n tag = self.view.substr(region)\n\n el = None\n candidates = self.line_map[self.view.rowcol(region.a)[0]]\n if candidates != None:\n for candidate in candidates:\n if candidate.tag == tag:\n el = candidate\n break\n\n if el != None:\n xpath = [el.tag]\n while el in self.parent_map and self.parent_map[el] in self.parent_map:\n el = self.parent_map[el]\n xpath.insert(0, el.tag)\n\n return xpath\n else:\n sublime.status_message('XPath not found')\n","sub_path":"xpath-generate.py","file_name":"xpath-generate.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"168704223","text":"def countInversion(item_container,lower_index,upper_index):\n if lower_index==upper_index:\n return 0\n middle_index=(lower_index+upper_index)//2\n left_inverion=countInversion(item_container,lower_index,middle_index)\n right_inversion=countInversion(item_container,middle_index+1,upper_index)\n split_inversion=0\n leftindex=0;rightindex=0\n left_sorted_aray=item_container[lower_index:middle_index+1]\n right_sorted_aray=item_container[middle_index+1:upper_index+1]\n \n for i in range(lower_index,upper_index+1):\n if rightindex>=len(right_sorted_aray) or (leftindex<len(left_sorted_aray) and left_sorted_aray[leftindex]<right_sorted_aray[rightindex]):\n item_container[i]=left_sorted_aray[leftindex]\n leftindex+=1\n elif leftindex>=len(left_sorted_aray) or (rightindex<len(right_sorted_aray) and right_sorted_aray[rightindex]< left_sorted_aray[leftindex]):\n item_container[i]=right_sorted_aray[rightindex]\n rightindex+=1\n split_inversion+=len(left_sorted_aray)-leftindex\n \n return left_inverion+right_inversion+split_inversion\n\nif __name__==\"__main__\":\n item=[]\n for i in range(1,100001):\n item.append(int(input()))\n print(item)\n items=[1,4,2,5,7,6,10,8]\n\n print(len(item))\n print(countInversion(item,0,len(item)-1))\n\n\n\n","sub_path":"CountInversion.py","file_name":"CountInversion.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"113038168","text":"from src.states.base_state import RobotState\nfrom src.states.exceptions import ChangingStateExcaption\n\n\nclass StateFindTakingLine(RobotState):\n def __init__(self, robot):\n super().__init__(robot)\n\n def handle(self):\n \"\"\"obrot w lewo o 90 stopni i podjechać trochę do przodu\"\"\"\n self.robot.drive_forward(500, 250)\n self.robot.rotate_right_angle_left()\n self.robot.drive_forward(750, 250)\n raise ChangingStateExcaption(\"ENTER_TAKING_LINE_FOLLOWER\")","sub_path":"src/states/find_taking_line.py","file_name":"find_taking_line.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"15499092","text":"#!/usr/bin/env python3\n\nimport math\n\ndef memoize(func):\n cache={}\n def inner(n,a,b):\n if not n in cache:\n cache[n]=func(n,a,b)\n return cache[n]\n return inner\n\ndef sieve(n):\n temp={i:True for i in range(5,n+1,6)}\n for i in range(7, n+1, 6):\n temp[i]=True\n temp[2]=True\n temp[3]=True\n for i in range(5,math.floor(math.sqrt(n))+1,6):\n if temp[i]==True:\n a=i+i\n while a<=n:\n temp[a]=False\n a+=i\n for i in range(7,math.floor(math.sqrt(n))+1,6):\n if temp[i]==True:\n a=i+i\n while a<=n:\n temp[a]=False\n a+=i\n\n return [i for i in temp if temp[i]==True],{i for i in temp if temp[i]==True}\n\n@memoize\ndef totient(n, primes, prime_dict):\n if n in prime_dict:\n return n-1\n for i in primes:\n if n%i==0:\n if (n//i)%i==0:\n return i*totient(n//i, primes, prime_dict)\n else:\n return totient(n//i, primes, prime_dict)*(i-1)\n\ndef farey_sequence(n, primes, prime_dict):\n if n==2:\n return 1\n else:\n total=1\n for i in range(3,n+1):\n total+=totient(i, primes, prime_dict)\n return total\n\ndef main(upper=10**6):\n a,b=sieve(upper)\n return farey_sequence(upper, a, b)\n","sub_path":"euler/farey_sequence.py","file_name":"farey_sequence.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"543841958","text":"from omegaconf import DictConfig\nimport pytorch_lightning as pl\nimport numpy as np\nimport torch\nimport wandb\n\nfrom simsiam.models import get_resnet\nfrom simsiam.metrics import get_accuracy\nfrom simsiam.optimizer import get_optimizer, get_scheduler\n\n\nclass SupervisedEngine(pl.LightningModule):\n\n def __init__(self, config: DictConfig):\n super().__init__()\n self.config = config\n self.resnet = get_resnet(num_classes=config.dataset.n_classes)\n self.loss_func = torch.nn.CrossEntropyLoss()\n\n self.predict_step = self.validation_step\n self.test_step = self.validation_step\n\n @property\n def lr(self):\n result = self.optimizers().param_groups[0]['lr']\n return result\n\n def forward(self, x):\n x = self.resnet(x)\n return x\n\n def training_step(self, batch, batch_idx):\n x, y = batch\n y_hat = self.resnet(x)\n loss = self.loss_func(y_hat, y[:, 0])\n\n self.log('lr', self.lr, prog_bar=True, on_step=True, logger=False) # For progress bar\n return {'loss': loss}\n\n def training_epoch_end(self, outputs: list):\n loss = torch.stack([x['loss'] for x in outputs]).mean()\n metrics = {'train/loss': loss}\n metrics.update({f'train/lr': self.lr})\n self.logger.experiment.log(metrics, step=self.current_epoch) # For wandb\n self.log_dict(metrics, prog_bar=False, on_epoch=True, on_step=False, logger=False, sync_dist=True) # For callbacks\n\n def validation_step(self, batch, batch_idx):\n x, y = batch\n f = self.resnet(x)\n return f.detach().cpu(), y.detach().cpu()\n\n def validation_epoch_end(self, outputs: list):\n self.calc_acc(outputs, 'valid')\n\n def calc_acc(self, outputs, data_split):\n y_hat, y = map(torch.cat, zip(*outputs))\n y_hat, y = np.argsort(y_hat.numpy(), axis=1)[:, ::-1], y.numpy()\n acc = dict()\n _acc = get_accuracy(y_hat, y, (1, 3, 5))\n for k, v in _acc.items():\n acc[f'{data_split}/supervised_{k}'] = v\n self.logger.experiment.log(acc, step=self.current_epoch) # For wandb\n self.log_dict(acc, prog_bar=False, on_epoch=True, on_step=False, logger=False,\n sync_dist=True) # For callbacks\n\n def configure_optimizers(self):\n training_config = self.config.training\n optimizer = get_optimizer(training_config.optimizer, self.resnet.parameters())\n if training_config.scheduler is not None:\n scheduler = get_scheduler(training_config.scheduler, optimizer)\n return [optimizer], [scheduler]\n else:\n return optimizer\n\n\n\n\n\n","sub_path":"simsiam/engine/supervised.py","file_name":"supervised.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"} +{"seq_id":"360095783","text":"input = open(\"d14_in.txt\").read()\nlines = input.split('\\n')\n\nmem = {}\ncur_mask = ''\n\nfor line in lines:\n arg = line.split(' ')\n if arg[0] == 'mask':\n cur_mask = arg[1]\n elif arg[0] == 'mem':\n location = int(arg[1])\n to_write = int(arg[2])\n to_write_bin = \"{0:b}\".format(to_write)\n while len(to_write_bin) < len(cur_mask):\n to_write_bin = '0' + to_write_bin\n actual_write = []\n for i in range(len(cur_mask)):\n if cur_mask[i] == 'X':\n actual_write.append(to_write_bin[i])\n else:\n actual_write.append(cur_mask[i])\n mem[location] = int(''.join(actual_write),2)\n\nans = 0\nfor key in mem:\n ans += mem[key]\n\nprint(ans)","sub_path":"2020/Day 14/d14p1.py","file_name":"d14p1.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"52"}