diff --git "a/4215.jsonl" "b/4215.jsonl" new file mode 100644--- /dev/null +++ "b/4215.jsonl" @@ -0,0 +1,651 @@ +{"seq_id":"462225516","text":"# -*- coding: utf-8 -*-\n# Create your views here.\nfrom django.shortcuts import render,redirect\nfrom macrocalc.models import *\nfrom datetime import *\nfrom forms import *\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import auth\nfrom django.http import HttpResponse\nimport json\n\n\ndef home(request):\n ##CAMBIAR!!!!\n if not request.user.is_authenticated():\n return redirect('/')\n\n today_min = datetime.combine(date.today(), time.min)\n today_max = datetime.combine(date.today(), time.max) \n\n #Hay alguna dieta empezada hoy?\n d = Day.objects.filter(date__range=(today_min, today_max),user=request.user.username)\n\n #si no, crear una nueva\n if not d:\n dieta = Diet.objects.filter(user=request.user.username)\n if not dieta:\n dieta = Diet(user=request.user.username,dietName=\"dummy\",calories=0,proteins=0,carbs=0,fats=0)\n dieta.save()\n dieta = Diet.objects.get(dietName=\"dummy\")\n d = Day(user=request.user.username,diet=dieta,date=date.today())\n else:\n d = Day(user=request.user.username,diet=dieta[0],date=date.today())\n\n d.save()\n\n if request.GET.get('welcome'):\n return render(request,'menu.html', {'section': \"Inicio\",'welcome':True})\n else:\n return render(request,'menu.html', {'section': \"Inicio\"})\n\n\ndef newItem(request):\n if not request.user.is_authenticated():\n return redirect('/')\n\n if request.method == 'POST':\n form = newItemForm(request.POST)\n if form.is_valid(): \n try:\n alimento = Food.objects.get(name=request.POST['name'])\n except Food.DoesNotExist:\n aux = Food(user=request.user.username,name=request.POST['name'],quantity=float(request.POST['quantity']),unit=request.POST['unit'],proteins=float(request.POST['proteins']),carbs=float(request.POST['carbs']),fat=float(request.POST['fat']),calories=float(request.POST['calories']))\n aux.save()\n return render(request,'newItem.html', {'section': \"Nuevo Alimento\",'itemSaved':True})\n else:\n return render(request,'dialogo.html', {'titulo':\"Error\",'mensaje':\"Ese alimento ya existe. Utilice otro nombre.\"})\n else:\n form = newItemForm()\n\n return render(request,'newItem.html', {'section': \"Nuevo alimento\",'form': form,'itemSaved':False})\n\ndef infoAlimento(request):\n if not request.user.is_authenticated():\n return redirect('/')\n \n if \"name\" in request.GET:\n alimento = Food.objects.get(name=request.GET['name'])\n else:\n return redirect('/listarAlimentos/') \n\n return render(request,'infoAlimento.html', {'section': \"Información alimento\",'alimento': alimento})\n\ndef listItem(request):\n if not request.user.is_authenticated():\n return redirect('/')\n\n names = Food.objects.filter(user=request.user.username).values('name').order_by('name')\n return render(request,'listItem.html', {'section': \"Alimentos\",'names':names})\n\n\ndef addItem(request):\n if not request.user.is_authenticated():\n return redirect('/') \n\n if request.method == 'POST':\n if \"name\" in request.POST and \"cantidad\" in request.POST and \"unidades\" in request.POST:\n today_min = datetime.combine(date.today(), time.min)\n today_max = datetime.combine(date.today(), time.max)\n try:\n f = Food.objects.get(user=request.user.username,name=request.POST[\"name\"])\n except Food.DoesNotExist:\n return HttpResponse('Error al añadir el alimento')\n \n aux = FoodCountItem(user = request.user.username, date= datetime.today(),food = f ,quantity = request.POST[\"cantidad\"],unit = request.POST[\"unidades\"])\n aux.save()\n return HttpResponse('Alimento añadido')\n \n else:\n return HttpResponse('Error al añadir el alimento')\n \n \n return HttpResponse(\" \")\n\ndef deleteItem(request):\n if not request.user.is_authenticated():\n return redirect('/') \n\n if request.method == 'POST':\n\n if \"name\" in request.POST and \"quantity\" in request.POST and \"units\" in request.POST:\n today_min = datetime.combine(date.today(), time.min)\n today_max = datetime.combine(date.today(), time.max)\n try:\n food = Food.objects.filter(user=request.user.username,name=request.POST[\"name\"])\n food = food[0]\n f = FoodCountItem.objects.filter(food=food,date__range=(today_min, today_max),quantity=request.POST[\"quantity\"],unit=request.POST[\"units\"])\n\n except Food.DoesNotExist:\n return HttpResponse('Error1')\n\n f[0].delete()\n\n foodList = FoodCountItem.objects.filter(user=request.user.username,date__range=(today_min, today_max)).prefetch_related('food') \n\n totals = [0.0,0.0,0.0,0.0]\n\n for i in foodList:\n totals[0] += i.food.proteins\n totals[1] += i.food.carbs\n totals[2] += i.food.fat\n totals[3] += i.food.calories\n\n res = {}\n res['proteins']=totals[0]\n res['carbs']=totals[1]\n res['fat']=totals[2]\n res['calories']=totals[3]\n\n return HttpResponse(json.dumps(res), content_type=\"application/json\")\n \n else:\n return HttpResponse('Error2')\n \n return HttpResponse('Error3')\n\ndef count(request):\n if not request.user.is_authenticated():\n return redirect('/')\n\n #Obtengo el Day del usuario, que contiene una referencia a su count\n #Con ese count, cojo todos los objetos objectCount\n\n\n today_min = datetime.combine(date.today(), time.min)\n today_max = datetime.combine(date.today(), time.max)\n\n foodList = FoodCountItem.objects.filter(user=request.user.username,date__range=(today_min, today_max)).prefetch_related('food') \n\n totals = [0.0,0.0,0.0,0.0]\n\n for i in foodList:\n totals[0] += i.food.proteins\n totals[1] += i.food.carbs\n totals[2] += i.food.fat\n totals[3] += i.food.calories\n\n max={}\n\n diet = Day.objects.get(user=request.user.username,date__range=(today_min, today_max)).diet\n\n if diet:\n max['Prot']=diet.proteins\n max['Carbs']=diet.carbs\n max['Fat']=diet.fats\n max['Cal']=diet.calories\n else:\n max['Prot']=0\n max['Carbs']=0\n max['Fat']=0\n max['Cal']=0\n\n return render(request,'count.html', {'section': \"Contador\",'foodList':foodList,'totals':totals,'max':max})\n\n\n\ndef dieta(request):\n if not request.user.is_authenticated():\n return redirect('/')\n\n dietas = Diet.objects.filter(user=request.user.username) \n\n out = []\n\n for d in dietas:\n if d.dietName != \"dummy\":\n out.append(d)\n\n return render(request,'dietas.html', {'section': \"Dieta\",'diets':out})\n\n\ndef addDiet(request):\n if not request.user.is_authenticated():\n return redirect('/') \n\n if request.method == 'POST':\n\n if \"n\" in request.POST and \"p\" in request.POST and \"c\" in request.POST and \"f\" in request.POST and \"cals\" in request.POST:\n\n n=request.POST[\"n\"]\n p=float(request.POST[\"p\"])\n c=float(request.POST[\"c\"])\n f=float(request.POST[\"f\"])\n cals=float(request.POST[\"cals\"])\n\n d = Diet(user=request.user.username,dietName=n,proteins=p,carbs=c,fats=f,calories=cals)\n d.save();\n\n return HttpResponse(\"Done\");\n \n else:\n return HttpResponse('Error')\n \n return HttpResponse('Error')","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"45216301","text":"\"\"\"\r\nModule de couleurs répertoriant quelques constantes de couleurs RGB/RVB\r\nainsi que des fonctions simple manipulant ces couleurs RGB/RVB\r\n\"\"\"\r\n# --coding:utf-8--\r\n\r\n######################### CONSTANTE DE COULEURS RGB #########################\r\n\r\nROUGE = (255, 0, 0)\r\nVERT = ( 0,255, 0)\r\nBLEU = ( 0, 0,255)\r\nNOIR = ( 0, 0, 0)\r\nBLANC = (255,255,255)\r\nJAUNE = (255,255, 0)\r\nVIOLET = (100, 0,100)\nVERT_FONCE = ( 0,100, 0)\r\nORANGE = (255,200, 0)\r\nROSE = (255,192,203)\r\nBEIGE = (199,175,138)\r\n\r\n\r\n################# FONCTIONS SIMPLE MANIPULANT DES COULEURS ##################\r\n\r\ninverser = lambda couleur : tuple([ 255-c for c in couleur ])\r\n","sub_path":"Morpion/couleurs.py","file_name":"couleurs.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"308524834","text":"import pandas as pd\nfile1 = \"/home/davidyu/stock/data/test/fin_report_index_cnt.csv\"\ndf1 = pd.read_csv(file1)\ndf1.columns = [x.split(\".\")[1] for x in df1.columns.tolist()]\ndf2 = df1.T.reset_index()\ndf2.columns = [\"index\",\"cnt\"]\n\n\nhigh_index = df2[df2[\"cnt\"]>50]\nindex_out = [x.split(\"_\")[0] for x in high_index[\"index\"].tolist() ]\nprint(index_out)\n\n","sub_path":"scripts/analysis/fin_report/v2/f1.py","file_name":"f1.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"90844037","text":"from urllib import urlopen\n\nf = urlopen(\"http://regina.kb.se/sou/\")\nlines = f.readlines()\n\nfor i in range(len(lines)-1):\n if not \"urn:nbn:se:kb:sou\" in lines[i]:\n continue\n parts = lines[i].split(\"\\\"\")\n if \"div\" in parts[0]:\n url = parts[1]\n else:\n url = parts[2]\n data = lines[i+1].split(\"\\\"\")[1].replace(\"<\",\">\").split(\">\")\n sou = data[1]\n title = data[3].strip()\n try:\n tf = urlopen(url)\n temp = tf.read()\n except:\n continue\n pdfurl = \"\"\n for t in temp.split(\"\\\"\"):\n if \".pdf\" in t:\n pdfurl = t\n break\nprint(\"wget -O \\\"\" + title + \" - SOU \"+ sou + \".pdf\\\" \"+pdfurl)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"213350798","text":"import operator\n\nimport pymongo\nimport numpy as np\nfrom itertools import islice\nfrom pymongo import MongoClient\nfrom statsmodels.tsa.ar_model import AR\n\n\nclass Database():\n client = MongoClient('mongodb://dbuser1:dbuser1dbuser1@localhost:27200/space_exploration')\n\n confirmed_planets_collection = client.space_exploration.confirmed_planets\n observatories_collection = client.space_exploration.observatories\n\n def getAllObservatories(self):\n return self.confirmed_planets_collection.find()\n\n def get_disc_years(self, pl_locale):\n return self.confirmed_planets_collection.aggregate(\n [\n {\n \"$match\": {\n \"pl_locale\": pl_locale\n }\n },\n {\n \"$group\" : {\n \"_id\" : \"$pl_disc\",\n \"count\": { \"$sum\": 1 }\n }\n },\n {\n \"$sort\": {\n \"_id\": 1\n }\n }\n ]\n )\n\n # returns Cursor object of discovery methods of planets which controversial flag == pl_controvflag\n def get_contr_methods(self, pl_controvflag):\n return self.confirmed_planets_collection.aggregate(\n [\n {\n \"$match\": {\n \"pl_controvflag\": pl_controvflag\n }\n },\n {\n \"$group\" : {\n \"_id\" : \"$pl_discmethod\",\n \"count\": { \"$sum\": 1 }\n }\n },\n {\n \"$sort\": {\n \"_id\": 1\n }\n }\n ]\n )\n\n def get_discovery_methods(self):\n return self.confirmed_planets_collection.aggregate(\n [\n {\n \"$group\" : {\n \"_id\" : \"$pl_discmethod\",\n \"count\": { \"$sum\": 1 }\n }\n },\n {\n \"$sort\": {\n \"_id\": 1\n }\n }\n ]\n )\n\n def get_discovery_accuracy_stat(self, pl_controvflag):\n controv_methods = self.get_contr_methods(pl_controvflag)\n all_methods = self.get_discovery_methods()\n\n #method_stats = np.array([])\n #method_counts = np.array([])\n # method_names = np.array([])\n #for obj in controv_methods:\n #method_stats = np.append(method_stats, [obj[\"_id\"], obj[\"count\"]], dtype=[('name', 'U50'), ('quantity', 'i4')])\n #print(method_stats)\n\n flagged_methods_dict = {}\n for obj in controv_methods:\n flagged_methods_dict[obj[\"_id\"]] = obj[\"count\"]\n\n general_methods_dict = {}\n for obj in all_methods:\n general_methods_dict[obj[\"_id\"]] = obj[\"count\"]\n\n for key, value in general_methods_dict.items():\n if key in flagged_methods_dict:\n general_methods_dict[key] = 100 * (flagged_methods_dict[key] / value)\n else:\n general_methods_dict[key] = 0.0\n\n\n names = ['name', 'accuracy']\n formats = ['U50', 'f8']\n dtype = dict(names=names, formats=formats)\n np_result = np.array(list(general_methods_dict.items()), dtype=dtype)\n\n return(np_result)\n\n def get_discovery_stat(self, pl_locale):\n data = self.get_disc_years(pl_locale)\n\n list_counts = list()\n years = list()\n for obj in data:\n years.append(obj[\"_id\"])\n list_counts.append(obj[\"count\"])\n\n\n return {\"years\": years, \"counts\": list_counts}\n\n def get_top_facilities_id(self, quantity):\n\n res = self.confirmed_planets_collection.aggregate([{\n \"$group\": {\"_id\": \"$pl_facility_id\", \"count\": {\"$sum\": 1}}\n }, {\n \"$sort\": {\"count\": -1}\n }, {\n \"$limit\": quantity\n }])\n\n return list(res)\n\n def get_top_facilities_by_id_array(self, id_array):\n names_array = []\n for facility in id_array:\n names_array.append((self.get_facility_by_id(facility[\"_id\"]))[\"name\"].split('\\n')[0])\n\n facilities_array = dict.fromkeys(names_array, 0)\n\n for facility_desc in id_array:\n facility = self.get_facility_by_id(facility_desc[\"_id\"])\n facilities_array[str(facility[\"name\"].split(',')[-1])] += int(facility_desc[\"count\"])\n\n sorted_facilities = sorted(facilities_array.items(), key=operator.itemgetter(1), reverse=True)\n\n return np.array(sorted_facilities[:], dtype=[('name', 'U50'), ('quantity', 'i4')])\n\n\n def get_top_locations_by_id_array(self, id_array):\n\n country_names_list = []\n\n for facility in id_array:\n facility = self.get_facility_by_id(facility[\"_id\"])\n name = facility[\"location\"].split(',')[-1]\n if str(name) not in country_names_list:\n country_names_list.append(name)\n\n country_array = dict.fromkeys(country_names_list, 0)\n\n for facility_desc in id_array:\n facility = self.get_facility_by_id(facility_desc[\"_id\"])\n country_array[str(facility[\"location\"].split(',')[-1])] += int(facility_desc[\"count\"])\n\n # sort locations\n sorted_locations = sorted(country_array.items(), key=operator.itemgetter(1), reverse=True)\n\n # returns numpy array\n\n return np.array(sorted_locations[:], dtype=[('name', 'U50'), ('quantity', 'i4')])\n\n\n def get_facility_by_id(self, id):\n return self.observatories_collection.find_one({\"_id\": id})\n\n def get_facility_quantity_by_id(self, id):\n return self.confirmed_planets_collection.find({\"pl_facility_id\": id}).count()\n\n def get_facility_quantities_from_array(self, id_array):\n quantities = []\n for id in id_array:\n quantities.append(self.get_facility_quantity_by_id(id))\n\n return quantities\n\n # returns list of locations grouped by pl_locale\n # input: id_array - array of ids of discovering facilities\n # output: list of grouped by pl_locale planets\n def get_locations_by_discovery_array(self, id_array):\n\n country_names_list = []\n\n for facility in id_array:\n facility = self.get_facility_by_id(facility[\"_id\"])\n name = facility[\"location\"].split(',')[-1]\n if str(name) not in country_names_list:\n country_names_list.append(name)\n\n country_array = dict.fromkeys(country_names_list, 0)\n\n for facility_desc in id_array:\n facility = self.get_facility_by_id(facility_desc[\"_id\"])\n country_array[str(facility[\"location\"].split(',')[-1])] += int(facility_desc[\"count\"])\n\n return sorted(country_array.items(), key=operator.itemgetter(1), reverse=True)\n\n\n # returns list of facilities ids by pl_locale\n # input: pl_locale (possibles are: Ground and Space)\n # output: list of grouped by pl_locale planets id's\n def get_facilities_id_by_discovery_method(self, pl_locale):\n\n self.confirmed_planets_collection.create_index([('pl_locale', pymongo.TEXT)], name='search_index', default_language='english')\n\n res = self.confirmed_planets_collection.aggregate([\n {\"$match\": { \"$text\": { \"$search\": pl_locale}}},\n {\"$group\": {\"_id\": \"$pl_facility_id\", \"count\": {\"$sum\": 1}}},\n {\"$sort\": {\"count\": -1}}\n ])\n\n return list(res)\n\n def get_array_with_percents(self, locations):\n\n return locations['quantity'][0:] * 100 / locations['quantity'][0:].sum()\n\n # returns dictionary with top of locations by percent\n # of discovered planets among all discovered planets\n # input: locations quantity\n # output: dictionary with country name as a key and quantity\n # of discovered planets as a value\n def get_top_locations_by_percentage(self, quantity):\n ids = self.get_top_facilities_id(quantity)\n locations = self.get_top_locations_by_id_array(ids)\n percents_array = self.get_array_with_percents(locations)\n return {\"x\": locations['name'], \"y\": percents_array}\n\n # returns dictionary with top of locations by quantity of discovered planets\n # input: locations quantity\n # output: dictionary with country name as a key and quantity\n # of discovered planets as a value\n def get_top_locations(self, quantity):\n\n ids = self.get_top_facilities_id(quantity)\n locations = self.get_top_locations_by_id_array(ids)\n\n return {\"x\": locations['name'], \"y\": locations['quantity']}\n\n # returns top of facilities by quantity of discovered planets\n # input: facilities quantity\n # output: list with \"name\" and \"count\" parameters in objects\n def get_top_facilities(self, quantity):\n\n ids = self.get_top_facilities_id(quantity)\n facilities = self.get_top_facilities_by_id_array(ids)\n\n return {\"x\": facilities['name'], \"y\": facilities['quantity']}\n\n # returns list of locations grouped by pl_locale\n # input: id_array - array of ids of discovering facilities;\n # quantity - quantity of top needed locations\n # output: list of grouped by pl_locale planets\n def getLocationsByPlLocale(self, pl_locale, quantity):\n ids = self.get_facilities_id_by_discovery_method(pl_locale)\n return list(islice(self.get_top_locations_by_id_array(ids), quantity))\n\n def predict_f_discovered_planets_quantity(self):\n\n stat = self.get_discovery_stat(\"Ground\")[\"counts\"]\n # fit model\n model = AR(stat)\n model_fit = model.fit()\n # make prediction\n yhat = model_fit.predict(len(stat), len(stat))\n return yhat\n\n\n\n\n\n","sub_path":"course_3/term_2/db_course_work/db_operations.py","file_name":"db_operations.py","file_ext":"py","file_size_in_byte":9735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"144264404","text":"from django.db import models\n\n\nclass Book(models.Model):\n name = models.CharField(\n verbose_name='書籍名',\n max_length=100,\n )\n published_date = models.IntegerField(\n verbose_name='出版日',\n default=20180101,\n )\n\n def __str__(self):\n return self.name\n","sub_path":"books/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"296311913","text":"import doctest\nimport unittest2 as unittest\n\n#from zope.testing import doctestunit\n#from zope.component import testing\nfrom Testing import ZopeTestCase as ztc\nimport base\n\ndef test_suite():\n\n TEST_CLASS = base.FunctionalTestCase\n OPTIONFLAGS = (doctest.REPORT_ONLY_FIRST_FAILURE |\n doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS)\n return unittest.TestSuite([\n\n ztc.ZopeDocFileSuite(\n 'topic.txt',package='collective.gallery',\n test_class=TEST_CLASS,\n optionflags=OPTIONFLAGS\n ),\n\n ztc.FunctionalDocFileSuite(\n 'folder.txt', package='collective.gallery',\n test_class=TEST_CLASS,\n optionflags=OPTIONFLAGS),\n\n ztc.FunctionalDocFileSuite(\n 'link/link.txt', package='collective.gallery',\n test_class=TEST_CLASS,\n optionflags=OPTIONFLAGS),\n\n ])\n","sub_path":"collective/gallery/tests/test_functional.py","file_name":"test_functional.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"377193233","text":"# Copyright 2016 TransCirrus 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 os\n\nimport charmhelpers.contrib.openstack.utils as ch_utils\n\nimport charms_openstack.charm\nimport charms_openstack.adapters\nimport charms_openstack.ip as os_ip\n\nTROVE_DIR = '/etc/trove'\nTROVE_CONF = os.path.join(TROVE_DIR, 'trove.conf')\n\n\nclass TroveAdapters(charms_openstack.adapters.OpenStackAPIRelationAdapters):\n \"\"\"\n Adapters class for the Trove charm.\n \"\"\"\n def __init__(self, relations):\n super(TroveAdapters, self).__init__(\n relations,\n options_instance=charms_openstack.adapters.APIConfigurationAdapter(\n port_map=TroveCharm.api_ports))\n\n\nclass TroveCharm(charms_openstack.charm.HAOpenStackCharm):\n\n # Internal name of charm + keystone endpoint\n service_name = name = 'trove'\n\n # First release supported\n release = 'mitaka'\n\n # Packages the service needs installed\n packages = ['python-trove', 'python-troveclient',\n 'trove-api', 'trove-common',\n 'trove-taskmanager','trove-conductor']\n\n # Init services the charm manages\n services = ['trove-api', 'trove-taskmanager','trove-conductor']\n\n # Standard interface adapters class to use.\n adapters_class = charms_openstack.adapters.OpenStackRelationAdapters\n\n # Ports that need exposing.\n default_service = 'trove-api'\n api_ports = {\n 'trove-api': {\n os_ip.PUBLIC: 8779,\n os_ip.ADMIN: 8779,\n os_ip.INTERNAL: 8779,\n }\n }\n\n # Database sync command used to initalise the schema.\n sync_cmd = ['trove-manage db_sync']\n\n # The restart map defines which services should be restarted when a given\n # file changes\n restart_map = {\n TROVE_CONF: services,\n }\n\n # Resource when in HA mode\n ha_resources = ['vips', 'haproxy']\n\n # Trove requires a message queue, database, glance, cinder, swift, nova\n # and keystone to work, so these are the 'required' relationships for the\n # service to have an 'active' workload status. 'required_relations' is used in\n # the assess_status() functionality to determine what the current\n # workload status of the charm is.\n required_relations = ['amqp', 'shared-db', 'identity-service', 'image-service', 'cloud-compute']\n\n # Set the adapters class to on specific to Trove\n adapters_class = TroveAdapters\n\n def __init__(self, release=None, **kwargs):\n \"\"\"Custom initialiser for class\n If no release is passed, then the charm determines the release from the\n ch_utils.os_release() function.\n \"\"\"\n if release is None:\n release = ch_utils.os_release('python-keystonemiddleware')\n super(TroveCharm, self).__init__(release=release, **kwargs)\n\n def install(self):\n \"\"\"Customise the installation, configure the source and then call the\n parent install() method to install the packages\n \"\"\"\n self.configure_source()\n # and do the actual install\n super(TroveCharm, self).install()\n\n\ndef install():\n \"\"\"Use the singleton from the AodhCharm to install the packages on the\n unit\n \"\"\"\n TroveCharm.singleton.install()\n\n\ndef restart_all():\n \"\"\"Use the singleton from the AodhCharm to restart services on the\n unit\n \"\"\"\n TroveCharm.singleton.restart_all()\n\n\ndef db_sync():\n \"\"\"Use the singleton from the AodhCharm to run db migration\n \"\"\"\n TroveCharm.singleton.db_sync()\n\n\ndef setup_endpoint(keystone):\n \"\"\"When the keystone interface connects, register this unit in the keystone\n catalogue.\n \"\"\"\n charm = TroveCharm.singleton\n keystone.register_endpoints(charm.service_name,\n charm.region,\n charm.public_url,\n charm.internal_url,\n charm.admin_url)\n\n\ndef render_configs(interfaces_list):\n \"\"\"Using a list of interfaces, render the configs and, if they have\n changes, restart the services on the unit.\n \"\"\"\n TroveCharm.singleton.render_with_interfaces(interfaces_list)\n\n\ndef assess_status():\n \"\"\"Just call the AodhCharm.singleton.assess_status() command to update\n status on the unit.\n \"\"\"\n TroveCharm.singleton.assess_status()\n\n\ndef configure_ha_resources(hacluster):\n \"\"\"Use the singleton from the AodhCharm to run configure_ha_resources\n \"\"\"\n TroveCharm.singleton.configure_ha_resources(hacluster)\n","sub_path":"charms/Trove/lib/charm/openstack/trove.py","file_name":"trove.py","file_ext":"py","file_size_in_byte":4982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"157508036","text":"from utilities import filter_out_write_line_pattern, \\\n split_the_data_in_write_line_pattern, \\\n merge_all_files_within_a_directory, delete_directory_contents\n\n__author__ = 'gpamfilis'\n\n\nclass CleanUpRawData:\n \"\"\"\n \"\"\"\n\n @staticmethod\n def main():\n delete_directory_contents()\n filter_out_write_line_pattern(location_of_file='data/raw')\n split_the_data_in_write_line_pattern(location_of_data_to_be_processed='data/raw')\n merge_all_files_within_a_directory(path_to_raw_data_files='data/raw',\n location_to_save_merged_raw_data='data/training/raw_data_merged.txt',\n delete_originals=False)\n\nif __name__ == '__main__':\n CleanUpRawData().main()\n","sub_path":"cleanup_raw_data.py","file_name":"cleanup_raw_data.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"652281372","text":"'''\nCreated on Feb 24, 2012\n\n@author: zimp\n'''\n\nfrom PyQt4 import QtGui, QtCore\nfrom PyQt4.QtCore import QSize\n\nclass InfoWidget(QtGui.QWidget):\n '''\n Handles the display of information passed to it about the current status of\n the fitting of shapes in a Frame object. \n '''\n\n\n def __init__(self):\n '''\n Initialize an instance calling self.init_ui to add necessary widgets to\n layout.\n '''\n super(InfoWidget, self).__init__()\n self.init_ui()\n \n def init_ui(self):\n '''\n Helper function for __init__. Creates QLabels for showing the\n information passed to self.\n '''\n self.pelabel = QtGui.QLabel()\n self.pelabel.setText(\"Packing efficiency: 0%\")\n\n self.fittednumlabel = QtGui.QLabel()\n self.fittednumlabel.setText(\"Fitted shapes: 0\")\n\n self.availnumlabel = QtGui.QLabel()\n self.availnumlabel.setText(\"Available shapes: 0\")\n\n vbox1 = QtGui.QVBoxLayout()\n vbox1.addWidget(self.pelabel)\n vbox1.addStretch(0)\n\n vbox2 = QtGui.QVBoxLayout()\n vbox2.addWidget(self.fittednumlabel)\n vbox2.addWidget(self.availnumlabel)\n vbox2.addStretch(0)\n\n hbox = QtGui.QHBoxLayout()\n hbox.addLayout(vbox1)\n hbox.addLayout(vbox2)\n hbox.addStretch(1)\n\n self.setLayout(hbox)\n \n def refresh(self, packing_efficiency, num_fitted, num_available):\n '''\n Updates the QLabels with the information received.\n\n @param packing_efficiency: packing efficiency displayed in self.pelabel\n @type packing_efficiency: number\n @param num_fitted: number of fitted items displayed in\n self.fittednumlabel\n @type num_fitted: number\n @param num_available: number of available shapes displayed in\n self.availnumlabel\n @type num_available: number\n '''\n self.pelabel.setText(\n \"Packing efficiency: {:.2%}\".format(packing_efficiency))\n self.fittednumlabel.setText(\n \"Fitted shapes: {0}\".format(num_fitted))\n self.availnumlabel.setText(\n \"Available shapes: {0}\".format(num_available))\n","sub_path":"src/infowidget.py","file_name":"infowidget.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"547276143","text":"# import locale as __locale\n#\n# if 'es' in __locale.getdefaultlocale()[0]:\n# from spanish_messages import *\n# # from spanish_messages import *\n# #from english_message import *\n# else:\n# from english_message import *\n \n# BROWSERS\nCHROME = 'chrome'\nCHROME_P = 'chrome_p'\nFIREFOX = 'firefox'\nFIREFOX_P = 'firefox_p'\n \n# CHROME PROPERTIES\nIGNORE_CERTIFICATE = '--ignore-certificate-errors'\n\n# FIREFOX PROPERTIES\nSAFEBROWSING = \"browser.safebrowsing.malware.enabled\"\nAUTOLOGIN = \"signon.autologin.proxy\"\nTRUSTED_URIS = 'trusted-uris'\nNEGOTIATE = 'negotiate-auth'\nN_TRUSTED_URIS = 'network.{}.{}'.format(NEGOTIATE, TRUSTED_URIS)\nAUTOMATIC_NTLM = \"network.automatic-ntlm-auth.{}\".format(TRUSTED_URIS)\nN_DELEGATION = \"network.{}.delegation-uris\".format(NEGOTIATE)\nDOMAIN = \".sis.ad.bia.itau\"\nPROXY = \"proxyserver.sis.ad.bia.itau:80\"\nBINARY = 'C:\\\\ITAU_Tools\\\\QA_Automation\\Mozilla\\\\firefox.exe'\n \n# JS\nSCROLL = \"arguments[0].scrollIntoView();\"\nSET_ATTRIBUTE = \"arguments[0].setAttribute('style', arguments[1])\"\nCLICK = \"arguments[0].click();\"\nNEW_TAB = 'window.open(\"{}\")'\nBACK = 'window.history.go(-1)'\n\nBORDER = \"border: 4px solid red\"\nSTYLE = 'style'\n\n# WEBELEMENT ATTRIBUTE\nARIA_OWNS = 'aria-owns'\nTAG_LI = 'li'\n\n# PATH\nPNG = 'PNG'\nLOG_PATH = '{}\\{}.log'\nPNG_FILE = '{}.png'\n\n# ECXEL DATOS\n\nCRM_DATA_PATH = 'C:\\ITAU_Tools\\QA_Automation\\workspace\\Fram27\\src\\proyectos\\CRM\\Data\\Data_CRM.xlsx'\nCRM_DATA_TEST_FUNC_SHEET = 'DataTestFunc'","sub_path":"src/utils/constants/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"607609800","text":"#!/usr/bin/python3\n\nfrom flask import Flask, request, redirect, render_template, jsonify\nfrom telegram import Telegram\nimport os,json,datetime,subprocess,time\n\napp = Flask(__name__)\ndownload_path = \"{}/Downloads/\".format(os.getcwd())\n\ndef append_to_downloads(data):\n # append the argument to Downloads/downloads.json file\n downloads_json_file = json.loads(open(download_path+\"/downloads.json\",\"r\").read())\n downloads_json_file.append(data)\n downloads_json_file = json.dumps(downloads_json_file,sort_keys=True, indent=4)\n open(download_path + \"/downloads.json\",\"w\").write(downloads_json_file)\n\n@app.route(\"/\",methods=[\"GET\"])\ndef index():\n size = subprocess.check_output(['du','-sh', download_path]).split()[0].decode('utf-8')\n return render_template(\"index.html\",dir_size = size)\n\n@app.route(\"/monitor\",methods=[\"GET\"])\ndef monitor():\n return render_template(\"monitor.html\")\n\n@app.route(\"/api/download\",methods=[\"POST\"])\ndef api_download():\n # starting the download\n link = request.form[\"linkInput\"]\n wget_cmd = \"wget {} -o wget.log\".format(link)\n folder_name = link.split(\"/\")[-1]\n\n now = datetime.datetime.now()\n current_date_time = str(now).split(\" \")[0] + \" \" + str(now.hour) + \":\" + str(now.minute) + \":\" + str(now.second)\n try:\n os.mkdir(download_path+\"/\"+folder_name)\n os.system(\"cd {} && {} &\".format(download_path + \"/\" + folder_name,wget_cmd))\n append_to_downloads({'time':current_date_time,'link':link,'folder':folder_name})\n \n except OSError:\n print(\"\")\n return redirect(\"/\")\n\n@app.route(\"/api/monitor\",methods=[\"GET\"])\ndef api_monitor():\n # read the Downloads/downloads.json and append the wget.log of every folder and\n # return that json\n downloads_data = json.loads(open(download_path+\"/downloads.json\",\"r\").read())\n for i in downloads_data:\n i[\"wget_log\"] = open(download_path+\"/\"+i[\"folder\"]+\"/wget.log\",\"r\").read()\n return jsonify(downloads_data)\n\n\nif __name__ == \"__main__\":\n time.sleep(5) # some time for ngrok to start\n\n # Token of DownloadGatorBot (@downloadgator_bot) on Telegram\n bot_token = \"580264852:AAHd6JUBxjj6iDoYMH8GN95bwZkZ3A7Byvw\"\n \n #Enter your user id on Telegram, its an integer, you can get it from @get_id_bot\n user_id = 000000 # put your id here\n \n telegram_bot = Telegram(bot_token,user_id) #instantiating the bot\n \n # sending the message to the user that the server was started on this ngrok url\n telegram_bot.sendServerStartedMessage()\n \n app.run(host=\"0.0.0.0\",port=3000)\n\n telegram_bot.sendServerStoppedMessage()\n raise SystemExit\n ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"561438990","text":"# Python Script for running Sentiment Analysis using NLP (Natural Language Processing)\r\n\r\n# Importing all the libraries\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nimport nltk\r\nimport re\r\nimport csv\r\nfrom tqdm import tqdm\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem.porter import PorterStemmer\r\nfrom sklearn.externals import joblib\r\nimport matplotlib.pyplot as plt\r\n\r\n# Taking CSV from user\r\ncsv_file_name = input(\"Enter the name of the dataset : \")\r\ncsv_file_name = csv_file_name + \".csv\"\r\n\r\ndata = pd.read_csv(csv_file_name)\r\nprint(data.head(1))\r\n# score = input(\"Enter the name of attribute containing the 'Scores' : \")\r\ntext = input(\"Enter the name of the attribute containing the 'Reviews' : \")\r\nrows = int(input(\"Enter the number of rows for processing : \"))\r\ndata = pd.read_csv(csv_file_name, nrows = rows, usecols = [text])\r\ndf = pd.DataFrame(data)\r\n\r\n# cleaning the texts\r\ncorpus = []\r\n\r\nfor i in tqdm(range(0, rows)):\r\n review = re.sub('[^a-zA-Z]', ' ',df[text][i])\r\n review = review.lower()\r\n review = review.split()\r\n ps = PorterStemmer()\r\n review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]\r\n review = ' '.join(review)\r\n corpus.append(review)\r\n\r\n# Create Bag of Words model\r\ncv = CountVectorizer(max_features = 1500)\r\nX = cv.fit_transform(corpus).toarray()\r\n\r\n# Importing the trained model file using joblib from sklearn\r\n\r\nmodel = joblib.load('model_joblib')\r\npredict = model.predict(X)\r\n\r\n# Counting the number of 'Good', 'Bad' & 'Neutral' comments predicted by our model\r\n(good, bad, neutral) = (0,0,0)\r\nfor x in predict:\r\n if x=='good':\r\n good = good + 1\r\n elif x=='bad':\r\n bad = bad + 1\r\n elif x=='neutral':\r\n neutral = neutral + 1\r\n # print(x)\r\n\r\n# Printing the number of 'Good', 'Bad' & 'Neutral' comments\r\nprint(\"Good = \",good)\r\nprint(\"Neutral = \",neutral)\r\nprint(\"bad = \",bad)\r\n\r\n# Exporting the PREDICTIONS along with the REVIEWS in a CSV file\r\nwith open('Result.csv', 'w') as f:\r\n writer = csv.writer(f)\r\n writer.writerows(zip(df[text], predict))\r\n\r\n\r\n# Plotting a pie chart showing the percentage of three comments predicted\r\n# Pie chart, where the slices will be ordered and plotted counter-clockwise:\r\nlabels = 'Good', 'Neutral', 'Bad'\r\nsizes = [good, neutral, bad]\r\nexplode = (0, 0, 0) # only \"explode\" the 1st slice (i.e. 'Good')\r\n\r\nfig1, ax1 = plt.subplots()\r\nax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',\r\n shadow=True, startangle=90)\r\nax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\r\n\r\nplt.show()\r\n","sub_path":"automate.py","file_name":"automate.py","file_ext":"py","file_size_in_byte":2841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"419628182","text":"from TicTacToe import Gamelogic\nimport MCTS\nimport ResNet\nfrom TicTacToe import Config\nimport Files\nimport os\n\ngame = Gamelogic.TicTacToe()\nconfig = Config\n\n# Creating the NN\nh, w, d = game.get_board().shape\nagent = ResNet.ResNet.build(h, w, d, 128, config.policy_output_dim, num_res_blocks=5)\nagent2 = ResNet.ResNet.build(h, w, d, 128, config.policy_output_dim, num_res_blocks=5)\n\n# Creating the MCTS\ntree = MCTS.MCTS(game, game.get_board(), agent)\n# tree.dirichlet_noise = False\ntree.NN_input_dim = config.board_dims\ntree.policy_output_dim = config.policy_output_dim\ntree.NN_output_to_moves_func = config.NN_output_to_moves\ntree.move_to_number_func = config.move_to_number\ntree.number_to_move_func = config.number_to_move\n# tree.set_game(game)\n\nfor opponent in os.listdir(\"Models/TicTactoe/\"):\n won = 0\n sum = 0\n draw=0\n agent.load_weights(\"Models/TicTactoe/40.h5\")\n agent2.load_weights(\"Models/TicTactoe/\" + opponent)\n\n for player_start in range(2):\n for start in range(9):\n print(\"Started\\n\\n\")\n game.__init__()\n game.execute_move(start)\n while not game.is_final():\n game.print_board()\n # input()\n print(game.get_moves())\n print(game.get_legal_NN_output())\n if game.get_turn() == player_start:\n tree.set_evaluation(agent)\n else:\n tree.set_evaluation(agent2)\n tree.search_series(2)\n print(\"post\", tree.get_posterior_probabilities())\n print(\"pri\", tree.get_prior_probabilities(game.get_board().reshape(1,3,3,2)))\n game.execute_move(tree.get_most_searched_move(tree.root))\n tree.reset_search()\n won += game.get_outcome()[player_start] == 1\n draw += game.get_outcome()[player_start] == 0\n sum += 1\n print(\"Finished\\n\\n\")\n print(\"Result against\", opponent, \"-\", won, \"/\", draw, \"/\", sum-won-draw)\n","sub_path":"TestAZ.py","file_name":"TestAZ.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"569615950","text":"class Solution(object):\n def getPermutation(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: str\n \"\"\"\n elements = range(1, n+1)\n NN = reduce(operator.mul, elements) # n!\n k, result = (k-1) % NN, ''\n while len(elements) > 0:\n NN = NN / len(elements)\n i, k = k / NN, k % NN\n result += str(elements.pop(i))\n return result\n","sub_path":"60 Permutation Sequence.py","file_name":"60 Permutation Sequence.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"514949955","text":"import argparse\nimport os.path\nimport random\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"--nt\", help=\"number of threads to use\")\nparser.add_argument(\"--maxtime\", help=\"max time for computation\")\nparser.add_argument(\"--memmax\", help=\"max memory to request\")\nparser.add_argument(\"--partitions\", help=\"comma sep list of partitions\")\n\nparser.add_argument(\"--f1\", help=\"f1 fastq file\")\nparser.add_argument(\"--f2\", help=\"f2 fastq file\")\nparser.add_argument(\"--output_dir\", help=\"output dir\")\nparser.add_argument(\"--isolate\", help=\"isolate name/number\")\nparser.add_argument(\"--job_file\", help=\"output job file\")\n\nargs = parser.parse_args()\n\nheader1 = \"#!/bin/bash\\n\"\nheader7 = \"#SBATCH --time=\" + args.maxtime\nheader3 = \"#SBATCH --nodes=1\"\nheader2 = \"#SBATCH --ntasks=1\"\nheader4 = \"#SBATCH --cpus-per-task=\" + args.nt\nheader5 = \"#SBATCH --partition=\" + args.partitions\nheader6 = \"#SBATCH --mem=\" + args.memmax\nheader8 = \"#SBATCH --output=\" + args.isolate + \".out\"\nheader9 = \"#SBATCH --error=\" + args.isolate + \".err\"\n\nheader = \"\\n\".join([header1, header7, header2, header3, header4, header5, header6, header8, header9])\n\nunicycler_cmd = \"module load bioconda/conda3\\n\\nsource activate unicycler-0.4.8\\n\\nunicycler -1 \" + args.f1 + \" -2 \" + args.f2 + \" -o \" + args.output_dir +\\\n \" -t \" + args.nt + \" --depth_filter 0.01 --min_fasta_len 100 --min_polish_size 100\"\n\nto_write = header + \"\\n\\n\" + unicycler_cmd\n\nwith open(args.job_file, \"w\") as outfile:\n outfile.write(to_write)\n","sub_path":"phd/j2_create_arc_unicycler_jobs_1.py","file_name":"j2_create_arc_unicycler_jobs_1.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"294729544","text":"from flask import Flask, request\nfrom request_utils import RequestHandler\nfrom response_utils import Response\nimport init\n\n# FLASK_APP=app.py flask run --port=8090\n# ngrok http 8090\napp = Flask(__name__)\n\ninit.init()\n\n\n@app.route(\"/\", methods=[\"POST\"])\ndef slack_request():\n handler = RequestHandler(request)\n results = handler.get_command().execute()\n return build_response(results)\n\n\ndef build_response(command_results):\n response = Response(command_results)\n return response.send()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"541525823","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('tc', '0016_media_deleted'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='media',\n name='orient',\n field=models.CharField(default=b'orient_0', max_length=10),\n ),\n ]\n","sub_path":"tc/migrations/0017_media_orient.py","file_name":"0017_media_orient.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"200678271","text":"\n\n\n# =============================================================================\n# Threading .....concurrent operation\n# =============================================================================\n#dir(threading)\n['Barrier', 'BoundedSemaphore', 'BrokenBarrierError',\n 'Condition', 'Event', 'ExceptHookArgs',\n 'Lock', 'RLock', 'Semaphore', 'TIMEOUT_MAX',\n 'Thread', 'ThreadError', 'Timer', 'WeakSet',\n '_CRLock', '_DummyThread', '_HAVE_THREAD_NATIVE_ID',\n '_MainThread', '_PyRLock', '_RLock', '_SHUTTING_DOWN',\n '__all__', '__builtins__', '__cached__', '__doc__',\n '__file__', '__loader__', '__name__', '__package__', '__spec__', '_active', '_active_limbo_lock', '_after_fork', '_allocate_lock',\n '_count', '_counter', '_dangling', '_deque',\n '_enumerate', '_islice', '_limbo', '_main_thread', '_maintain_shutdown_locks',\n '_make_invoke_excepthook', '_newname', '_os', '_profile_hook',\n '_register_atexit', '_set_sentinel',\n '_shutdown', '_shutdown_locks',\n '_shutdown_locks_lock', '_start_new_thread',\n '_sys', '_threading_atexits', '_time',\n '_trace_hook', 'activeCount',\n 'active_count', 'currentThread', 'current_thread',\n 'enumerate', 'excepthook',\n 'functools', 'get_ident',\n 'get_native_id', 'local',\n 'main_thread', 'setprofile',\n 'settrace', 'stack_size']\n\nimport threading\n\n# global variable x\nx = 0\n\ndef increment():\n\t\"\"\"\n\tfunction to increment global variable x\n\t\"\"\"\n\tglobal x\n\tx += 1\n\ndef thread_task():\n\t\"\"\"\n\ttask for thread\n\tcalls increment function 100000 times.\n\t\"\"\"\n\tfor _ in range(100000):\n\t\tincrement()\n\ndef main_task():\n\tglobal x\n\t# setting global variable x as 0\n\tx = 0\n\n\t# creating threads\n\tt1 = threading.Thread(target=thread_task)\n\tt2 = threading.Thread(target=thread_task)\n\n\t# start threads\n\tt1.start()\n\tt2.start()\n\n\t# wait until threads finish their job\n\tt1.join()\n\tt2.join()\n\nif __name__ == \"__main__\":\n\tfor i in range(10):\n\t\tmain_task()\n\t\tprint(\"Iteration {0}: x = {1}\".format(i,x))\n","sub_path":"evening_batch2/thread/thread_test3.py","file_name":"thread_test3.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"406326572","text":"from pymongo import MongoClient\nimport time\nimport numpy as np\nfrom scipy.linalg import svd\nfrom scipy import dot\n\n\n# Mongo db connection\nconnection = MongoClient('localhost', 27017)\ndb = connection.MWDB_devset\n\n# Input k from the user\nk = int(input(\"Enter the value of k: \"))\n\n# get all the location details from the database\nall_locations_details = list(db.locations.find())\n\nall_terms = []\nall_locations = []\n\n# create array of 'all_locations' and 'all_terms'\nfor item in all_locations_details:\n if item['locationQuery'] is not all_locations:\n all_locations.append(item['locationQuery'])\n for detail in item['details']:\n if detail['term'] is not all_terms:\n all_terms.append(detail['term'])\n\n# create zeros matrix of length of all locations and all terms\nlocation_data_matrix = np.zeros(shape=(len(all_locations_details), len(all_terms)))\n\n# create locations - terms matrix\nfor location in all_locations_details:\n for detail in location['details']:\n location_data_matrix[all_locations.index(location['locationQuery'])][all_terms.index(detail['term'])] = detail['TF-IDF']\n\n# transpose of location - term matrix\nlocation_data_matrix_transpose = location_data_matrix.transpose()\n\nlocation_location_matrix = dot(location_data_matrix, location_data_matrix_transpose)\n\n# SVD\nU, s, VT = svd(location_location_matrix)\n\n# project original matrix to the new location-semantics matrix\nproject_matrix = dot(location_location_matrix, U)\n\nfeatures_locations_matrix = project_matrix.transpose()\n\n# Get top k- latent semantics\ntop_k_latent_semantics = features_locations_matrix[:k, :]\n# d = {}\ncount = 1\nfor item in top_k_latent_semantics:\n d = {}\n print('\\n')\n print(\"Latent Semantic\", count)\n print()\n count += 1\n i = 0\n while i < len(all_locations):\n d[all_locations[i]] = item[i]\n i += 1\n for w in sorted(d, key=d.get, reverse=True):\n print(w, ':', d[w])\n","sub_path":"Phase 2/task6.py","file_name":"task6.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"201028132","text":"import json\n\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nfrom jsonfield import JSONField\n\nfrom talentmap_api.common.models import StaticRepresentationModel\nfrom talentmap_api.common.common_helpers import get_filtered_queryset, resolve_path_to_view, format_filter, get_avatar_url\nfrom talentmap_api.common.permissions import in_group_or_403\n\nfrom talentmap_api.messaging.models import Notification\n\n\nclass UserProfile(StaticRepresentationModel):\n user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')\n emp_id = models.CharField(max_length=255, null=False, help_text=\"The user's employee id\")\n\n def __str__(self):\n return f\"{self.user.first_name} {self.user.last_name}\"\n\n @property\n def avatar(self):\n return get_avatar_url(self.user.email)\n\n @property\n def display_name(self):\n '''\n Returns the user's display name, derived from first name, username or e-mail\n '''\n display_name = \"\"\n if self.user.first_name:\n display_name = self.user.first_name\n elif self.user.username:\n display_name = self.user.username\n else:\n display_name = self.user.email\n\n return display_name\n\n @property\n def initials(self):\n '''\n Returns the user's initials, derived from first name/last name or e-mail\n '''\n initials = \"\"\n if self.user.first_name and self.user.last_name:\n initials = f\"{self.user.first_name[0]}{self.user.last_name[0]}\"\n if len(initials) == 0:\n # No first name/last name on user object, derive from email\n # Example email: StateJB@state.gov\n # [x for x in self.user.email if x.isupper()] - get all capitals\n # [:2] - get the first two\n # [::-1] - reverse the list\n initials = \"\".join([x for x in self.user.email if x.isupper()][:2][::-1])\n\n return initials\n\n @property\n def is_cdo(self):\n '''\n Represents if the user is a CDO (Career development officer) or not.\n '''\n try:\n in_group_or_403(self.user, 'cdo')\n return True\n except BaseException:\n return False\n\n class Meta:\n managed = True\n ordering = ['user__last_name']\n\n\nclass SavedSearch(models.Model):\n '''\n Represents a saved search.\n '''\n owner = models.ForeignKey(UserProfile, on_delete=models.DO_NOTHING, related_name=\"saved_searches\")\n\n name = models.CharField(max_length=255, null=False, default=\"Saved Search\", help_text=\"The name of the saved search\")\n endpoint = models.TextField(help_text=\"The endpoint for this search and filter\")\n\n '''\n Filters should be a JSON object of filters representing a search. Generally, the values\n should be stored in a list.\n For example, suppose our user preferred posts with post danger pay >= 20 and with grade = 05\n\n {\n \"post__danger_pay__gte\": [\"20\"],\n \"grade__code\": [\"05\"]\n }\n '''\n filters = JSONField(default={}, help_text=\"JSON object containing filters representing the saved search\")\n\n count = models.IntegerField(default=0, help_text=\"Current count of search results for this search\")\n\n date_created = models.DateTimeField(auto_now_add=True)\n date_updated = models.DateTimeField(auto_now=True)\n is_bureau = models.BooleanField(default=False, help_text=\"Whether this search is for Bureau/AO\")\n\n\n def get_queryset(self):\n return get_filtered_queryset(resolve_path_to_view(self.endpoint).filter_class, self.filters)\n\n def update_count(self, created=False, jwt_token=''):\n\n filter_class = resolve_path_to_view(self.endpoint).filter_class\n query_params = format_filter(self.filters)\n if getattr(filter_class, \"use_api\", False):\n count = int(filter_class.get_count(query_params, jwt_token).get('count', 0))\n else:\n count = self.get_queryset().count()\n\n if self.count != count:\n # Create a notification for this saved search's owner if the amount has increased\n diff = count - self.count\n if diff > 0 and not created:\n Notification.objects.create(\n owner=self.owner,\n tags=['saved_search'],\n message=f\"Saved search {self.name} has {diff} new results available\",\n meta=json.dumps({\"count\": diff, \"search\": {\"filters\": self.filters, \"endpoint\": self.endpoint}})\n )\n\n self.count = count\n\n # Do not trigger signals for this save\n self._disable_signals = True\n self.save()\n self._disable_signals = False\n\n @staticmethod\n def update_counts_for_endpoint(endpoint=None, contains=False, jwt_token='', user=''):\n '''\n Update all saved searches counts whose endpoint matches the specified endpoint.\n If the endpoint is omitted, updates all saved search counts.\n\n Args:\n - endpoint (string) - Endpoint to updated saved searches for\n '''\n\n queryset = SavedSearch.objects.all()\n if endpoint:\n if contains:\n queryset = SavedSearch.objects.filter(endpoint__icontains=endpoint)\n else:\n queryset = SavedSearch.objects.filter(endpoint=endpoint)\n\n for search in queryset:\n if search.owner == user or user == '':\n search.update_count(jwt_token=jwt_token)\n\n class Meta:\n managed = True\n ordering = [\"date_created\"]\n\n\n# Signal listeners\n@receiver(post_save, sender=User)\ndef create_profile(sender, instance, created, **kwargs):\n '''\n This listener creates a user profile for every created user.\n '''\n if created:\n UserProfile.objects.create(user=instance)\n","sub_path":"talentmap_api/user_profile/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"172245035","text":"from keras.optimizers import RMSprop\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\n \ncheckpoint = ModelCheckpoint(\"facemodel.h5\",\n monitor=\"val_loss\",\n mode=\"min\",\n save_best_only = True,\n verbose=1)\n\nearlystop = EarlyStopping(monitor = 'val_loss', \n min_delta = 0, \n patience = 3,\n verbose = 1,\n restore_best_weights = True)\n\n# we put our call backs into a callback list\ncallbacks = [earlystop, checkpoint]\n\n# Note we use a very small learning rate \nmodelnew.compile(loss = 'categorical_crossentropy',\n optimizer = RMSprop(lr = 0.001),\n metrics = ['accuracy'])\n\nnb_train_samples = 544\nnb_validation_samples = 200\nepochs = 3\nbatch_size = 64\n\nhistory = modelnew.fit_generator(\n train_generator,\n steps_per_epoch = nb_train_samples // batch_size,\n epochs = epochs,\n callbacks = callbacks,\n validation_data = validation_generator,\n validation_steps = nb_validation_samples // batch_size)\n\nmodelnew.save(\"facemodel.h5\")\n","sub_path":"vgg5thtraining.py","file_name":"vgg5thtraining.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"252237907","text":"L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\nl0 = [2009, 2001, 2003, 1986, 1990, 1983, 1980, 1979, 1950, 2005]\nl1 = ['Paulão', 'Pablo Vitar', 'Jojo Todinho', 'Surfistinha', 'Mia Khalifa',\\\n 'Just Bieber', 'Lula', 'Jatene', 'Dilma', 'Annita']\nl4 = ['Macaco', 'Galo', 'Cão', 'Porco', 'Rato', 'Boi', 'Tigre',\\\n 'Coelho', 'Dragão', 'Serpente', 'Cavalo', 'Carneiro']\n\ndef zodiaco ():\n return(l0[i] % 12 == L[j])\nfor i in range(10):\n for j in range(12):\n if zodiaco():\n print('{0} = {1}'. format(l1[i], l4[j]))","sub_path":"python/reviProva/Python-master/39_ZodíacoEmLista.py","file_name":"39_ZodíacoEmLista.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"293947790","text":"from typing import Callable, Iterable, Tuple\n\nfrom ereuse_devicehub.resources.device.sync import Sync\nfrom ereuse_devicehub.resources.event.schemas import Add, AggregateRate, Benchmark, \\\n BenchmarkDataStorage, BenchmarkProcessor, BenchmarkProcessorSysbench, BenchmarkRamSysbench, \\\n BenchmarkWithRate, EraseBasic, EraseSectors, Event, Install, PhotoboxSystemRate, \\\n PhotoboxUserRate, Rate, Remove, Snapshot, Step, StepRandom, StepZero, StressTest, Test, \\\n TestDataStorage, WorkbenchRate\nfrom ereuse_devicehub.resources.event.views import EventView, SnapshotView\nfrom teal.resource import Converters, Resource\n\n\nclass EventDef(Resource):\n SCHEMA = Event\n VIEW = EventView\n AUTH = True\n ID_CONVERTER = Converters.uuid\n\n\nclass AddDef(EventDef):\n SCHEMA = Add\n\n\nclass RemoveDef(EventDef):\n SCHEMA = Remove\n\n\nclass EraseBasicDef(EventDef):\n SCHEMA = EraseBasic\n\n\nclass EraseSectorsDef(EraseBasicDef):\n SCHEMA = EraseSectors\n\n\nclass StepDef(Resource):\n SCHEMA = Step\n\n\nclass StepZeroDef(StepDef):\n SCHEMA = StepZero\n\n\nclass StepRandomDef(StepDef):\n SCHEMA = StepRandom\n\n\nclass RateDef(EventDef):\n SCHEMA = Rate\n\n\nclass AggregateRateDef(RateDef):\n SCHEMA = AggregateRate\n\n\nclass WorkbenchRateDef(RateDef):\n SCHEMA = WorkbenchRate\n\n\nclass PhotoboxUserDef(RateDef):\n SCHEMA = PhotoboxUserRate\n\n\nclass PhotoboxSystemRateDef(RateDef):\n SCHEMA = PhotoboxSystemRate\n\n\nclass InstallDef(EventDef):\n SCHEMA = Install\n\n\nclass SnapshotDef(EventDef):\n SCHEMA = Snapshot\n VIEW = SnapshotView\n\n def __init__(self, app, import_name=__package__, static_folder=None, static_url_path=None,\n template_folder=None, url_prefix=None, subdomain=None, url_defaults=None,\n root_path=None, cli_commands: Iterable[Tuple[Callable, str or None]] = tuple()):\n super().__init__(app, import_name, static_folder, static_url_path, template_folder,\n url_prefix, subdomain, url_defaults, root_path, cli_commands)\n self.sync = Sync()\n\n\nclass TestDef(EventDef):\n SCHEMA = Test\n\n\nclass TestDataStorageDef(TestDef):\n SCHEMA = TestDataStorage\n\n\nclass StressTestDef(TestDef):\n SCHEMA = StressTest\n\n\nclass BenchmarkDef(EventDef):\n SCHEMA = Benchmark\n\n\nclass BenchmarkDataStorageDef(BenchmarkDef):\n SCHEMA = BenchmarkDataStorage\n\n\nclass BenchmarkWithRateDef(BenchmarkDef):\n SCHEMA = BenchmarkWithRate\n\n\nclass BenchmarkProcessorDef(BenchmarkWithRateDef):\n SCHEMA = BenchmarkProcessor\n\n\nclass BenchmarkProcessorSysbenchDef(BenchmarkProcessorDef):\n SCHEMA = BenchmarkProcessorSysbench\n\n\nclass BenchmarkRamSysbenchDef(BenchmarkWithRateDef):\n SCHEMA = BenchmarkRamSysbench\n","sub_path":"ereuse_devicehub/resources/event/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"497863861","text":"#!/usr/bin/env python\n\n#############################################################################\n# Makes the probability tables using AddToHist and records as .npy files\n#############################################################################\n\nfrom icecube import icetray, dataio\nfrom I3Tray import I3Tray\nimport myGlobals as my\nimport numpy as np\nimport argparse, time, AddToHist\n\n\nif __name__ == \"__main__\":\n\n # Global variables setup for path names\n my.setupShowerLLH(verbose=False)\n\n p = argparse.ArgumentParser(\n description='Builds binned histograms for use with ShowerLLH')\n p.add_argument('-f', '--files', dest='files', nargs='*',\n help='Input filelist to run over')\n p.add_argument('-b', '--bintype', dest='bintype',\n default='standard',\n choices=['standard','nozenith','logdist'],\n help='Option for a variety of preset bin values')\n p.add_argument('-o', '--outFile', dest='outFile',\n help='Output filename')\n args = p.parse_args()\n\n # Starting parameters\n recoPulses = 'CleanedHLCTankPulses'\n\n # Import ShowerLLH bins\n binFile = '{}/ShowerLLH_bins.npy'.format(my.llh_resource)\n binDict = np.load(binFile)\n binDict = binDict.item()\n binDict = binDict[args.bintype]\n\n # Execute\n t0 = time.time()\n tray = I3Tray()\n tray.Add('I3Reader', FileNameList=args.files)\n tray.Add(AddToHist.fillHist,\n binDict=binDict,\n recoPulses=recoPulses,\n outFile=args.outFile)\n tray.Execute()\n tray.Finish()\n\n print('Time taken: {}'.format(time.time() - t0))\n","sub_path":"makeTables/MakeHist.py","file_name":"MakeHist.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"346228704","text":"import os\nfrom nose.tools import eq_\nfrom pyexcel_cli.merge import merge\nfrom click.testing import CliRunner\nfrom pyexcel import get_book\nfrom textwrap import dedent\n\n\ndef test_simple_option():\n runner = CliRunner()\n file_fixture = os.path.join(\"tests\", \"fixtures\", \"transcode_simple.csv\")\n dir_fixture = os.path.join(\"tests\", \"fixtures\", \"file_dir\")\n glob_fixture = os.path.join(\"tests\", \"fixtures\", \"glob_dir\", \"*\")\n output = \"test_simple_option.xls\"\n result = runner.invoke(merge, [file_fixture, dir_fixture, glob_fixture,\n output])\n eq_(result.exit_code, 0)\n book = get_book(file_name=output)\n expected = dedent(\"\"\"\n transcode_simple.csv:\n +---+---+---+\n | 1 | 2 | 3 |\n +---+---+---+\n merge_test.csv:\n +---+---+---+\n | 1 | 2 | 3 |\n +---+---+---+\n merge_test2.csv:\n +---+---+---+\n | 1 | 2 | 3 |\n +---+---+---+\"\"\").strip('\\n')\n eq_(str(book), expected)\n os.unlink(output)\n\n\ndef test_stdout_option():\n runner = CliRunner()\n file_fixture = os.path.join(\"tests\", \"fixtures\", \"transcode_simple.csv\")\n dir_fixture = os.path.join(\"tests\", \"fixtures\", \"file_dir\")\n glob_fixture = os.path.join(\"tests\", \"fixtures\", \"glob_dir\", \"*\")\n output = \"-\"\n result = runner.invoke(merge, [\"--output-file-type\", \"csv\",\n \"--csv-output-lineterminator\", \"\\n\",\n \"--csv-output-delimiter\", \";\",\n file_fixture, dir_fixture, glob_fixture,\n output])\n eq_(result.exit_code, 0)\n expected = dedent(\"\"\"\n ---pyexcel:transcode_simple.csv---\n 1;2;3\n ---pyexcel---\n ---pyexcel:merge_test.csv---\n 1;2;3\n ---pyexcel---\n ---pyexcel:merge_test2.csv---\n 1;2;3\n ---pyexcel---\n \"\"\").strip('\\n') + '\\n'\n eq_(result.output, expected)\n\n\ndef test_more_csv_options():\n runner = CliRunner()\n file_fixture = os.path.join(\"tests\", \"fixtures\", \"transcode_quoted.csv\")\n output = \"-\"\n result = runner.invoke(merge, [\"--output-file-type\", \"csv\",\n \"--csv-output-lineterminator\", \"\\n\",\n \"--csv-output-delimiter\", \":\",\n \"--csv-output-quoting\", \"minimal\",\n file_fixture, output])\n eq_(result.exit_code, 0)\n expected = dedent(\"\"\"\n hello:|world|:1:2\n 3:4:5:6\n \"\"\").strip('\\n') + '\\n'\n eq_(result.output, expected)\n\n\ndef test_nothing_do_do():\n runner = CliRunner()\n glob_fixture = os.path.join(\"tests\", \"fixtures\", \"nothing_is_excel\", \"*\")\n output = \"test_simple_option.xls\"\n result = runner.invoke(merge, [glob_fixture, output])\n expected = dedent(\"\"\"\n Skipping tests{0}fixtures{0}nothing_is_excel{0}test.no.excel\n Nothing to be merged\"\"\").strip('\\n') + '\\n'\n eq_(result.exit_code, 0)\n eq_(result.output, expected.format(os.sep))\n","sub_path":"tests/test_merge.py","file_name":"test_merge.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"372637993","text":"# Project Done By:\r\n# Mohammed Junaid Alam (2019503025)\r\n# Gurbani Bedi (2019503518)\r\n# Abhishek Manoharan (2019503502)\r\n\r\nimport os\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.autograd as autograd\r\nfrom torch.autograd import Variable\r\nimport torch.optim as optim\r\nimport torch.nn.functional as functional\r\nfrom random import sample\r\n\r\nclass Network(nn.Module):\r\n \r\n def __init__(self,nb_inputs,nb_actions):\r\n super(Network,self).__init__()\r\n self.nb_inputs = nb_inputs\r\n self.nb_outputs = nb_actions\r\n self.first_connection = nn.Linear(self.nb_inputs,30)\r\n self.second_connection = nn.Linear(30,self.nb_outputs)\r\n \r\n def forward(self,state):\r\n fc1_activated = functional.relu(self.first_connection(state))\r\n q_values = self.second_connection(fc1_activated)\r\n return q_values\r\n \r\nclass Memory(object):\r\n \r\n def __init__(self,capacity):\r\n self.capacity = capacity\r\n self.memory = []\r\n \r\n def push(self,state):\r\n self.memory.append(state)\r\n if len(self.memory) > self.capacity:\r\n del self.memory[0]\r\n \r\n def pull(self,batch_size):\r\n rand_sample = zip(*sample(self.memory,batch_size))\r\n return map(lambda x:Variable(torch.cat(x,0)),rand_sample)\r\n \r\nclass Brain():\r\n \r\n def __init__(self,input_nodes,nb_actions,gamma):\r\n self.gamma = gamma\r\n self.reward_mean = []\r\n self.memory = Memory(100000)\r\n self.model = Network(input_nodes,nb_actions)\r\n self.optimizer = optim.Adam(self.model.parameters(),lr=0.001)\r\n self.last_state = torch.Tensor(input_nodes).unsqueeze(0)\r\n self.last_reward = 0\r\n self.last_action = 0\r\n \r\n def select_action(self,state):\r\n probs = functional.softmax(self.model.forward(Variable(state,volatile=True))*100)\r\n action = probs.multinomial(1)\r\n return action.data[0,0]\r\n \r\n def learn(self,prev_state,current_state,prev_action,prev_reward):\r\n outputs = self.model.forward(prev_state).gather(1,prev_action.unsqueeze(1)).squeeze(1)\r\n max_futures = self.model.forward(current_state).detach().max(1)[0]\r\n targets = self.gamma*max_futures + prev_reward\r\n loss = functional.smooth_l1_loss(outputs,targets)\r\n self.optimizer.zero_grad()\r\n loss.backward()\r\n self.optimizer.step()\r\n \r\n def update(self,prev_reward,current_state):\r\n new_state = torch.Tensor(current_state).float().unsqueeze(0)\r\n self.memory.push((self.last_state,new_state,torch.LongTensor([int(self.last_action)]),torch.Tensor([self.last_reward])))\r\n action = self.select_action(new_state)\r\n if len(self.memory.memory) > 100:\r\n train_last_state,train_next_state,train_last_action,train_last_reward = self.memory.pull(100)\r\n self.learn(train_last_state,train_next_state,train_last_action,train_last_reward)\r\n self.last_state = new_state\r\n self.last_action = action\r\n self.last_reward = prev_reward\r\n self.reward_mean.append(prev_reward)\r\n if len(self.reward_mean) > 1000:\r\n del self.reward_mean[0]\r\n return action\r\n \r\n def score(self):\r\n mean = sum(self.reward_mean)/(len(self.reward_mean) + 1.0)\r\n return mean\r\n \r\n def save(self):\r\n torch.save({'state_dict': self.model.state_dict(),\r\n 'optimizer': self.optimizer.state_dict\r\n },'recent_brain.pth')\r\n \r\n def load(self):\r\n if os.path.isfile('recent_brain.pth'):\r\n print('---Loading checkpoint---')\r\n checkpoint = torch.load('recent_brain.pth')\r\n self.model.load_state_dict(checkpoint['state_dict'])\r\n self.optimizer.load_state_dict(checkpoint['optimizer']) \r\n print('Model successfully loaded!')\r\n else:\r\n print('There isn\\'t an instance of a saved model!')\r\n \r\n\r\n ","sub_path":"backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":3993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"362433480","text":"VPScriptMenuTitle = \"Copy VoodooPad Link to Clipboard\"\n\nfrom AppKit import *\nfrom Foundation import *\n\ndef main(windowController, *args, **kwargs):\n page = windowController.currentPage()\n link = \"x-voodoopad-item://\" + page.uuid()\n newStr = NSString.stringWithString_(link)\n pb = NSPasteboard.generalPasteboard()\n pb.declareTypes_owner_([NSStringPboardType], None)\n pb.setString_forType_(unicode(link), NSStringPboardType)\n","sub_path":"Library/Application Support/VoodooPad/Script PlugIns/VoodooPadLink.py","file_name":"VoodooPadLink.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"292799275","text":"#!/usr/bin/python\n\nimport auxiliary as aux\nimport os\nimport sys\n\nif(len(sys.argv) < 3):\n print(\"python getSZA.py AKS_DIR OUTPUT_FILE CRUISE_FILE\")\n exit(-1)\n\naks = []\noutputaks = []\ndirname = sys.argv[1]\ndircontent = os.listdir(dirname)\nspectrum = aux.getVals(sys.argv[3], \"spectrum\")\nsza = aux.getVals(sys.argv[3], \"asza\")\n\n#Lies die Namen der Averaging Kernels ein\nfor element in sorted(dircontent):\n if(\".aks\" in element):\n aks.append(element)\n\n#Etwas sicherer machen, indem die Werte in einem Dictionary abgespeichert werden\nspectrasza = zip(spectrum, sza)\n\nfor i in spectrasza:\n for kernel in aks:\n if(i[0] in kernel):\n outputaks.append(\"{}\\t{}\".format(kernel, i[1]))\nprint(\"Anzahl Spektren: {}\".format(len(spectrum)))\nprint(\"Anzahl Kernel: {}\".format(len(aks)))\nprint(\"Anzahl zu speichernder Kernel: {}\".format(len(outputaks)))\nf = open(sys.argv[2], \"w\")\nfor element in outputaks:\n f.write(\"{}/{}\\n\".format(dirname, element))\nf.close()\n","sub_path":"GEOSChemProcessing/src/getSZA.py","file_name":"getSZA.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"68726682","text":"#r\nstart, end =input().split()\nstart=int(start)\nend=int(end)\n \n# iterating each number in list \nfor num in range(start+1, end + 1): \n \n # checking condition \n if num % 2 != 0: \n print(num, end = \" \") \n","sub_path":"odddd.py","file_name":"odddd.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"340083023","text":"from collections import deque\n# queue를 위함\n\n\ndef check(s, begin):\n answer = 0\n for i in range(len(s)):\n if list(s)[i] != list(begin)[i]:\n answer += 1\n return True if answer == 1 else False\n\n\ndef solution(begin, target, words):\n if target not in words:\n return 0\n\n queue = deque()\n queue.append([begin, []])\n\n while queue:\n n, l = queue.popleft()\n for word in words:\n if word not in l and check(word, n):\n if word == target:\n return len(l) + 1\n temp = l[0:]\n temp.append(word)\n queue.append([word, temp])\n\n return 0\n","sub_path":"yusang/week7/단어변환.py","file_name":"단어변환.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"401824198","text":"import re\r\n\r\nl = []\r\nfor _ in range(int(input())):\r\n l.append(input())\r\ns = ' '.join(l)\r\n\r\nres = re.findall(r'https?://(?:(?:[w]{3}\\.)?|(?:w2\\.)?)([\\w-]+\\.[\\w.-]+)(?=(?:[/?\"]))', s)\r\n\r\nl = []\r\nd = {}\r\nfor elm in res:\r\n if not d.get(elm):\r\n l.append(elm)\r\n d[elm] = 1\r\n\r\nl.sort()\r\nprint(';'.join(l))\r\n\r\n","sub_path":"Medium - RegEx_DetectTheDomainName.py","file_name":"Medium - RegEx_DetectTheDomainName.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"347687861","text":"#!/usr/bin/env python\n\nfrom wall_follower import WallFollower\nfrom person_follower import PersonFollower\n\nimport rospy\nfrom geometry_msgs.msg import Twist, Vector3\nfrom sensor_msgs.msg import LaserScan\n\n\ndef run():\n \"\"\"Follows the wall using sensor data.\"\"\"\n pub = rospy.Publisher('cmd_vel', Twist, queue_size=10)\n rospy.init_node('control_neato', anonymous=True)\n r = rospy.Rate(10) # 10hz\n\n wall_follower = WallFollower()\n person_follower = PersonFollower()\n follower = wall_follower\n\n # Subscribe the followers to LaserScan\n sub = rospy.Subscriber('scan', LaserScan, follower.get_location)\n sub2 = rospy.Subscriber('scan', LaserScan, person_follower.get_location)\n\n while not rospy.is_shutdown():\n v, a = follower.follow()\n if a and v:\n pub.publish(Twist(linear=Vector3(x=v), angular=Vector3(z=a)))\n # If the neato sees an object thats not a wall. Change to person follower\n if follower.object_found():\n follower = person_follower\n else:\n follower = wall_follower\n r.sleep()\n\nif __name__ == '__main__':\n try:\n run()\n except rospy.ROSInterruptException: pass\n","sub_path":"src/warmup_project/src/scripts/run_neato.py","file_name":"run_neato.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"46645286","text":"####################################\n########## Here I will look into the MERT for the cross section\n####################################\nimport numpy as np\n\n\n\ndef MERT(epsilon, A, D, F, A1):\n a0 = 1 # 5.29e-11 # in m\n hbar = 1 # 197.32697*1e-9 # in eV m\n m = 1 # 511e3 # eV/c**2\n alpha = 27.292 * a0 ** 3\n k = np.sqrt((epsilon) / (13.605 * a0 ** 2))\n\n eta0 = -A * k * (1 + (4 * alpha) / (3 * a0) * k ** 2 * np.log(k * a0)) \\\n - (np.pi * alpha) / (3 * a0) * k ** 2 + D * k ** 3 + F * k ** 4\n\n eta1 = (np.pi) / (15 * a0) * alpha * k ** 2 - A1 * k ** 3\n\n Qm = (4 * np.pi * a0 ** 2) / (k ** 2) * (np.sin(np.arctan(eta0) - np.arctan(eta1))) ** 2\n\n Qt = (4 * np.pi * a0 ** 2) / (k ** 2) * (np.sin(np.arctan(eta0))) ** 2\n\n return Qm * (5.29e-11) ** 2 * 1e20, Qt * (5.29e-11) ** 2 * 1e20\n\n\ndef WEIGHT_Q(eV, Qm, BashBoltzQm, Lamda, eV0):\n WeightQm = (1 - np.tanh(Lamda * (eV - eV0))) / 2\n WeightBB = (1 + np.tanh(Lamda * (eV - eV0))) / 2\n\n NewBashQm = BashBoltzQm * WeightBB\n NewMERTQm = Qm * WeightQm\n NewQm = NewBashQm + NewMERTQm\n return NewQm\n\n\ndef HYBRID_X_SECTIONS(MB_EMTx, MB_EMTy, MB_ETx, MB_ETy, A, D, F, A1, Lambda, eV0):\n Qm_MERT, Qt_MERT = MERT(MB_EMTx, A, D, F, A1)\n New_Qm = WEIGHT_Q(MB_EMTx, Qm_MERT, MB_EMTy, Lambda, eV0)\n Qm_MERT, Qt_MERT = MERT(MB_ETx, A, D, F, A1)\n New_Qt = WEIGHT_Q(MB_ETx, Qt_MERT, MB_ETy, Lambda, eV0)\n\n return MB_EMTx, New_Qm, MB_ETx, New_Qt","sub_path":"src/Scripts/Cython/UTIL.py","file_name":"UTIL.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"347307951","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 8 15:41:03 2015\n\n@author: CPU\n\"\"\"\n\nimport urllib\nimport lxml.html as LH\nimport re\nimport datetime\nimport os\n###set filepath\nfilepath='/Users/CPU/Desktop/modeling_informatics_lab/mil_project/twitter_religion/study1-2_religious-text/data/'\n\n###----------Christian Texts----------###\n###preprocess text\nwith open('{}bible/preregex_project_gutenberg_of_the_king_james_bible_2015-11-25.txt'.format(filepath),'r') as f:\n bible=f.read()\none_linebreak=re.compile('(.)(\\n{1})(.)')\nsection_break=re.compile('(\\d{1,3}\\:)')\nmulti_linebreak=re.compile('(.)(\\n{2,})(.)')\nspace_behind_index=re.compile('(\\:\\d{1,3})((?i)[a-z])')\nbible=one_linebreak.sub(string=bible,repl=r'\\1 \\3')\nbible=section_break.sub(string=bible,repl=r'\\n\\1')\nbible=multi_linebreak.sub(string=bible,repl=r'\\1\\n\\3')\nbible=space_behind_index.sub(string=bible,repl=r'\\1 \\2')\nwith open('{}bible/preliwc_project_gutenberg_of_the_king_james_bible_{}.txt'.format(filepath,str(datetime.date.today())),'w') as f:\n f.write(bible)\n\n###make segments\nwith open('{}bible/preliwc_project_gutenberg_of_the_king_james_bible_2016-02-18.txt'.format(filepath),'r') as f:\n bible=f.read()\nbook_break=re.compile(r'.+\\n1\\:1\\D')\nbook_title=re.compile(r'(.+)(\\n1\\:1\\D)')\nbible_seg=book_break.split(string=bible)\ndel bible_seg[0]\nbible_title=book_title.findall(string=bible)\ntitles=[]\nfor title in bible_title:\n titles.append(re.sub(pattern=r'[\\:|\\s]+',repl='-',string=title[0]))\nif not os.path.exists('{}bible/bible_seg_{}/'.format(filepath,datetime.date.today())):\n os.mkdir('{}bible/bible_seg_{}/'.format(filepath,datetime.date.today()))\nfor book,title in zip(bible_seg,titles):\n with open('{}bible/bible_seg_{}/{}.txt'.format(filepath,datetime.date.today(),title),'w') as f:\n f.write('1:1 '+book+'\\n')\n\n###combine popular books in bible\n#for idx,line in enumerate(titles):\n# if 'Exod' in line:\n# print(idx,line)\n\nshort=[18,39,42,44,19,0,41,45,22,43,40]\nlong=[18,39,42,44,19,0,41,45,22,43,40,48,49,65,1]\npopular_idx=['short','long']\nfor length in popular_idx:\n popular_titles=[]\n popular_books=[]\n for idx in eval(length):\n popular_titles.append(titles[idx])\n popular_books.append(bible_seg[idx])\n for book,title in zip(popular_books,popular_titles):\n with open('{}bible/preliwc_bible_pop_{}_{}.txt'.format(filepath,length,datetime.date.today()),'a') as f:\n f.write('1:1 '+book+'\\n')\n if not os.path.exists('{}bible/bible_seg_pop_{}_{}/'.format(filepath,length,datetime.date.today())):\n os.mkdir('{}bible/bible_seg_pop_{}_{}/'.format(filepath,length,datetime.date.today()))\n for book,title in zip(popular_books,popular_titles):\n with open('{}bible/bible_seg_pop_{}_{}/{}.txt'.format(filepath,length,datetime.date.today(),title),'w') as f:\n f.write('1:1 '+book+'\\n')\n\n\n\n\n###----------Buddhist Texts----------###\n#####The Dhammapada\n###crawl text\nURL='http://www.fullbooks.com/The-Dhammapada.html'\ndata=urllib.request.urlopen(URL).read()\ndoc=LH.fromstring(data)\nDhammapada=doc.xpath(\"//font[@face='Arial']\")[1].text_content()\nwith open('{}buddhist_texts/raw_dhammapada_fullbooks_{}.txt'.format(filepath,str(datetime.date.today())),'w') as f:\n f.write(Dhammapada)\n\n###preprocess text\nwith open('{}buddhist_texts/preregex_dhammapada_fullbooks_2016-02-13.txt'.format(filepath),'r') as f:\n dha=f.read()\none_linebreak=re.compile('(.)(\\n{1})(.)')\nmulti_linebreak=re.compile('(.)(\\n{2,})(.)')\nchapter_break=re.compile('(Chapter)')\ndha=one_linebreak.sub(string=dha,repl=r'\\1 \\3')\ndha=multi_linebreak.sub(string=dha,repl=r'\\1\\n\\3')\ndha=chapter_break.sub(string=dha,repl=r'\\n\\1')\nwith open('{}buddhist_texts/preliwc_dhammapada_fullbooks_{}.txt'.format(filepath,str(datetime.date.today())),'w') as f:\n f.write(dha)\n\n\n#####Diamond Sutra\n###crawl text\nfor i in range(1,33):\n URL='http://www.diamond-sutra.com/diamond_sutra_text/page{}.html'.format(i)\n data=urllib.request.urlopen(URL).read()\n doc=LH.fromstring(data)\n with open('{}buddhist_texts/raw_diamond-sutra_{}.txt'.format(filepath,str(datetime.date.today())),'a') as f:\n f.write(doc.xpath(\"//td/h2\")[0].text_content()+'\\n')\n content=doc.xpath(\"//td/h1\")[0].getparent().findall(\".//p\")\n del content[-1]\n for line in content:\n f.write(line.text_content()+'\\n')\n print('chapter {} crawled.'.format(i))\n f.write('\\n')\n\n\n#####Lotus Sutra\n###crawl text\nfor i in range(1,28):\n URL='http://www.sacred-texts.com/bud/lotus/lot{:02d}.htm'.format(i)\n data=urllib.request.urlopen(URL).read()\n doc=LH.fromstring(data)\n with open('{}buddhist_texts/raw_lotus-sutra_{}.txt'.format(filepath,str(datetime.date.today())),'a') as f:\n title=doc.xpath(\"//h1\")\n for line in title:\n f.write(line.text_content()+'\\n')\n content=doc.xpath(\"//p\")\n del content[-1]\n for line in content:\n f.write(line.text_content()+'\\n')\n print('chapter {} crawled.'.format(i))\n f.write('\\n')\n\n\n#####Vimalakirti-Nirdesa Sutra\n###preprocess text\nvns=open('{}buddhist_texts/preregex_vimalakirti-nirdesa-sutra_2016-02-04.txt'.format(filepath),'r').read()\none_linebreak=re.compile('(.)(\\n{1})(.)')\nmulti_linebreak=re.compile('(.)(\\n{2,})(.)')\nvns=one_linebreak.sub(string=vns,repl=r'\\1 \\3')\nvns=multi_linebreak.sub(string=vns,repl=r'\\1\\n\\3')\nwith open('{}buddhist_texts/preliwc_vimalakirti-nirdesa-sutra_{}.txt'.format(filepath,str(datetime.date.today())),'w') as f:\n f.write(vns)\n\n#####Lam Rim Chen Mo\n###crawl text\nfor i in [1,3]:\n URL='https://archive.org/stream/TsongKhaPaTheGreatTreatiseOnTheStagesOfThePathToEnlightenmentVol3/Tsong-Kha-Pa_The%20Great%20Treatise%20on%20the%20Stages%20of%20the%20Path%20to%20Enlightenment%20Vol%20{}_djvu.txt'.format(i)\n data=urllib.request.urlopen(URL).read()\n doc=LH.fromstring(data)\n with open('{}buddhist_texts/raw_lamrim-chenmo_vol{}_{}.txt'.format(filepath,i,str(datetime.date.today())),'a') as f:\n f.write(doc.xpath(\"//pre\")[0].text_content()+'\\n')\n f.write('\\n')\n\n###preprocess text\n##vol1, vol3-1, vol3-2\nvols=['1','3-1','3-2']\nfor vol in vols:\n with open('{}buddhist_texts/preregex_lamrim-chenmo_vol{}_2016-02-13.txt'.format(filepath,vol),'r') as f:\n LRCM=f.read()\n one_linebreak=re.compile('(.)(\\n{1})(.)')\n multi_linebreak=re.compile('(.)(\\n{2,})(.)')\n LRCM=one_linebreak.sub(string=LRCM,repl=r'\\1 \\3')\n LRCM=multi_linebreak.sub(string=LRCM,repl=r'\\1\\n\\3')\n with open('{}buddhist_texts/preliwc_lamrim-chenmo_vol{}_{}.txt'.format(filepath,vol,str(datetime.date.today())),'w') as f:\n f.write(LRCM)\n\n\n#####The Tibetan Book of the Dead\n###preprocess text\nwith open('{}buddhist_texts/preregex_tibetan-book-of-the-dead_sacred-texts_2015-12-11.txt'.format(filepath),'r') as f:\n tbd=f.read()\none_linebreak=re.compile('(.)(\\n{1})(.)')\nmulti_linebreak=re.compile('(.)(\\n{2,})(.)')\ntbd=one_linebreak.sub(string=tbd,repl=r'\\1 \\3')\ntbd=multi_linebreak.sub(string=tbd,repl=r'\\1\\n\\3')\nwith open('{}buddhist_texts/preliwc_tibetan-book-of-the-dead_sacred-texts_{}.txt'.format(filepath,str(datetime.date.today())),'w') as f:\n f.write(tbd)\n\n\n###Combine all Buddhist Texts###\ndha=open('{}buddhist_texts/preliwc_dhammapada_fullbooks_2016-02-14.txt'.format(filepath),'r').read()\nds=open('{}buddhist_texts/preliwc_diamond-sutra_2016-02-03.txt'.format(filepath),'r').read()\nhs=open('{}buddhist_texts/preliwc_heart-sutra_thich-nhat-hanh_2016_02_03.txt'.format(filepath),'r').read()\nls=open('{}buddhist_texts/raw_lotus-sutra_2016-02-04.txt'.format(filepath),'r').read()\nvns=open('{}buddhist_texts/preliwc_vimalakirti-nirdesa-sutra_2016-02-14.txt'.format(filepath),'r').read()\nlrcm1=open('{}buddhist_texts/preliwc_lamrim-chenmo_vol1_2016-02-14.txt'.format(filepath),'r').read()\nlrcm31=open('{}buddhist_texts/preliwc_lamrim-chenmo_vol3-1_2016-02-14.txt'.format(filepath),'r').read()\nlrcm32=open('{}buddhist_texts/preliwc_lamrim-chenmo_vol3-2_2016-02-14.txt'.format(filepath),'r').read()\ntbd=open('{}buddhist_texts/preliwc_tibetan-book-of-the-dead_sacred-texts_2016-02-14.txt'.format(filepath),'r').read()\nwith open('{}buddhist_texts/preliwc_combined-buddhist-texts_{}.txt'.format(filepath,str(datetime.date.today())),'w') as f:\n f.write(dha+'\\n')\n f.write(ds+'\\n')\n f.write(hs+'\\n')\n f.write(ls+'\\n')\n f.write(vns+'\\n')\n f.write(lrcm1+'\\n')\n f.write(lrcm31+'\\n')\n f.write(lrcm32+'\\n')\n f.write(tbd+'\\n')\n\n\n###----------ltr6-20----------###\ntexts=[]\ntexts_names=[]\nbible_full_filenames=['preliwc_project_gutenberg_of_the_king_james_bible_2016-02-18','preliwc_bible_pop_long_2016-02-18','preliwc_bible_pop_short_2016-02-18']\nfor names in bible_full_filenames:\n texts.append(open('{}bible/{}.txt'.format(filepath,names)).read())\ntitles\nfor names in titles:\n texts.append(open('{}bible/bible_seg_2016-02-18/{}.txt'.format(filepath,names)).read())\nbuddha_filenames=['preliwc_combined-buddhist-texts_2016-02-14','preliwc_dhammapada_fullbooks_2016-02-14','preliwc_diamond-sutra_2016-02-03','preliwc_heart-sutra_thich-nhat-hanh_2016_02_03','preliwc_lamrim-chenmo_vol1_2016-02-14','preliwc_lamrim-chenmo_vol3-1_2016-02-14','preliwc_lamrim-chenmo_vol3-2_2016-02-14','preliwc_tibetan-book-of-the-dead_sacred-texts_2016-02-14','preliwc_vimalakirti-nirdesa-sutra_2016-02-14','raw_lotus-sutra_2016-02-04']\nfor names in buddha_filenames:\n texts.append(open('{}buddhist_texts/{}.txt'.format(filepath,names)).read())\ntexts_names=bible_full_filenames\ntexts_names.extend(titles)\ntexts_names.extend(buddha_filenames)\ntexts_names=[line+'.txt' for line in texts_names]\n\ndef ltr_re(target_art,results,ltr_len=[6,8,10,12,15,18,20]):\n for line in ltr_len:\n ltr_regex=re.compile(r'[\\s\\D\\W][\\w\\d]{'+str(line)+r',}[\\s\\D\\W]')\n results.update({'Ltr{}'.format(line):str(len(ltr_regex.findall(target_art)))})\nresults_list=[{} for text in texts]\nfor i,j,k in zip(texts,texts_names,results_list):\n k.update({'Filename_ltr':j})\n ltr_re(i,k)\n\nwith open('/Users/CPU/Desktop/modeling_informatics_lab/mil_project/twitter_religion/study1-2_religious-text/results/ltr_{}.txt'.format(datetime.date.today()),'w') as f:\n f.write('\\t'.join(results_list[0].keys()))\n f.write('\\n')\n for text in results_list:\n f.write('\\t'.join(text.values()))\n f.write('\\n')\n\n\n###----------negation examination----------###\nnegemo=open('/Users/CPU/Desktop/dict_negemo.txt','r').read()\nnegemo=re.sub(pattern=r'\\n+',repl=' ',string=negemo)\nnegemo=re.sub(pattern=r'\\s',repl='\\n',string=negemo)\nnegemo_list=negemo.split('\\n')\ndel(negemo_list[-1])\nposemo=open('/Users/CPU/Desktop/dict_posemo.txt','r').read()\nposemo=re.sub(pattern=r\"\\([\\w\\'\\s]+\\)\\slike\",repl='',string=posemo)\nposemo=re.sub(pattern=r'\\n+',repl=' ',string=posemo)\nposemo=re.sub(pattern=r'\\s',repl='\\n',string=posemo)\nposemo_list=posemo.split('\\n')\ndel(posemo_list[-1])\nposemo_list.append('like')\n\n\nout_fp='/Users/CPU/Desktop/modeling_informatics_lab/mil_project/twitter_religion/study1-2_religious-text/results/posemo/'\ntext_list=['preliwc_dhammapada_fullbooks_2016-02-14.txt','preliwc_diamond-sutra_2016-02-03.txt','preliwc_heart-sutra_thich-nhat-hanh_2016_02_03.txt','raw_lotus-sutra_2016-02-04.txt','preliwc_vimalakirti-nirdesa-sutra_2016-02-14.txt','preliwc_lamrim-chenmo_vol1_2016-02-14.txt','preliwc_lamrim-chenmo_vol3-1_2016-02-14.txt','preliwc_lamrim-chenmo_vol3-2_2016-02-14.txt','preliwc_tibetan-book-of-the-dead_sacred-texts_2016-02-14.txt']\nfor text in text_list:\n target_art=open('{}buddhist_texts/{}'.format(filepath,text),'r').read()\n target_art=re.findall(pattern=r\"([\\w\\d\\']+)\",string=target_art)\n for line in posemo_list:\n dict_word=line.replace('*','[\\w\\d]*')\n dict_word_re=re.compile(r\"\\b(?={0}[^\\']*){0}\\b\".format(dict_word),re.IGNORECASE)\n for idx2,line2 in enumerate(target_art):\n if dict_word_re.findall(line2):\n # print(dict_word_re.findall(line2))\n surround=target_art[idx2-5:idx2+6]\n with open('{}{}'.format(out_fp,text),'a') as f:\n f.write(' '.join(surround))\n f.write('\\n')\n\n\n","sub_path":"religious_texts_preprocess.py","file_name":"religious_texts_preprocess.py","file_ext":"py","file_size_in_byte":12136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"384339686","text":"import dashie.core as core\nimport dashie.db.db as dbfunc\n\nuser = dbfunc.User()\n\n\n@core.dashiefunc\nasync def serverlist(message, client):\n return\n\n\n@core.dashiefunc\nasync def rank(message, client):\n \"\"\"Admins only: Allows admin to change a users rank via text.\"\"\"\n content = message.content.split()\n role = client.utils.get(message.server.roles, name=content[2])\n author = message.author\n if author.id == 97003404601094144:\n await client.send_message(message.channel, 'Moving user...')\n await client.replace_roles(content[1], role)\n\n else:\n return\n","sub_path":"dashie/ranks.py","file_name":"ranks.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"3722205","text":"from flask import Flask, render_template, request\nfrom werkzeug.utils import secure_filename \nimport os\nimport zipfile\nfrom threading import Thread\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///data.db\"\ndb = SQLAlchemy(app)\n\nclass FileContent(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(300)) \n\nALLOWED_EXTENSION = set(['zip'])\napp.config['UPLOAD_FOLDER'] = 'uploads'\n\n#pengecekan file degan menggunakan rsplit\ndef allowed_file(filename):\n return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSION\n\n@app.route('/upload', methods=['GET', 'POST'])\ndef upload():\n if request.method == 'POST':\n\n file = request.files['file']\n\n if 'file' not in request.files:\n return render_template('upload.html')\n\n if file.filename == '':\n return render_template('upload.html')\n\n if file and allowed_file(file.filename):\n filename = secure_filename(file.filename)\n file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))\n \n #ekstrak file\n with zipfile.ZipFile('uploads'+'//'+filename) as zf:\n zf.extractall('uploads')\n\n #melihat isi file zip\n zfile = zf.namelist()\n z = (\"; \".join(zfile))\n\n #insert isi file zip ke db\n newFile = FileContent(name=z)\n db.session.add(newFile)\n db.session.commit()\n \n return 'file ' + filename +' di simpan' + ' kembali'\n\n return render_template('upload.html')\n threads = []\n for i in range(1):\n threads.append(Thread(target=upload))\n threads[-1].start()\n for thread in threads:\n thread.join()\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"94454451","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\ndef parsing(content):\n \n #print \"********************* SportsTeam ATTRS ******************************\"\n attrs = {}\n attrs_keys = {\\\n 'Name': ['/type/object/name'],\\\n 'Sport': ['/sports/sports_team/sport'],\\\n 'Arena': ['/sports/sports_team/arena_stadium'],\\\n 'Championships': ['/sports/sports_team/championships'],\\\n 'Founded': ['/sports/sports_team/founded'],\\\n 'Leagues': ['/sports/sports_team/league'],\\\n 'Locations': ['/sports/sports_team/location'],\\\n 'Coaches': ['/sports/sports_team/coaches'],\\\n 'Players_Roster': ['/sports/sports_team/roster'],\\\n 'Description': ['/common/topic/description']\\\n }\n \n #a dictioray key-values for each coach\n coachDic = {\\\n 'Name' : ['/sports/sports_team_coach_tenure/coach'],\\\n 'Position': ['/sports/sports_team_coach_tenure/position'],\\\n 'From/To':['/sports/sports_team_coach_tenure/from','/sports/sports_team_coach_tenure/to']\\\n }\n #a dictionary of key-value pairs for each roster\n rosterDic = {\\\n 'Name': ['/sports/sports_team_roster/player'],\\\n 'Position': ['/sports/sports_team_roster/position'],\\\n 'Number': ['/sports/sports_team_roster/number'],\\\n 'From/To': ['/sports/sports_team_roster/from','/sports/sports_team_roster/to']\\\n }\n \n content_keys = content.keys()\n \n #name of Sport team\n attrs ['Name'] = ''\n if attrs_keys['Name'][0] in content_keys:\n attrs['Name'] = content[attrs_keys['Name'][0]]['values'][0]['text']\n \n #type of sport\n attrs['Sport'] = ''\n if attrs_keys['Sport'][0] in content_keys:\n attrs['Sport'] = content[attrs_keys['Sport'][0]]['values'][0]['text']\n \n # Venue they play at\n attrs['Arena'] = ''\n if attrs_keys['Arena'][0] in content_keys:\n attrs['Arena'] = content[attrs_keys['Arena'][0]]['values'][0]['text']\n #saving Championships as a list of championships\n attrs['Championships'] = []\n if attrs_keys['Championships'][0] in content_keys:\n for champ in content[attrs_keys['Championships'][0]]['values']:\n attrs['Championships'].append(champ ['text'])\n \n #Frounded\n attrs['Founded'] = ''\n if attrs_keys['Founded'][0] in content_keys:\n attrs['Founded'] = content[attrs_keys['Founded'][0]]['values'][0]['text']\n \n #League\n attrs['Leagues'] = ''\n if attrs_keys['Leagues'][0] in content_keys:\n attrs['Leagues'] = content[attrs_keys['Leagues'][0]]['values'][0]['property']['/sports/sports_league_participation/league']['values'][0]['text']\n \n #Location\n attrs ['Locations'] = ''\n if attrs_keys['Locations'][0] in content_keys:\n attrs['Locations'] = content[attrs_keys['Locations'][0]]['values'][0]['text']\n \n #Coaches in a list of coaches with each coach represented in a dictionary, with keys Name, Position, From/To\n attrs['Coaches'] = []\n if attrs_keys['Coaches'][0] in content_keys:\n for coach in content[attrs_keys['Coaches'][0]]['values']:\n coachKeys = coach['property'].keys()\n eachCoach = {}\n #Coach Name\n eachCoach['Name']=''\n if coachDic['Name'][0] in coachKeys:\n eachCoach['Name'] = coach['property'][coachDic['Name'][0]]['values'][0]['text']\n #Coach Postion\n eachCoach['Position'] = ''\n if coachDic['Position'][0] in coachKeys:\n eachCoach['Position'] = coach['property'][coachDic['Position'][0]]['values'][0]['text']\n #Coqch From/To\n eachCoach['From/To'] = ''\n if coachDic['From/To'][0] in coachKeys:\n coach_obj = (coach['property'][coachDic['From/To'][0]]).get('values', None)\n if (coach_obj != None and len(coach_obj) != 0):\n eachCoach['From/To'] += coach['property'][coachDic['From/To'][0]]['values'][0]['text']\n if coachDic['From/To'][1] in coachKeys:\n eachCoach['From/To'] += ' / '\n coach_obj = (coach['property'][coachDic['From/To'][1]]).get('values', None)\n if ( len(coach_obj) != 0 and coach_obj != None):\n eachCoach['From/To'] += coach['property'][coachDic['From/To'][1]]['values'][0]['text']\n elif eachCoach['From/To'] != '':\n eachCoach['From/To'] += 'now'\n elif eachCoach['From/To'] != '':\n eachCoach['From/To'] += ' / now'\n \n attrs['Coaches'].append(eachCoach)\n\n \n \n #Players_Roster is a list, each player represented in a dictionary, position in each dictionary is a list of positions\n #everything else is just string\n attrs['Players_Roster'] = []\n if attrs_keys['Players_Roster'][0] in content_keys:\n for roster in content[attrs_keys['Players_Roster'][0]]['values']:\n rosterKeys = roster['property'].keys()\n eachRoster = {}\n \n #Roster Name\n eachRoster['Name'] = ''\n if rosterDic['Name'][0] in rosterKeys:\n eachRoster['Name'] = roster['property'][rosterDic['Name'][0]]['values'][0]['text']\n eachRoster['Position'] = ''\n \n #Roster Position\n eachRoster['Position'] = ''\n positions = []\n if rosterDic['Position'][0] in rosterKeys:\n for position in roster['property'][rosterDic['Position'][0]]['values']:\n positions.append(position['text'])\n eachRoster['Position'] = ', '.join(positions)\n \n #Roster Number\n eachRoster['Number'] = ''\n if rosterDic['Number'][0] in rosterKeys:\n Number = roster['property'][rosterDic['Number'][0]].get('values',None)\n if len(Number) != 0 and Number != None:\n eachRoster['Number'] = roster['property'][rosterDic['Number'][0]]['values'][0]['text']\n\n #Roster From/To\n eachRoster['From/To'] = ''\n if rosterDic['From/To'][0] in rosterKeys:\n From = roster['property'][rosterDic['From/To'][0]].get('values', None)\n if len(From) != 0 and From != None:\n eachRoster['From/To'] += roster['property'][rosterDic['From/To'][0]]['values'][0]['text']\n if rosterDic['From/To'][1] in rosterKeys:\n To = roster['property'][rosterDic['From/To'][1]].get('values', None)\n if len(To) !=0 and To != None:\n eachRoster['From/To'] += ' / '\n eachRoster['From/To'] += roster['property'][rosterDic['From/To'][1]]['values'][0]['text']\n elif eachRoster['From/To'] != '':\n eachRoster['From/To'] += 'now'\n elif eachRoster['From/To'] != '':\n eachRoster['From/To'] += ' / now'\n \n attrs['Players_Roster'].append(eachRoster)\n \n #Description\n attrs ['Description'] = ''\n if attrs_keys['Description'][0] in content_keys:\n attrs['Description'] = content[attrs_keys['Description'][0]]['values'][0]['value']\n \n return attrs","sub_path":"sportsTeam_attr_extraction.py","file_name":"sportsTeam_attr_extraction.py","file_ext":"py","file_size_in_byte":7147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"214036561","text":"import itertools\nimport string\ndef _ord(a):\n if ord(a) in range(48,58):\n return ord(a)-48\n return ord(a)-55\n\ndef check(s):\n l = len(s)\n v2 = 0\n for i in range(l-1):\n v2 += (_ord(s[i])+1)*(i+1)\n x = (v2%36) - (_ord(s[l-1]))\n return x\n\ns = string.ascii_uppercase + \"0123456789\"\n\nfor comb in itertools.combinations(s, 16):\n if check(''.join(comb)) == 0:\n print(''.join(comb))\n ","sub_path":"picoctf18/keygenme1/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"37340388","text":"from typing import Callable, Optional\n\n\nclass Solution:\n def subsets(self, nums: list[int]) -> list[list[int]]:\n subsets: list[list[int]] = [[]]\n\n for num in nums:\n subsets_with_num = [subset + [num] for subset in subsets]\n subsets += subsets_with_num\n\n return subsets\n\n\ntests = [\n (\n ([1, 2, 3],),\n [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]],\n ),\n (\n ([0],),\n [[], [0]],\n ),\n]\n\n\ndef validator(\n subsets: Callable[[list[int]], list[list[int]]],\n inputs: tuple[list[int]],\n expected: list[list[int]],\n) -> None:\n nums, = inputs\n output = subsets(nums)\n output.sort()\n expected.sort()\n assert output == expected, (output, expected)\n","sub_path":"subsets_alt.py","file_name":"subsets_alt.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"392466740","text":"import argparse\nfrom torch import nn\nfrom torch import optim\nimport model as mod\nimport utilities as util\n\ndef main():\n in_arg = get_input_args() # Creates and returns command line arguments\n\n print('\\nPath To Image:\\n', in_arg.path_to_image, '\\n', '\\nCheckpoint:\\n', in_arg.checkpoint, '\\n')\n \n print('Optional Command Line Arguments:\\n', 'Top K [--top_k]: ', in_arg.top_k, '\\n', 'Category Names [--category_names]: ', in_arg.category_names, '\\n', 'GPU [--gpu]: ', in_arg.gpu, '\\n')\n\n label_count, hidden_units, arch, class_to_idx, classifier_state_dict, epochs = mod.load_checkpoint(in_arg.checkpoint, in_arg.gpu) # Load checkpoint\n \n model = mod.build_model(label_count, hidden_units, arch, class_to_idx) # Build model\n \n model.classifier.load_state_dict(classifier_state_dict)\n criterion = nn.NLLLoss()\n \n image = util.process_image(in_arg.path_to_image) # Pre-process image\n \n labels = util.get_labels(in_arg.category_names) # Get dict of categories mapped to real names\n \n mod.predict(image, model, labels, in_arg.top_k, in_arg.gpu) # Prints Top K Labels and Probabilities \n\ndef get_input_args():\n parser = argparse.ArgumentParser() # Creates the command line argument parser\n parser.add_argument('path_to_image', type=str) # Required Argument\n parser.add_argument('checkpoint', type=str) # Required Argument\n parser.add_argument('--top_k', type=int, default=1,\n help='Set K for Top K most likely classes') # Optional Argument\n parser.add_argument('--category_names', type=str, default = None, \n help='Filepath of JSON object for mapping of categories to real names') # Optional Argument\n parser.add_argument('--gpu', action='store_true', default=False,\n help='Use GPU (True or False)') # Optional Argument\n return parser.parse_args() # Returns collection of parsed arguments\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"540642267","text":"import collections\n\nfrom flask import request\nfrom flask_login import login_required\nfrom flask_restful import Resource, marshal, marshal_with\n\nfrom app import db\nfrom app.authentications.decorators import user_has\nfrom app.services.forms.leads import CreateLeadForm, EditLeadForm\nfrom app.services.models.service import Service\nfrom app.services.models.offer import ServiceOffer\nfrom app.services.models.patient import Patient\nfrom app.services.models.lead import Lead\nfrom app.services.repositories import LeadRepo, PatientRepo, ServiceRepo, ServiceOfferRepo\nfrom app.services.permissions import Leads\nfrom ..helpers import *\n\nleadRepo = LeadRepo(db, Lead)\n\npatientRepo = PatientRepo(db, Patient)\nserviceRepo = ServiceRepo(db, Service)\nserviceOfferRepo = ServiceOfferRepo(db, ServiceOffer)\n\nlead_fields = collections.OrderedDict()\n\npatient_fields = {\n 'id': fields.Integer(default=None),\n 'name': fields.String,\n 'mobileNumber': fields.String\n}\n\nidName_fields = {\n 'id': fields.Integer(default=None),\n 'name': fields.String\n}\n\nlead_fields['id'] = fields.Integer()\nlead_fields['createdBy_id'] = fields.Integer\nlead_fields['issueDateTime'] = fields.DateTime(dt_format='iso8601')\nlead_fields['service_id'] = fields.Integer\nlead_fields['serviceOffer_id'] = fields.Integer(default=None)\nlead_fields['serviceOrder_id'] = fields.Integer(default=None)\nlead_fields['patient_id'] = fields.Integer\nlead_fields['notes'] = fields.String\n\nlead_fields['service'] = fields.Nested(idName_fields)\nlead_fields['createdBy'] = fields.Nested(idName_fields)\nlead_fields['patient'] = fields.Nested(patient_fields)\nlead_fields['serviceOffer'] = fields.Nested(idName_fields)\n\nserviceOrders_fields = dict(paginate_fields)\nserviceOrders_fields['items'] = fields.List(fields.Nested(lead_fields))\n\n\nclass LeadApi(Resource):\n @login_required\n @user_has(Leads.show)\n @marshal_with(lead_fields)\n def get(self, id):\n entity = leadRepo.get(id)\n if entity is None:\n return notFoundResponse()\n return entity\n\n @login_required\n def delete(self, id):\n entity = leadRepo.get(id)\n if entity is None:\n return notFoundResponse()\n\n if isSuperUser():\n leadRepo.remove(entity)\n else:\n return notAuthorizedResponse()\n\n return successResponse()\n\n @login_required\n @user_has(Leads.update)\n def put(self, id):\n entity = leadRepo.get(id)\n if entity is None:\n return notFoundResponse()\n\n form = EditLeadForm(obj=entity)\n\n if form.validate():\n form.populate_obj(entity)\n\n leadRepo.save(entity)\n return successResponse()\n\n return unableToProcessResponse(form.errors)\n\n\nclass LeadsApi(Resource):\n @login_required\n @user_has(Leads.list)\n def get(self):\n\n # handle pagination\n parser = paginageParser.copy()\n parser.add_argument('patient_id', type=int)\n parser.add_argument('service_id', type=int)\n parser.add_argument('serviceOffer_id', type=int)\n parser.add_argument('issueDateTime', type=str)\n\n args = parser.parse_args()\n page = args.get('page')\n limit = args.get('limit')\n\n patient_id = args.get('patient_id')\n issueDateTime = args.get('issueDateTime')\n service_id = args.get('service_id')\n serviceOffer_id = args.get('serviceOffer_id')\n\n # handle search\n q = request.args.get('q')\n\n if patient_id:\n leadRepo.addFilter((Lead.patient_id == patient_id))\n\n if issueDateTime:\n leadRepo.addFilter((Lead.issueDateTime == issueDateTime))\n\n if service_id:\n leadRepo.addFilter((Lead.service_id == service_id))\n\n if serviceOffer_id:\n leadRepo.addFilter((Lead.serviceOffer_id == serviceOffer_id))\n\n if q:\n return marshal([entity for entity in\n leadRepo.search(q)], lead_fields)\n\n return marshal(leadRepo.paginate(page, limit, False), serviceOrders_fields)\n\n @login_required\n @user_has(Leads.create)\n def post(self):\n doer = getTheDoer()\n form = CreateLeadForm()\n\n if doer is None:\n return unableToProcessResponse([\"user is required\"])\n\n if form.validate():\n patient = None\n if form.data['patient_id']:\n patient = patientRepo.get(form.data['patient_id'])\n\n service = serviceRepo.get(form.data['service_id'])\n\n serviceOffer = None\n if form.data['serviceOffer_id'] is not None:\n serviceOffer = ServiceOffer.query.get(\n form.data['serviceOffer_id'])\n\n if patient is None:\n patient = Patient(\n name=form.data['name'], mobileNumber=form.data['mobileNumber'], createdBy=doer)\n\n try:\n entity = Lead(patient=patient, service=service,\n serviceOffer=serviceOffer, createdBy=doer, notes=form.data['notes'])\n\n leadRepo.save(entity)\n return createdResponseWithPayload(marshal(entity, lead_fields))\n except ValueError as err:\n return unableToProcessResponse([err.args[0]])\n\n return unableToProcessResponse(form.errors)\n\n\nclass UnclosedLeadsApi(Resource):\n @login_required\n @user_has(Leads.list)\n def get(self):\n\n # handle pagination\n parser = paginageParser.copy()\n parser.add_argument('patient_id', type=int, required=True)\n parser.add_argument('service_id', type=int, required=True)\n parser.add_argument('serviceOffer_id', type=int)\n\n args = parser.parse_args()\n page = args.get('page')\n limit = args.get('limit')\n\n patient_id = args.get('patient_id')\n service_id = args.get('service_id')\n serviceOffer_id = args.get('serviceOffer_id')\n\n result = leadRepo.unclosed(service_id=service_id, serviceOffer_id=serviceOffer_id, patient_id=patient_id)\n\n return marshal(result, lead_fields)\n","sub_path":"app/api/resources/leads.py","file_name":"leads.py","file_ext":"py","file_size_in_byte":6083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"314251074","text":"#!/usr/bin/env python\n# vi:si:et:sw=4:sts=4:ts=4\n# encoding: utf-8\n\ntry:\n from setuptools import setup\nexcept:\n from distutils.core import setup\n\ndef get_revision():\n import subprocess\n return subprocess.check_output(['git', 'rev-list', 'HEAD', '--count']).decode().strip()\n\ndef get_version():\n return '2.3.904' #import os\n import re\n _git = os.path.join(os.path.dirname(__file__), '.git')\n __version = os.path.join(os.path.dirname(__file__), 'ox/__version.py')\n changelog = os.path.join(os.path.dirname(__file__), 'debian/changelog')\n if os.path.exists(_git):\n rev = get_revision()\n if rev:\n version = \"2.3.%s\" % rev\n with open(__version, 'w') as fd:\n fd.write('VERSION=\"%s\"' % version)\n return version\n elif os.path.exists(__version):\n with open(__version) as fd:\n data = fd.read().strip().split('\\n')[0]\n version = re.compile('VERSION=\"(.*)\"').findall(data)\n if version:\n version = version[0]\n return version\n elif os.path.exists(changelog):\n f = open(changelog)\n head = f.read().strip().split('\\n')[0]\n f.close()\n rev = re.compile('\\d+\\.\\d+\\.(\\d+)').findall(head)\n if rev:\n return '2.3.%s' % rev[0]\n return '2.3.x'\n\n\nsetup(\n name=\"ox\",\n version=get_version(),\n description=\"python-ox - the web in a dict\",\n author=\"0x2620\",\n author_email=\"0x2620@0x2620.org\",\n url=\"https://code.0x2620.org/0x2620/python-ox\",\n license=\"GPLv3\",\n packages=['ox', 'ox.torrent', 'ox.web'],\n install_requires=['six>=1.5.2', 'chardet'],\n keywords=[\n ],\n classifiers=[\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ],\n)\n\n","sub_path":"pypi_install_script/ox-2.3.904.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"518706679","text":"'''\nCreated on Jan 13, 2017\n\n@author: Cristian\n'''\n\nfrom Ui import *\n\nrepo1 = BusRepository()\nrepo2 = RouteRepository()\n\nrepo1.readFromFile(\"Bus\")\nrepo2.readFromFile(\"Route\")\n\ncontroller = Controller(repo1,repo2)\n\nui = Ui(controller)\n\nui.menu()\n\nrepo1.writeToFile(\"Bus\")\nrepo2.writeToFile(\"Route\")","sub_path":"FP/Test2/Run.py","file_name":"Run.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"373898278","text":"import logging\nimport os\nimport signal\nimport threading\nfrom collections import namedtuple, deque, defaultdict\nfrom fnmatch import fnmatch\n\nfrom sqlalchemy import or_\nfrom sqlalchemy.orm import joinedload\n\nimport slivka.utils\nfrom slivka.db import Session, start_session\nfrom slivka.db.models import Request, File\nfrom slivka.scheduler.exceptions import QueueBrokenError, \\\n QueueTemporarilyUnavailableError, QueueError\nfrom slivka.scheduler.execution_manager import RunnerFactory\nfrom slivka.utils import JobStatus\n\nRunnerRequestPair = namedtuple('RunnerRequestPair', ['runner', 'request'])\nJobHandlerRequestPair = namedtuple('JobHandlerRequestPair',\n ['job_handler', 'request'])\n\n\nclass Scheduler:\n \"\"\"Scans the database for new tasks and dispatches them to executors.\n\n A single object of this class is created when the scheduler is started from\n the command line using ``manage.py scheduler``. Having been started, it\n repeatedly polls the database for new job requests. When a pending request\n is found, it is started with an appropriate executor\n \"\"\"\n\n def __init__(self):\n self._logger = logging.getLogger(__name__)\n self._shutdown_event = threading.Event()\n self._running_jobs = defaultdict(set)\n self._running_jobs_lock = threading.RLock()\n self._pending_runners = deque()\n\n self._runner_factories = {\n conf.service: RunnerFactory.new_from_configuration(\n conf.execution_config)\n for conf in slivka.settings.service_configurations.values()\n }\n self._restore_runners()\n self._restore_jobs()\n\n self._watcher_thread = threading.Thread(\n target=self._database_watcher_loop,\n name=\"PollThread\"\n )\n self._runner_thread = threading.Thread(\n target=self._runner_observer_loop,\n name=\"CollectorThread\"\n )\n\n def _restore_runners(self):\n \"\"\"Restores runners that has been prepared, but not submitted.\"\"\"\n with start_session() as session:\n accepted_requests = (\n session.query(Request)\n .options(joinedload('options'))\n .filter_by(status_string=JobStatus.ACCEPTED.value)\n .all()\n )\n for request in accepted_requests:\n runner = self._build_runner(request, new_cwd=False)\n if runner is None:\n request.status = JobStatus.ERROR\n self.logger.warning('Runner cannot be restored.')\n else:\n self._pending_runners.append(\n RunnerRequestPair(runner, request)\n )\n session.commit()\n\n def _restore_jobs(self):\n \"\"\"Recreated hob handlers from currently running requests.\"\"\"\n with start_session() as session:\n running_requests = (\n session.query(Request)\n .filter(or_(Request.status_string == JobStatus.RUNNING.value,\n Request.status_string == JobStatus.QUEUED.value))\n .all()\n )\n for request in running_requests:\n job_handler = (self._runner_factories[request.service]\n .get_runner_class(request.run_configuration)\n .get_job_handler_class()\n .deserialize(request.serial_job_handler))\n if job_handler is not None:\n job_handler.cwd = request.working_dir\n runner_class = (\n self._runner_factories[request.service]\n .get_runner_class(request.run_configuration)\n )\n job_handler.runner_class = runner_class\n self._running_jobs[runner_class].add(\n JobHandlerRequestPair(job_handler, request)\n )\n else:\n request.status = JobStatus.UNDEFINED\n session.commit()\n\n def register_terminate_signal(self, *signals):\n for sig in signals:\n signal.signal(sig, self.terminate_signal_handler)\n\n def terminate_signal_handler(self, _signum, _frame):\n self.logger.warning(\"Termination signal received.\")\n self.stop()\n\n def start(self, block=True):\n \"\"\"Start the scheduler and it's working threads.\n\n It launches poller and collector threads of the scheduler which scan\n the database and dispatch the tasks respectively. If ``async``\n parameter is set to ``False``, it blocks until keyboard interrupt\n signal is received. After that, it stops the polling and collecting\n threads and join them before returning.\n\n Setting ``block`` to ``False`` will cause the method to return\n immediately after spawning collector and poll threads which will\n run in the background. When started asynchronously, the scheduler's\n shutdown method shoud be called manually by the main thread.\n This option is especially usefun in interactive debugging of testing.\n\n :param block: whether the scheduler should block\n \"\"\"\n self._watcher_thread.start()\n self._runner_thread.start()\n if block:\n self.logger.info(\"Child threads started. Press Ctrl+C to quit\")\n try:\n while self.is_running:\n self._shutdown_event.wait(1)\n except KeyboardInterrupt:\n self.logger.info(\"Keyboard Interrupt; Shutting down...\")\n self.stop()\n finally:\n self.shutdown()\n self.logger.info(\"Finished\")\n\n def stop(self):\n self._shutdown_event.set()\n\n def shutdown(self):\n \"\"\"\n Sends shutdown signal and starts exit process.\n \"\"\"\n if self.is_running:\n raise RuntimeError(\"Can't shutdown while running\")\n self._shutdown_event.set()\n self.logger.debug(\"Shutdown event set\")\n self.join()\n\n def join(self):\n \"\"\"\n Blocks until scheduler stops working.\n \"\"\"\n self._runner_thread.join()\n self._watcher_thread.join()\n\n def _database_watcher_loop(self):\n \"\"\"\n Keeps checking database for pending requests.\n Submits a new job if one is found.\n \"\"\"\n self.logger.info(\"Scheduler is watching database.\")\n while self.is_running:\n session = Session()\n pending_requests = (\n session.query(Request)\n .options(joinedload('options'))\n .filter_by(status_string=JobStatus.PENDING.value)\n .all()\n )\n runners = []\n for request in pending_requests:\n self.logger.debug('Processing request %r', request)\n try:\n runner = self._build_runner(request)\n if runner is None:\n raise QueueError('Runner could not be created')\n runner.prepare()\n request.run_configuration = runner.configuration.name\n request.status = JobStatus.ACCEPTED\n request.working_dir = runner.cwd\n runners.append(RunnerRequestPair(runner, request))\n except Exception:\n request.status = JobStatus.ERROR\n self.logger.exception(\"Setting up the runner failed.\")\n finally:\n session.commit()\n session.close()\n self._pending_runners.extend(runners)\n self._shutdown_event.wait(0.5)\n\n def _build_runner(self, request, new_cwd=True):\n values = {\n option.name: option.value\n for option in request.options\n }\n runner_factory = self._runner_factories[request.service]\n if new_cwd:\n cwd = os.path.join(slivka.settings.WORK_DIR, request.uuid)\n else:\n cwd = request.working_dir\n return runner_factory.new_runner(values, cwd)\n\n def _runner_observer_loop(self):\n try:\n while self.is_running:\n self._submit_runners()\n self._update_job_statuses()\n self._shutdown_event.wait(0.5)\n except Exception:\n self.logger.exception(\n 'Critical error occurred, scheduler shuts down'\n )\n self.shutdown()\n\n def _submit_runners(self):\n retry_runners = []\n session = Session()\n try:\n while self._pending_runners:\n runner, request = self._pending_runners.popleft()\n session.add(request)\n try:\n job_handler = runner.start()\n self.logger.info('Job submitted')\n except QueueTemporarilyUnavailableError:\n retry_runners.append(RunnerRequestPair(runner, request))\n self.logger.info('Job submission deferred')\n except QueueError:\n request.status = JobStatus.ERROR\n self.logger.exception(\n 'Job cannot be scheduled due to the queue error'\n )\n else:\n request.status = JobStatus.QUEUED\n request.serial_job_handler = job_handler.serialize()\n with self._running_jobs_lock:\n self._running_jobs[runner.__class__].add(\n JobHandlerRequestPair(job_handler, request)\n )\n finally:\n session.commit()\n session.close()\n self._pending_runners.extend(retry_runners)\n\n def _update_job_statuses(self):\n session = Session()\n self._running_jobs_lock.acquire()\n try:\n for runner_class, jobs in self._running_jobs.items():\n if not jobs:\n continue\n disposable_jobs = set()\n handlers = [job.job_handler for job in jobs]\n try:\n statuses = dict(runner_class.get_job_status(handlers))\n for job in jobs:\n handler, request = job\n session.add(request)\n request.status = statuses[handler]\n skip_paths = {f.path for f in request.files}\n request.files.extend(\n self._collect_output_files(\n request.service, handler.cwd, skip_paths\n )\n )\n if request.is_finished():\n self.logger.info('Job finished')\n disposable_jobs.add(job)\n except QueueTemporarilyUnavailableError:\n self.logger.warning('Queue not available')\n except QueueBrokenError:\n for job in jobs:\n job.request.status = JobStatus.UNDEFINED\n self.logger.exception('Could not retrieve job status.')\n disposable_jobs.add(job)\n jobs.difference_update(disposable_jobs)\n except Exception:\n self.logger.exception(\n 'Critical error occurred, scheduler shuts down'\n )\n self.shutdown()\n finally:\n self._running_jobs_lock.release()\n session.commit()\n session.close()\n\n def _collect_output_files(self, service, cwd, skip_paths=set()):\n results = self._runner_factories[service].results\n return [\n File(path=entry.path, mimetype=result.mimetype)\n for entry in slivka.utils.recursive_scandir(cwd)\n for result in results\n if ((entry.path not in skip_paths) and\n fnmatch(os.path.relpath(entry.path, cwd), result.path))\n ]\n\n @property\n def logger(self):\n \"\"\"\n :return: current scheduler logger\n \"\"\"\n return self._logger\n\n @property\n def is_running(self):\n \"\"\"\n :return: if the scheduler is currently running.\n :rtype: bool\n \"\"\"\n return not self._shutdown_event.is_set()\n","sub_path":"slivka/scheduler/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":12424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"182132644","text":"#!/usr/bin/env python3\nimport copy\nfrom itertools import product\n\n\ndef num_adjacent_occupied(seats, row, column):\n nrows, ncols, num = len(seats), len(seats[0]), 0\n for i, j in product((-1, 0, 1), (-1, 0, 1)):\n if i == 0 and j == 0:\n continue\n x, y = row + i, column + j\n if x < 0 or x >= nrows or y < 0 or y >= ncols:\n continue\n if seats[x][y] == \"#\":\n num += 1\n return num\n\n\ndef update(seats, row, column):\n if seats[row][column] == \"L\" and num_adjacent_occupied(seats, row, column) == 0:\n return \"#\"\n if seats[row][column] == \"#\" and num_adjacent_occupied(seats, row, column) >= 4:\n return \"L\"\n return seats[row][column]\n\n\ndef apply_rules(seats):\n nrows, ncols = len(seats), len(seats[0])\n new = copy.deepcopy(seats)\n for i in range(nrows):\n for j in range(ncols):\n new[i][j] = update(seats, i, j)\n return new\n\n\ndef run(seats):\n previous, step = [], 0\n while seats != previous:\n previous, seats = copy.deepcopy(seats), apply_rules(seats)\n step += 1\n print(step)\n num_occupied = sum(1 if seat == \"#\" else 0 for row in seats for seat in row)\n print(\"\\n\".join(\"\".join(s) for s in seats))\n return num_occupied\n\n\nif __name__ == \"__main__\":\n seats = list(map(list, open(\"input\").read().splitlines()))\n print(run(seats))\n","sub_path":"2020/11/sol1.py","file_name":"sol1.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"469773686","text":"#!/usr/bin/env python3\n\n\"\"\"\nTrain U-Nets using different depths\n\"\"\"\nimport os\n\nimport click\nimport numpy as np\nimport torch\n\nfrom unet.dataset import TessellationDataset, get_data_loaders\nfrom unet.unet import make_unet\nfrom unet.train import training_loop, test_unet\nfrom unet.utils import select_torch_device\n\n\ndef load_dataset(basepath):\n \"\"\"\n Load the tessellation dataset and return dataloaders\n \"\"\"\n dataset = TessellationDataset(basepath)\n train_loader, val_loader, test_loader = get_data_loaders(\n dataset, val_ratio=0.2, test_ratio=0.2, batch_size=32\n )\n return train_loader, val_loader, test_loader\n\n\ndef train_models(depths, train_loader, val_loader, test_loader, device, outpath):\n \"\"\" Train U-Nets with different depths \"\"\"\n width = 3\n patience = 20\n\n for depth in depths:\n unet, criterion, optim = make_unet(\n depth, wf=width, padding=True, batch_norm=True, device=device\n )\n\n train_results = training_loop(\n patience,\n unet,\n criterion,\n optim,\n train_loader,\n val_loader,\n verbose=True,\n device=device,\n )\n test_results = test_unet(unet, criterion, test_loader, device=device)\n\n results = {\n \"width\": width,\n \"depth\": depth,\n \"unet\": unet.state_dict(),\n \"train\": train_results,\n \"test\": test_results,\n }\n torch.save(results, os.path.join(outpath, f\"unet-{depth}.torch\"))\n\n\n@click.command()\n@click.option(\"--datapath\", \"-d\", required=True)\n@click.option(\"--outpath\", \"-o\", default=\"./\")\n@click.option(\"--device\")\ndef main(datapath, outpath, device):\n \"\"\" Main \"\"\"\n if device is None:\n device = select_torch_device()\n print(f\"Torch device: {device}\")\n\n dataloaders = load_dataset(datapath)\n print(\"Dataset loaded\")\n\n depths = np.arange(1, 5)\n train_models(depths, *dataloaders, device=device, outpath=outpath)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"2_unet_depth/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"327887743","text":"#\n# @lc app=leetcode id=16 lang=python3\n#\n# [16] 3Sum Closest\n#\n\n# @lc code=start\nfrom typing import List\nclass Solution:\n def threeSumClosest(self, nums: List[int], target: int) -> int:\n ans = 0x7fffffff\n sz = len(nums)\n nums.sort()\n for i in range(sz-2):\n if i > 0 and nums[i] == nums[i-1]:\n continue\n p = i + 1\n q = sz - 1\n b = True\n while p < q:\n tmp = nums[i] + nums[p] +nums[q]\n if abs(tmp - target) < abs(ans - target):\n ans = tmp\n if tmp == target:\n break\n elif tmp > target:\n q -= 1\n else:\n p += 1\n if ans == target:\n break\n return ans\n\n\n# @lc code=end\n\n","sub_path":"Difficulty/Medium/16.3-sum-closest.py","file_name":"16.3-sum-closest.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"653081359","text":"from .base import *\n\nDEBUG = False\n\n# Database\n# https://docs.djangoproject.com/en/1.11/ref/settings/#databases\n\n# CACHES = {\n# 'default': {\n# 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',\n# 'LOCATION': '/tmp/django_cache',\n# }\n# }\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django_redis.cache.RedisCache',\n 'LOCATION': 'redis://127.0.0.1:6379/4',\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n }\n }\n}\n\n# DATABASES = {\n# 'default': {\n# 'ENGINE': 'django.db.backends.sqlite3',\n# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n# }\n# }\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'typeidea',\n 'HOST': '127.0.0.1',\n 'USER': 'root',\n 'PASSWORD': 'wtf3512887',\n 'CONN_MAX_AGE': 60, # mysql允许连接60秒,可复用\n }\n }\n\nCKEDITOR_CONFIGS = {\n 'default': {\n 'toolbar': 'full',\n 'height': 300,\n 'width': 800,\n },\n}\n\nCKEDITOR_RESTRICT_BY_USER = True\nCKEDITOR_UPLOAD_PATH = 'content/ckeditor/'\n\nREST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',\n 'PAGE_SIZE': 1\n}\n\n# silk\nINSTALLED_APPS += ['silk']\nMIDDLEWARE += ['silk.middleware.SilkyMiddleware']\n","sub_path":"typeidea/typeidea/settings/line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"308197044","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('main', '0003_auto_20150818_1438'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='request',\n name='comment',\n field=models.TextField(max_length=30, default='', blank=True, verbose_name='Комментарий'),\n ),\n migrations.AlterField(\n model_name='request',\n name='phone',\n field=models.TextField(max_length=22, verbose_name='Телефон'),\n ),\n ]\n","sub_path":"main/migrations/0004_auto_20150818_1440.py","file_name":"0004_auto_20150818_1440.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"289855741","text":"'''\r\n\r\nIntroduction to Brian part 3: Simulations\r\n\r\nSimulating spikes using Brian\r\n\r\nhttps://github.com/brian-team/brian2/blob/master/tutorials/3-intro-to-brian-simulations.ipynb\r\n\r\n\r\n\r\n'''\r\n\r\nimport numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nfrom brian2 import *\r\nimport cv2\r\nfrom matplotlib.image import imread\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n #img = cv2.imread('brian.png' , 0)\r\n #print(img.T.shape , img.shape)\r\n\r\n img = imread('brian.png')\r\n\r\n print(img , img.shape)\r\n print(img[: : -1 , : , 0] , img[: : -1 , : , 1].shape)\r\n \r\n\r\n img_m = (1-imread('brian.png'))[::-1, :, 0].T\r\n\r\n num_samples , n = img_m.shape\r\n\r\n print(n)\r\n\r\n ta = TimedArray(img_m , dt = 1 * ms)\r\n #print(ta(1 * ms , 0))\r\n\r\n #img_m = (1-imread('brian.png'))[::-1, :, 0].T\r\n\r\n #print(img_m.shape)\r\n\r\n A = 1.5\r\n tau = 2 * ms\r\n eqs = '''\r\n dv/dt = (A * ta(t, i) - v)/tau + 0.8 * xi * tau**-0.5 : 1\r\n\r\n '''\r\n\r\n G = NeuronGroup(n , eqs ,\r\n threshold = 'v > 1',\r\n reset = 'v = 0',\r\n method = 'euler')\r\n\r\n M = SpikeMonitor(G)\r\n print(M.i[ : ] , M.t[ : ] , M.num_spikes)\r\n run(num_samples * ms)\r\n plt.plot(M.t/ms , M.i , '.k', ms = 3)\r\n plt.xlim(0 , num_samples)\r\n plt.ylim(0 , n)\r\n plt.xlabel('Time (ms)')\r\n plt.ylabel('Neuron index')\r\n plt.show()\r\n\r\n \r\n","sub_path":"b_snn_image.py","file_name":"b_snn_image.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"296384216","text":"import random as rnd\r\nimport os.path\r\n\r\n#Generer en random stokk for nytt spill\r\ndef genererSpill():\r\n sparSymbol = '\\u2660'\r\n ruterSymbol = '\\u2666'\r\n kløverSymbol = '\\u2663'\r\n hjerterSymbol = '\\u2665'\r\n tall = [7, 8, 9, 10, 'J', 'Q', 'K', 'A']\r\n symbol = [sparSymbol, kløverSymbol, hjerterSymbol, ruterSymbol]\r\n kortstokk = []\r\n stokk1 = []\r\n stokk2 = []\r\n stokk3 = []\r\n stokk4 = []\r\n stokk5 = []\r\n stokk6 = []\r\n stokk7 = []\r\n stokk8 = []\r\n\r\n nyttspill = [stokk1, stokk2, stokk3, stokk4, stokk5, stokk6, stokk7, stokk8]\r\n\r\n for i in tall:\r\n for j in symbol:\r\n kortstokk.append([j, i])\r\n\r\n for i in nyttspill:\r\n if len(kortstokk) > 0:\r\n while len(i) <= 3:\r\n x = rnd.choice(kortstokk)\r\n i.append(x)\r\n kortstokk.remove(x)\r\n\r\n return nyttspill\r\n\r\n#Skriver stokken for hver runde\r\ndef skriv_stokk(n):\r\n for i in n:\r\n\r\n if i == None:\r\n\r\n y = \"--\"\r\n return y\r\n elif i == []:\r\n\r\n z = \"--\"\r\n return z\r\n else:\r\n\r\n x = \"\".join(map(str, n[0]))\r\n return x\r\n\r\n#Sjekker om det er gyldige trekk igjen\r\ndef gyldig(n):\r\n teller = 0\r\n for i in n:\r\n if i == None:\r\n continue\r\n for j in n:\r\n if j == None:\r\n continue\r\n elif i[1] == j[1] and i != j:\r\n teller += 1\r\n if teller > 0:\r\n return True\r\n else:\r\n return False\r\n\r\n#Sjekker om input er gyldig\r\ndef inputValg():\r\n while True:\r\n input1 = input(\":\").upper()\r\n gyldiginput = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',\"LAGRE\"]\r\n\r\n if input1 == \"LAGRE\":\r\n return input1\r\n elif input1 in gyldiginput:\r\n return gyldiginput.index(input1)\r\n else:\r\n print(\"UGYLDIG INPUT! Velg bunke med bokstav fra A til H\")\r\n\r\n#Sjekker om spillet er vunnet eller tapt\r\ndef sjekkSpill(n):\r\n teller = 0\r\n for i in n:\r\n if i != []:\r\n teller += 1\r\n if teller > 0:\r\n print(\"Ingen flere mulig trekk. Du tapte!\")\r\n else:\r\n print(\"Gratulerer, du vant!\")\r\n\r\n#Skriver ut hvor mange kort som er igjen i hver bunke\r\ndef skrivBunkestørrelse(n):\r\n lst = []\r\n for i in n:\r\n lst.append(\" \"+str(len(i))+\" \")\r\n return lst\r\n\r\n#Lagrer spillet\r\ndef lagreSpill(n):\r\n dokument = open('dokument.txt','w')\r\n for i in n:\r\n for j in i:\r\n if j[0] == '\\u2663':\r\n dokument.write('klover '+ str(j[1])+'-')\r\n elif j[0] == '\\u2660':\r\n dokument.write('spar '+ str(j[1])+'-')\r\n elif j[0] == '\\u2666':\r\n dokument.write('ruter '+ str(j[1])+'-')\r\n elif j[0] == '\\u2665':\r\n dokument.write('hjerter '+ str(j[1])+'-')\r\n else:\r\n print(j)\r\n dokument.write('\\n')\r\n dokument.close()\r\n\r\n#Laster inn spillet\r\ndef lasteSpill():\r\n if os.path.exists('dokument.txt') == True:\r\n dokument = open('dokument.txt', 'r')\r\n lst = []\r\n for i in dokument:\r\n lst2 = []\r\n x = i.strip().split(\"-\")\r\n for j in x:\r\n y = j.strip().split()\r\n if len(y)>0:\r\n if y[0] == 'klover':\r\n lst2.append(['\\u2663',y[1]])\r\n elif y[0] == 'spar':\r\n lst2.append(['\\u2660',y[1]])\r\n elif y[0] == 'ruter':\r\n lst2.append(['\\u2666',y[1]])\r\n elif y[0] == 'hjerter':\r\n lst2.append(['\\u2665',y[1]])\r\n else:\r\n print(j)\r\n lst.append(lst2)\r\n return lst\r\n else:\r\n print(\"Finner ingen lagrede filer.\")\r\n\r\n\r\nwhile True:\r\n print(\"--------------\")\r\n print(\"1 - Nytt Spill\")\r\n print(\"2 - Last spill\")\r\n print(\"--------------\")\r\n valg = input(\":\")\r\n\r\n if int(valg) == 1: spill = genererSpill()\r\n elif int(valg) == 2: spill = lasteSpill()\r\n else: print(\"Ugyldig input. Velg 1 for nytt spill, eller 2 for å laste inn lagret spill\")\r\n\r\n fortsett = True\r\n lagret = False\r\n\r\n while fortsett == True:\r\n status = list(map(skriv_stokk, spill))\r\n status2 = []\r\n\r\n for i in status:\r\n if i == None:\r\n status2.append(\"--\")\r\n else:\r\n status2.append(i)\r\n\r\n fortsett = gyldig(status)\r\n\r\n print(\" A B C D E F G H \")\r\n print(status2)\r\n print(''.join(skrivBunkestørrelse(spill)))\r\n\r\n if fortsett == False: break\r\n print('Skriv \"Lagre\" for å lagre og avslutte spillet')\r\n print('Velg første bunke:')\r\n x = inputValg()\r\n\r\n if x == \"LAGRE\":\r\n lagreSpill(spill)\r\n lagret = True\r\n break\r\n\r\n print(\"Velg andre bunke\")\r\n y = inputValg()\r\n\r\n try:\r\n if status[x][1] == status[y][1]:\r\n spill[x].remove(spill[x][0])\r\n spill[y].remove(spill[y][0])\r\n else:\r\n print(\"Verdiene er ulike! Prøv på nytt\")\r\n except:\r\n print(\"Du har valgt en tom bunke! Prøv på nytt.\")\r\n\r\n if lagret is True:\r\n print(\"Spill lagret.\")\r\n else:\r\n sjekkSpill(spill)\r\n \r\n\r\n","sub_path":"solitaire_game.py","file_name":"solitaire_game.py","file_ext":"py","file_size_in_byte":5438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"434794182","text":"\"\"\" \n Here the main body of the graphical user interface (GUI) is build and \n configured. \n \n Three tabs are defined, each in there own function. The init function \n defines the different notebooks and tabs needed for the GUI. \n\"\"\"\n\ntry:\n from tkinter import *\n from tkinter import ttk\nexcept ImportError:\n from Tkinter import *\n import ttk\n \nimport programmer \n\nimport time\nimport csv\n\nclass ProgramView(Frame):\n \"\"\" \"\"\"\n \n def __init__(self, master, program):\n \"\"\" \"\"\"\n Frame.__init__(self, master)\n self.place(x=7,y=174)\n scrollbar = Scrollbar(master) \n scrollbar.pack(side=RIGHT, fill=Y)\n \n self.list = Listbox(master, selectmode=EXTENDED, width=64, height=29)\n self.list.pack(fill=BOTH, expand=1)\n self.current = None\n self.program = program\n self.program_len = program.numberOfCommands()\n self.poll()\n \n for ii, item in enumerate(self.program._program):\n self.list.insert(END,self.cmdLine2str(ii, item)) \n \n def poll(self):\n programLength = self.program.numberOfCommands()\n if programLength != self.program_len:\n print(\"program has changed\")\n self.program_len = programLength\n self.program_has_change()\n \n self.after(250, self.poll)\n \n def program_has_change(self):\n self.list.delete(0, END)\n for ii, item in enumerate(self.program._program):\n self.list.insert(END,self.cmdLine2str(ii, item)) \n self.list.pack()\n \n def cmdLine2str(self, ii, cmdLine):\n try:\n tmp = cmdLine.data.get()\n except AttributeError:\n tmp = str(cmdLine.data)\n \n return str(\"%d; %s: %s %s\" % (ii, cmdLine._desciption, cmdLine.comment, tmp))\n\nclass GuiAR2():\n \"\"\" The graphical interface of the robotic arm \"\"\"\n \n def __init__(self):\n \"\"\" \"\"\"\n self.root = Tk()\n self.root.wm_title(\"AR2 software 1.1\")\n self.root.iconbitmap(r'icons/AR2.ico')\n self.root.resizable(width=True, height=True)\n \n self._screen_width = self.root.winfo_screenwidth() - 15\n self._screen_height = self.root.winfo_screenheight() - 40\n \n self.root.geometry(str(self._screen_width)+'x'+str(self._screen_height)+'+0+0')\n\n self.root.runTrue = 0\n\n self.nb = ttk.Notebook(self.root, width=self._screen_width+15, height=self._screen_height)\n self.nb.place(x=0, y=0)\n\n self.tab1 = ttk.Frame(self.nb)\n self.nb.add(self.tab1, text=' Main Controls ')\n\n self.tab2 = ttk.Frame(self.nb)\n self.nb.add(self.tab2, text=' Calibration ')\n\n self.tab3 = ttk.Frame(self.nb)\n self.nb.add(self.tab3, text=' Inputs Outputs ')\n \n # TODO: split Main Controls in programming and robot status \n \n self.currentAngleEntryField = {}\n self.jogDegreesEntryField = {}\n \n self.currentPositionEntryField = {}\n self.jogPositionEntryField = {}\n \n self.progName = \"default\"\n self.programmer = programmer.Programmer(self.progName)\n\n def start(self):\n \"\"\" Start Main loop to get to program responsive \"\"\"\n \n self.tab1.mainloop()\n \n \n def updateProgramView(self): \n \"\"\" \"\"\"\n self.tab1.progView.delete(0, END)\n for ii, item in enumerate(self.programmer.program):\n disp_str = str(ii) + ';' + item._desciption + ': ' + str(item.data)\n self.tab1.progView.insert(END,disp_str) \n self.tab1.progView.pack()\n \n # self.tab1.progView.after(250, self.updateProgramView())\n \n def getCurrentSelection(self, var):\n \"\"\" \"\"\"\n try: \n self.selectedRow = self.tab1.progView.curselection()[0]\n except IndexError:\n self.selectedRow = -1\n\n \n def buttonCallBackAndUpdate(self, function):\n \"\"\" \"\"\"\n self.updateProgramView(self.tab1.progView)\n \n def CreateTab1(self):\n \"\"\" Main status and control tap is created here \"\"\"\n tab1 = self.tab1\n \n\n ProgEntryField = Entry(tab1,width=20)\n ProgEntryField.place(x=170, y=45)\n \n progframe=Frame(tab1)\n progframe.place(x=7,y=174)\n \n self.PV = ProgramView(progframe, self.programmer.program)\n # scrollbar = Scrollbar(progframe) \n # scrollbar.pack(side=RIGHT, fill=Y)\n # tab1.progView = Listbox(progframe ,width=64,height=29, yscrollcommand=scrollbar.set)\n \n # tab1.progView = Program_view(tab1)\n\n # time.sleep(.2)\n \n # tab1.progView.bind('<>', self.getCurrentSelection)\n \n # self.updateProgramView(tab1.progView)\n \n # scrollbar.config(command=tab1.progView.yview)\n \n # Create Labels\n LabelsTab1 = {}\n \n fileID = open('../conf/conf_tab1_labels.csv')\n csvID = csv.reader(fileID, delimiter=',')\n \n for row in csvID: \n LabelsTab1[row[0]] = Label(self.tab1, text=row[1])\n LabelsTab1[row[0]].place(x=row[2],y=row[3])\n \n if row[4] != 'none':\n LabelsTab1[row[0]]['bg'] = row[4]\n \n if row[5] != 'default':\n LabelsTab1[row[0]]['font'] = row[5]+row[6]\n \n fileID.close()\n \n # Joint labels\n joint_label = {}\n for ii in range(1,7):\n joint_label[ii] = Label(tab1, font=(\"Arial\", 18), text = \"J\" + str(ii))\n joint_label[ii].place(x=660+(ii-1)*90, y=5)\n\n\n ####STEPS LABELS BLUE######\n stepCol = \"SteelBlue4\"\n\n joint_step_label = {}\n joint_label2 = {}\n joint_str = [\" X\", \" Y\", \" Z\", \"Rx\", \"Ry\", \"Rz\"]\n for ii in range(1,7):\n joint_step_label[ii] = Label(tab1, font=(\"Arial\", 8), fg=stepCol, text = \"000\")\n joint_step_label[ii].place(x=695+(ii-1)*90, y=40)\n\n joint_label2[ii] = Label(tab1, font=(\"Arial\", 18), text = joint_str[ii-1])\n joint_label2[ii].place(x=660+(ii-1)*90, y=125)\n\n \n\n # register labels\n for ii in range(360, 521, 40):\n tmp = Label(tab1, text = \"=\")\n tmp.place(x=855, y=ii)\n\n tmp = Label(tab1, text = \"=\")\n tmp.place(x=1075, y=360)\n\n label_robot = {}\n \n for ii in range(1,9):\n label_robot[ii] = Label(tab1, text = \"R\" + str(ii))\n if ii < 5:\n label_robot[ii].place(x=1200, y=35+(ii-1)*40)\n else:\n label_robot[ii].place(x=1275, y=35+(ii-5)*40)\n\n\n ###BUTTONS##############################################################\n ########################################################################\n\n Buttons = {}\n \n fileID = open('../conf/conf_tab1_buttons.csv')\n csvID = csv.reader(fileID, delimiter=',')\n \n for row in csvID:\n Buttons[row[0]] = Button(tab1, width=row[1], height=row[2], bg=row[5], text=row[6])\n Buttons[row[0]].place(x=row[3], y=row[4])\n \n if row[7] != '':\n Buttons[row[0]]['command'] = getattr(self.programmer, row[7])\n \n\n Buttons['runProgBut'] = Button(tab1, height=1, width=10, text='run', command = self.programmer.run_program)\n # playPhoto=PhotoImage(file=\"icons/play-icon.gif\")\n # Buttons['runProgBut'].config(image=playPhoto,width=\"60\",height=\"60\")\n Buttons['runProgBut'].place(x=20, y=80)\n\n Buttons['stopProgBut'] = Button(tab1, height=1, width=10, text='stop', command = self.programmer.stop_program)\n # stopPhoto=PhotoImage(file=\"icons/stop-icon.gif\")\n # Buttons['stopProgBut'].config(image=stopPhoto,width=\"60\",height=\"60\")\n Buttons['stopProgBut'].place(x=200, y=80)\n\n \n ####\n # J1jogNegBut = Button(tab1, bg=\"grey85\", text=\"-\", height=1, width=3, command = J1jogNeg)\n # J1jogNegBut.place(x=642, y=90)\n\n # J1jogPosBut = Button(tab1, bg=\"grey85\",text=\"+\", height=1, width=3, command = J1jogPos)\n # J1jogPosBut.place(x=680, y=90)\n\n # J2jogNegBut = Button(tab1, bg=\"grey85\",text=\"-\", height=1, width=3, command = J2jogNeg)\n # J2jogNegBut.place(x=732, y=90)\n\n # J2jogPosBut = Button(tab1, bg=\"grey85\",text=\"+\", height=1, width=3, command = J2jogPos)\n # J2jogPosBut.place(x=770, y=90)\n\n # J3jogNegBut = Button(tab1, bg=\"grey85\",text=\"-\", height=1, width=3, command = J3jogNeg)\n # J3jogNegBut.place(x=822, y=90)\n\n # J3jogPosBut = Button(tab1, bg=\"grey85\",text=\"+\", height=1, width=3, command = J3jogPos)\n # J3jogPosBut.place(x=860, y=90)\n\n # J4jogNegBut = Button(tab1, bg=\"grey85\",text=\"-\", height=1, width=3, command = J4jogNeg)\n # J4jogNegBut.place(x=912, y=90)\n\n # J4jogPosBut = Button(tab1, bg=\"grey85\",text=\"+\", height=1, width=3, command = J4jogPos)\n # J4jogPosBut.place(x=950, y=90)\n\n # J5jogNegBut = Button(tab1, bg=\"grey85\",text=\"-\", height=1, width=3, command = J5jogNeg)\n # J5jogNegBut.place(x=1002, y=90)\n\n # J5jogPosBut = Button(tab1, bg=\"grey85\",text=\"+\", height=1, width=3, command = J5jogPos)\n # J5jogPosBut.place(x=1040, y=90)\n\n # J6jogNegBut = Button(tab1, bg=\"grey85\",text=\"-\", height=1, width=3, command = J6jogNeg)\n # J6jogNegBut.place(x=1092, y=90)\n\n # J6jogPosBut = Button(tab1, bg=\"grey85\",text=\"+\", height=1, width=3, command = J6jogPos)\n # J6jogPosBut.place(x=1130, y=90)\n\n # XjogNegBut = Button(tab1, bg=\"grey85\",text=\"-\", height=1, width=3, command = XjogNeg)\n # XjogNegBut.place(x=642, y=210)\n\n # XjogPosBut = Button(tab1, bg=\"grey85\",text=\"+\", height=1, width=3, command = XjogPos)\n # XjogPosBut.place(x=680, y=210)\n\n # YjogNegBut = Button(tab1, bg=\"grey85\",text=\"-\", height=1, width=3, command = YjogNeg)\n # YjogNegBut.place(x=732, y=210)\n\n # YjogPosBut = Button(tab1, bg=\"grey85\",text=\"+\", height=1, width=3, command = YjogPos)\n # YjogPosBut.place(x=770, y=210)\n\n # ZjogNegBut = Button(tab1, bg=\"grey85\",text=\"-\", height=1, width=3, command = ZjogNeg)\n # ZjogNegBut.place(x=822, y=210)\n\n # ZjogPosBut = Button(tab1, bg=\"grey85\",text=\"+\", height=1, width=3, command = ZjogPos)\n # ZjogPosBut.place(x=860, y=210)\n\n # RxjogNegBut = Button(tab1, bg=\"grey85\",text=\"-\", height=1, width=3, command = RxjogNeg)\n # RxjogNegBut.place(x=912, y=210)\n\n # RxjogPosBut = Button(tab1, bg=\"grey85\",text=\"+\", height=1, width=3, command = RxjogPos)\n # RxjogPosBut.place(x=950, y=210)\n\n # RyjogNegBut = Button(tab1, bg=\"grey85\",text=\"-\", height=1, width=3, command = RyjogNeg)\n # RyjogNegBut.place(x=1002, y=210)\n\n # RyjogPosBut = Button(tab1, bg=\"grey85\",text=\"+\", height=1, width=3, command = RyjogPos)\n # RyjogPosBut.place(x=1040, y=210)\n\n # RzjogNegBut = Button(tab1, bg=\"grey85\",text=\"-\", height=1, width=3, command = RzjogNeg)\n # RzjogNegBut.place(x=1092, y=210)\n\n # RzjogPosBut = Button(tab1, bg=\"grey85\",text=\"+\", height=1, width=3, command = RzjogPos)\n # RzjogPosBut.place(x=1130, y=210)\n\n ###\n\n # JogStepsCbut = Checkbutton(tab1, text=\"Jog joints in steps\",variable = JogStepsStat)\n # JogStepsCbut.place(x=1190, y=10)\n\n ####ENTRY FIELDS##########################################################\n ##########################################################################\n\n entryField = {}\n\n fileID = open('../conf/conf_tab1_entries.csv')\n csvID = csv.reader(fileID, delimiter=',')\n \n \n for row in csvID:\n entryField[row[0]] = Entry(tab1, width=row[1])\n entryField[row[0]].place(x=row[2], y=row[3])\n \n fileID.close()\n\n joint_names = []\n for ii in range(1,7):\n joint_names.append('J' + str(ii))\n \n self.currentAngleEntryField = {}\n for ii, joint_name in enumerate(joint_names): \n self.currentAngleEntryField[joint_name] = Entry(tab1, width=5)\n self.currentAngleEntryField[joint_name].place(x=660+(ii)*90, y=40)\n \n # self.jogDegreesEntryField[ii] = Entry(tab1,width=5)\n # self.jogDegreesEntryField[ii].place(x=660+(ii-1)*90, y=65)\n \n\n # self.currentPositionEntryField[ii] = Entry(tab1,width=5)\n # self.currentPositionEntryField[ii].place(x=660+(ii-1)*90, y=160)\n \n # self.jogPositionEntryField[ii] = Entry(tab1,width=5)\n # self.jogPositionEntryField[ii].place(x=660+(ii-1)*90, y=185)\n ","sub_path":"src/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":12371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"118836516","text":"import json\nimport time\nfrom websocket import create_connection\n\n\nclass KrakenSocket:\n\n def __init__(self):\n pass\n\n\nfor i in range(3):\n try:\n ws = create_connection(\"wss://ws.kraken.com\")\n except Exception as error:\n print('Caught this error: ' + repr(error))\n time.sleep(3)\n else:\n break\n\nws.send(json.dumps({\n \"event\": \"subscribe\",\n # \"event\": \"ping\",\n \"pair\": [\"ETH/USD\"],\n # \"subscription\": {\"name\": \"ticker\"}\n # \"subscription\": {\"name\": \"spread\"}\n \"subscription\": {\"name\": \"trade\"}\n # \"subscription\": {\"name\": \"book\", \"depth\": 10}\n # \"subscription\": {\"name\": \"ohlc\", \"interval\": 5}\n }))\n\nwhile True:\n try:\n result = ws.recv()\n result = json.loads(result)\n print(\"Received '%s'\" % result, time.time())\n except Exception as error:\n print('Caught this error: ' + repr(error))\n time.sleep(3)\n\nws.close()\n","sub_path":"testing/kraken_connection.py","file_name":"kraken_connection.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"49559970","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2017-06-03 16:37:23\n# @Author : jhb (jhbnanyou@163.com)\n# @Link : \n# @Version : $Id$\nfrom HTMLTestRunner import HTMLTestRunner\nimport unittest\nimport time\n\ntest_dir = \"./\"\ndiscover = unittest.defaultTestLoader.discover(test_dir,pattern = \"basemanage*.py\")\n\nif __name__ == '__main__':\n\n\tnow = time.strftime(\"%Y-%m-%d %H_%M_%S\")\n\t# 定义报告存放的路径、\n\tfilename ='D:\\\\testpro\\\\report\\\\' + now + ' ' + 'result.html'\n\tfp = open(filename,'wb')\n\t#定义测试报告\n\trunner = HTMLTestRunner(stream=fp,title=\"测试报告\",description='用例执行情况:')\n\n\t#runtest = unittest.TextTestRunner()\n\t#runtest.run(discover) \n\trunner.run(discover) #运行测试用例\n\n\tfp.close() #关闭报告文件\n\n\n","sub_path":"Python/unittest/test_project/runtest.py","file_name":"runtest.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"232793673","text":"from concurrent.futures import ProcessPoolExecutor\nfrom functools import partial\nimport numpy as np\nimport os\nfrom audio import melspectrogram, trim_silence\n\nfrom hparams import hparams\nimport librosa\nimport glob\n\n\ndef build_from_path(in_dir, out_dir, test_speakers=None, num_workers=1, tqdm=lambda x: x):\n \"\"\"\n Preprocesses the speech dataset from a gven input path to given output directories\n\n Args:\n - hparams: hyper parameters\n - input_dir: input directory that contains the files to prerocess\n - out_dir: output directory of npz files\n - n_jobs: Optional, number of worker process to parallelize across\n - tqdm: Optional, provides a nice progress bar\n\n Returns:\n - A list of tuple describing the train examples. this should be written to train.txtX\n\n \"\"\"\n\n # speaker 저장 변수\n speakers = {}\n\n # for multiprocessing\n executor = ProcessPoolExecutor(max_workers=num_workers)\n futures = []\n index = 1\n\n # read speaker list\n spk_list_name = os.path.join(in_dir, 'spk_list.txt')\n with open(spk_list_name, 'r') as f:\n speaker_paths = [os.path.join(in_dir, path).strip() for path in f.read().split('\\n')]\n\n # 전처리 할 data가 없는 경우\n if not speaker_paths:\n print(\"dataset is empty!\")\n exit(-1)\n\n # print total speakers\n total_speaker_num = len(speaker_paths)\n print(\"Total speaker number : %d\" % total_speaker_num)\n\n for i, path in enumerate(speaker_paths):\n # extract speaker name\n speaker_name = path.split('/')[-1]\n speakers[speaker_name] = i\n\n print(\"speaker %s processing...\" % speaker_name)\n futures.append(executor.submit(partial(_process_utterance, out_dir, path, i, speaker_name, hparams)))\n index += 1\n\n return [future.result() for future in tqdm(futures) if future.result() is not None], speakers\n\ndef _process_utterance(out_dir, in_dir, label, speaker_name, hparams):\n wav_paths = glob.glob(os.path.join(in_dir, \"*.wav\"))\n if not wav_paths:\n return None\n\n total_utter_num = len(wav_paths)\n train_utter_num = (total_utter_num // 10) * 9\n print(\"[%s] train : %d, test : %d\" % (speaker_name, train_utter_num, total_utter_num - train_utter_num))\n\n num_samples = len(wav_paths)\n npz_dir = os.path.join(out_dir, speaker_name)\n os.makedirs(npz_dir, exist_ok=True)\n\n # Train & Test path 설정\n train_path = os.path.join(npz_dir, \"train\")\n test_path = os.path.join(npz_dir, \"test\")\n os.makedirs(train_path, exist_ok=True)\n os.makedirs(test_path, exist_ok=True)\n\n for idx, wav_path in enumerate(wav_paths):\n wav_name, ext = os.path.splitext(os.path.basename(wav_path))\n if ext == \".wav\":\n wav, sr = librosa.load(wav_path, sr=hparams.sample_rate)\n\n # rescale wav\n if hparams.rescaling: # hparams.rescale = True\n wav = wav / np.abs(wav).max() * hparams.rescaling_max\n\n # M-AILABS extra silence specific\n if hparams.trim_silence: # hparams.trim_silence = True\n wav = trim_silence(wav, hparams) # Trim leading and trailing silence\n\n mel = melspectrogram(wav, hparams)\n seq_len = wav.shape[0]\n frame_len = mel.shape[1]\n\n # data output dir\n if idx < train_utter_num:\n data_out_dir = train_path\n else:\n data_out_dir = test_path\n file_name = wav_name\n np.savez(os.path.join(data_out_dir, file_name), mel=mel.T, speaker=label, seq_len=seq_len, frame_len=frame_len)\n\n\n return num_samples","sub_path":"datasets/NIKL.py","file_name":"NIKL.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"136630518","text":"import numpy as np\nimport seaborn as sns\nimport random\n\n#Importing from multiagent package\nfrom multiagent.core import World, Agent, Landmark\nfrom multiagent.scenario import BaseScenario\n\n\n# AGENT TYPES\n\nAGENT_LISTENER = 0\nAGENT_SPEAKER = 1\nAGENT_GHOST = 2\nrandom_choices = [[0.03, 0],[-0.03, 0],[0, -0.03],[0, 0.03]]\ndef world_step(world):\n for ghost in world.ghosts:\n dir = random.choice(random_choices)\n ghost.state.p_pos[0] += dir[0]\n ghost.state.p_pos[1] += dir[1]\n World.step(world)\n\nclass Scenario(BaseScenario):\n\n #Creates all of the entities that inhabit the world (landmarks, agents, etc.)\n #Assigns capabilities of entities (whether they can communicate, or move, or both)\n #Called once at the beginning of each training session\n\n def make_world(self):\n world = World()\n world.step = lambda :world_step(world)\n\n #Setting World Properties\n world.dim_c = 5\n self.num_listeners = 2 # Number of listeners= Number of agents\n self.num_speakers = 4 # Number of speakers= Number of advisors\n self.num_landmarks = 1 # Number of landmarks= Number of goals\n self.num_ghosts = 4\n\n world.landmark_colors = np.array(sns.color_palette(n_colors=self.num_landmarks))\n\n #Creation of listeners\n world.listeners = []\n for listener_ind in range(self.num_listeners):\n agent = self._create_listener(listener_ind)\n world.listeners.append(agent)\n world.listeners[-1].predicted = True\n\n #Creation of speakers\n world.speakers = []\n for speaker_ind in range(self.num_speakers):\n agent = self._create_speaker(speaker_ind)\n world.speakers.append(agent)\n world.speakers[-1].predicted = True\n\n world.landmarks = []\n for landmark_ind in range(self.num_landmarks):\n landmark = self._create_landmark(landmark_ind)\n landmark.color = world.landmark_colors[landmark_ind]\n world.landmarks.append(landmark)\n\n world.ghosts = []\n for ghost_ind in range(self.num_ghosts):\n agent = self._create_ghost(ghost_ind)\n world.ghosts.append(agent)\n\n #The World is collectively made up of listeners and speakers\n world.agents = world.listeners + world.speakers\n\n #Set initial conditions\n self.reset_world(world)\n self.reset_cached_rewards()\n return world\n\n def _create_landmark(self, ind):\n landmark = Landmark()\n ind = ind + self.num_speakers + self.num_listeners\n landmark.i = ind\n landmark.name = 'landmark %d' % ind\n landmark.collide = False\n landmark.movable = False\n landmark.size = 0.04\n return landmark\n\n def _create_agent_base(self, ind):\n agent = Agent()\n agent.i = ind\n agent.name = 'agent %i' % agent.i\n agent.collide = False\n agent.size = 0.075\n agent.accel = 1.5\n agent.initial_mass = 1.0\n agent.max_speed = 1.0\n agent.predicted=False\n return agent\n\n def _create_speaker(self, ind):\n ind = ind + self.num_listeners\n agent = self._create_agent_base(ind)\n agent.listener = False\n agent.agent_type = AGENT_SPEAKER\n agent.movable = False\n agent.predicted=False\n return agent\n\n def _create_listener(self, ind):\n agent = self._create_agent_base(ind)\n agent.agent_type = AGENT_LISTENER\n agent.listener = True\n agent.silent = True\n agent.movable = True\n return agent\n\n def _create_ghost(self, ind):\n ind = ind + self.num_speakers + self. num_landmarks + self.num_listeners\n agent = self._create_agent_base(ind)\n agent.listener = False\n agent.agent_type = AGENT_GHOST\n agent.movable = True\n return agent\n\n def reset_cached_rewards(self):\n self.pair_rewards = None\n\n def post_step(self, world):\n self.reset_cached_rewards()\n\n #method to signal end of game\n def game_done(self, agent, world):\n return world.done\n \n @staticmethod\n def get_quadrant(postion):\n if postion[0]>0:\n if postion[1]>0:\n return 0\n else:\n return 3\n else:\n if postion[1]>0:\n return 1\n else:\n return 2\n\n def _reset_movable(self, world):\n for agent in world.listeners + world.speakers + world.ghosts:\n agent.state.p_pos = np.random.uniform(-1,+1, world.dim_p)\n agent.state.p_vel = np.zeros(world.dim_p)\n agent.state.c = np.zeros(world.dim_c)\n\n def _reset_landmarks(self, world):\n for i, landmark in enumerate(world.landmarks):\n landmark.state.p_pos = np.random.uniform(-1,+1, world.dim_p)\n landmark.state.p_vel = np.zeros(world.dim_p)\n\n def _reset_speakers(self, world, shuff=True):\n landmark = np.random.choice(world.landmarks)\n quads = np.arange(4)\n if shuff:\n np.random.shuffle(quads)\n for i, speaker in enumerate(world.speakers):\n li = 0\n speaker.listen_ind = li\n speaker.goal_a = world.listeners[li]\n speaker.goal_b = landmark\n speaker.quad = quads[i]\n speaker.color = np.array([0.25, 0.25, 0.25])\n world.listeners[li].color = speaker.goal_b.color + np.array([0.25, 0.25, 0.25])\n world.listeners[li].speak_ind = i\n # speaker.state.c = np.zeros(world.dim_c)\n\n def reset_world(self, world):\n self._reset_speakers(world)\n self._reset_movable(world)\n self._reset_landmarks(world)\n self.reset_cached_rewards()\n \n world.done= False\n\n def benchmark_data(self, agent, world):\n #Data returned for benchmarking purposes\n return reward(agent, world)\n\n def calc_rewards(self, world):\n rews = []\n for speaker in world.speakers:\n dist = np.sum(np.square(speaker.goal_a.state.p_pos -\n speaker.goal_b.state.p_pos))\n rew = -dist\n if dist < (speaker.goal_a.size + speaker.goal_b.size) * 1.5:\n world.done = True\n \n for ghost in world.ghosts:\n dist = np.sum(np.square(speaker.goal_a.state.p_pos -\n ghost.state.p_pos))\n if dist< 0.225:\n if dist>0.001:\n rew -= (0.01)* (1/dist)\n else:\n rew -= 10\n if speaker.predicted:\n rew += 1\n else:\n rew -= 1\n \n rews.append(rew)\n # print (rews)\n return rews\n\n def reward(self, agent, world):\n if self.pair_rewards is None:\n self.pair_rewards = self.calc_rewards(world)\n share_rews = False\n if share_rews:\n return sum(self.pair_rewards)\n if agent.listener:\n if agent.predicted:\n return self.pair_rewards[-1]\n else:\n return self.pair_rewards[-2]\n else:\n return self.pair_rewards[-2]\n\n def observation(self, agent, world):\n if agent.listener:\n obs = []\n\n #Listener gets own position or velocity\n obs += [agent.state.p_pos, agent.state.p_vel]\n\n # give listener all communications\n obs += [speaker.state.c for speaker in world.speakers]\n \n return np.concatenate(obs)\n\n else: #If agent is a speaker\n obs = []\n if agent.quad == self.get_quadrant(agent.goal_a.state.p_pos):\n obs += [np.array([1]), agent.goal_a.state.p_pos, agent.goal_b.state.p_pos]\n else:\n obs += [np.array([0,0,0]), agent.goal_b.state.p_pos]\n\n for ghost in world.ghosts:\n if agent.quad == self.get_quadrant(ghost.state.p_pos):\n obs += [np.array([1]), ghost.state.p_pos]\n else:\n obs += [np.array([0,0,0])]\n\n return np.concatenate(obs)\n","sub_path":"envs/mpe_scenarios/PacmanLite_Experiment1.py","file_name":"PacmanLite_Experiment1.py","file_ext":"py","file_size_in_byte":8210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"417144357","text":"## Script (Python) \"after_rigetta\"\n##bind container=container\n##bind context=context\n##bind namespace=\n##bind script=script\n##bind subpath=traverse_subpath\n##parameters=state_change\n##title=\n##\ndoc = state_change.object\n\n#Aggiornamento dello stato su plominoDocument\ndoc.updateStatus()\n\nif script.run_script(doc, script.id) != False:\n\n #### OTHER CODE HERE ####\n\n # 1. INVIO MAIL RIGETTO\n if doc.naming('richiesta') != 'integrazione':\n doc.sendThisMail('rigetta')\n\n script.run_script(doc, script.id, suffix='post')\n\n#### SCRIPT ENDS HERE ####\n","sub_path":"src/gisweb/iol/profiles/default/workflows/iol_backoffice_wf/scripts/after_rigetta.py","file_name":"after_rigetta.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"545907406","text":"#!/usr/bin/env python\n\nperson = 'Bill', 'Gates', 'Microsoft', '1955-10-28'\n\nprint(person[3])\nprint(person[-1])\n\nfirst_name, last_name, product, dob = person\n\npeople = [\n ('Melinda', 'Gates', 'Gates Foundation', '1964-08-15'),\n ('Steve', 'Jobs', 'Apple', 'NeXT', '1955-02-24'),\n ('Larry', 'Wall', 'Perl', '1954-09-27'),\n ('Paul', 'Allen', 'Microsoft', '1953-01-21'),\n ('Larry', 'Ellison', 'Oracle', '1944-08-17'),\n ('Bill', 'Gates', 'Microsoft', '1955-10-28'),\n ('Mark', 'Zuckerberg', 'Facebook', '1984-05-14'),\n ('Sergey','Brin', 'Google', '1973-08-21'),\n ('Larry', 'Page', 'Google', '1973-03-26'),\n ('Linus', 'Torvalds', 'Linux', 'git', '1969-12-28'),\n ('John', 'Strickler', '1956-10-31'),\n]\nprint(people[0])\nprint(people[0][0])\nprint(people[0][0][0], '\\n')\n\nfor first_name, last_name, *product, dob in people:\n print(first_name, last_name, product)\nprint()\n\ncolors = ['pink', 'purple', 'orange']\n\nfor c in colors:\n print(c)\nprint()\n\nfor i, c in enumerate(colors, 1):\n print(i, c)\nprint()\n\nprint(list(enumerate(colors)))\n\nairports = {\n 'EWR': 'Newark',\n 'MCI': 'Kansas City',\n 'SFO': 'San Francisco',\n 'RDU': 'Raleigh-Durham',\n 'SJC': 'San Jose',\n 'MCO': 'Orlando',\n 'ABQ': 'Albuquerque',\n 'OAK': 'Oakland',\n 'SAC': 'Sacramento',\n 'IAD': 'Dulles',\n}\n\nfor abbr, name in airports.items():\n print(abbr, name)\nprint()\n\nprint(list(airports.items()), '\\n')\n\n","sub_path":"tuple_examples.py","file_name":"tuple_examples.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"500305205","text":"import wntr\nimport wntr.network.controls as controls\nimport re\nimport argparse\nimport yaml\n\n\nclass EpanetParser:\n\n \"\"\"\n This script reads an EPANET inp file and a epanetCPA file and builds a .yaml file with the PLC logic stored in\n EPANET. In addition, the file writes an appropriate utils.py file for the MiniCPS devices and topology\n \"\"\"\n def __init__(self, inp_file_path, cpa_file_path, out_path):\n\n if inp_file_path:\n self.inp_file_path = inp_file_path\n else:\n self.inp_file_path = \"../../Demand_patterns/ctown_map_with_controls.inp\"\n\n if cpa_file_path:\n self.cpa_file_path = cpa_file_path\n else:\n self.cpa_file_path = \"../../Demand_patterns/ctown.cpa\"\n\n if out_path:\n self.out_path = out_path\n else:\n self.out_path = 'plc_dicts.yaml'\n\n print(\"Creating water network model with \" + str(self.inp_file_path) + \" file\")\n self.wn = wntr.network.WaterNetworkModel(self.inp_file_path)\n self.control_list = self.create_control_list()\n self.plc_list = self.create_plc_list()\n\n # topology name\n self.topology_name = \"plant\"\n\n # Network information. Hardwired for now\n self.plc_netmask = \"'/24'\"\n self.enip_listen_plc_addr = \"'192.168.1.1'\"\n self.scada_ip_addr = \"'192.168.1.2'\"\n\n def main(self):\n\n self.configure_plc_list()\n\n ### Creating the dictionary with the IP addresses of the PLCs\n plc_index = 1\n ip_string = \"\"\n\n plc_data_string = \"\"\n\n # PLC Tags\n plc_tags = []\n\n # PLC Servers\n plc_servers = \"\"\n\n # PLC protocols\n plc_protocols = \"\"\n\n\n\n # SCADA information\n scada_tags = \"SCADA_TAGS = (\"\n scada_server = \"SCADA_SERVER = {\\n 'address': SCADA_IP_ADDR,\\n 'tags': SCADA_TAGS\\n}\\n\"\n scada_protocol = \"SCADA_PROTOCOL = {\\n 'name': 'enip',\\n 'mode': 1,\\n 'server': SCADA_SERVER\\n}\\n\"\n\n # For the DB tags, is better to refer to self.wnTR as epanet.INP and cpa files may not provide the full\n # list of pumps and valves\n # Creating the tags strings. We need to differentiate between sensor and actuator tags, because we get their\n # initial values/status in different ways from WaterNetworkModel\n\n # start create db_tags_method\n db_sensor_list = []\n db_actuator_list = []\n db_tags = []\n a_link_list = list(self.wn.link_name_list)\n a_node_list = list(self.wn.node_name_list)\n db_actuator_list.extend(self.get_link_list_by_type(a_link_list, 'Valve'))\n db_actuator_list.extend(self.get_link_list_by_type(a_link_list, 'Pump'))\n db_sensor_list.extend(self.get_node_list_by_type(a_node_list, 'Tank'))\n db_tags.extend(db_actuator_list)\n db_tags.extend(db_sensor_list)\n # end create db_tags_method\n\n tags_strings = []\n\n for tag in db_tags:\n tag_dict = {}\n tag_dict['name'] = tag\n tag_dict['string'] = \"('\" + tag + \"', 1)\"\n tags_strings.append(tag_dict)\n scada_tags += \"\\n ('\" + tag + \"', 1, 'REAL'),\"\n\n scada_tags = scada_tags + \"\\n)\\n\"\n\n # Control fag to sync actuators and physical process\n tag_dict = {}\n tag_dict['name'] = 'CONTROL'\n tag_dict['string'] = \"('CONTROL', 1)\"\n tags_strings.append(tag_dict)\n # ############# PLC ENIP address configuration\n\n for plc in self.plc_list:\n ip_string += \" '\" + plc['PLC'].lower() + \"':'10.0.\" + str(plc_index) + \".1',\\n\"\n\n plc_data_string += \"\\nPLC\" + str(plc_index) + \"_DATA = {\\n 'TODO': 'TODO',\\n}\\n\"\n a_plc_tag_string = \"PLC\" + str(plc_index) + \"_TAGS = (\"\n tag_string = \"\"\n for tag in plc['Sensors']:\n if tag != \"\":\n tag_string += \"\\n ('\" + tag + \"', 1, 'REAL'),\"\n\n for tag in plc['Actuators']:\n if tag != \"\":\n tag_string += \"\\n ('\" + tag + \"', 1, 'REAL'),\"\n\n for dependency in plc['Dependencies']:\n if dependency:\n tag_string += \"\\n ('\" + dependency['tag'] + \"', 1, 'REAL'),\"\n\n tag_string += \"\\n ('CONTROL', 1, 'REAL'),\"\n\n a_plc_tag_string += tag_string + \"\\n)\"\n plc_tags.append(a_plc_tag_string)\n\n plc_servers += \"PLC\" + str(\n plc_index) + \"_SERVER = {\\n 'address': ENIP_LISTEN_PLC_ADDR,\\n 'tags': PLC\" + str(\n plc_index) + \"_TAGS\\n}\\n\"\n plc_protocols += \"PLC\" + str(\n plc_index) + \"_PROTOCOL = {\\n 'name': 'enip',\\n 'mode': 1,\\n 'server': PLC\" + str(\n plc_index) + \"_SERVER\\n}\\n\"\n\n plc_index += 1\n\n plc_data_string += \"SCADA_DATA = {\\n 'TODO': 'TODO',\\n}\\n\"\n\n ctown_ips_prefix = \"CTOWN_IPS = {\\n\"\n ctown_ips = ctown_ips_prefix + ip_string + \"}\"\n\n # ################## DB creation strings\n\n path_string = \"PATH = 'plant.sqlite'\"\n name_string = \"NAME = '\" + self.topology_name + \"'\"\n\n state_string = \"STATE = {\\n 'name': NAME,\\n 'path': PATH\\n}\"\n\n comas = '\"' * 3\n schema_string = 'SCHEMA = ' + comas + '\\\n \\nCREATE TABLE ' + self.topology_name + ' (\\\n \\n name TEXT NOT NULL,\\\n \\n pid INTEGER NOT NULL,\\\n \\n value TEXT,\\\n \\n PRIMARY KEY (name, pid)\\\n \\n);\\n' + comas\n\n db_tag_string = \"SCHEMA_INIT = \" + comas + \"\\n\"\n for tag in db_sensor_list:\n db_tag_string += \" INSERT INTO \" + self.topology_name + \" VALUES ('\" + tag + \"', 1, '\" + str(\n self.get_sensor_initial_value(tag)) + \"');\\n\"\n\n for tag in db_actuator_list:\n db_tag_string += \" INSERT INTO \" + self.topology_name + \" VALUES ('\" + tag + \"', 1, '\" + str(\n self.get_actuator_initial_value(tag)) + \"');\\n\"\n\n db_tag_string += \" INSERT INTO \" + self.topology_name + \" VALUES ('ATT_1', 1, '0');\\n\"\n db_tag_string += \" INSERT INTO \" + self.topology_name + \" VALUES ('ATT_2', 1, '0');\\n\"\n db_tag_string += \" INSERT INTO \" + self.topology_name + \" VALUES ('CONTROL', 1, '0');\\n\"\n db_tag_string += comas\n\n # ########## Writing the utils file ########################################3\n # Erase the file contents\n utils_file = open(\"utils.py\", \"w\")\n utils_file.write(\"\")\n utils_file.close()\n\n utils_file = open(\"utils.py\", \"a\")\n for tag in tags_strings:\n utils_file.write(tag['name'] + \" = \" + tag['string'] + \"\\n\")\n\n utils_file.write(\"\\nplc_netmask = \" + self.plc_netmask + \"\\n\")\n utils_file.write(\"ENIP_LISTEN_PLC_ADDR = \" + self.enip_listen_plc_addr + \"\\n\")\n utils_file.write(\"SCADA_IP_ADDR = \" + self.scada_ip_addr + \"\\n\")\n\n utils_file.write(\"\\n\" + ctown_ips + \"\\n\")\n utils_file.write(plc_data_string + \"\\n\")\n\n for plc in plc_tags:\n utils_file.write(\"\\n\" + plc + \"\\n\")\n\n utils_file.write(\"\\n\" + scada_tags)\n\n # this is only temporal. With the revamp of the attacks, this will be done differently\n utils_file.write(\"\\nflag_attack_communication_plc1_plc2_replay_empty = 0\\n\")\n utils_file.write(\"flag_attack_plc1 = 0\\n\")\n utils_file.write(\"flag_attack_communication_plc1_plc2 = 0\\n\")\n utils_file.write(\"ATT_1 = ('ATT_1', 1)\\n\")\n utils_file.write(\"ATT_2 = ('ATT_2', 1)\\n\")\n utils_file.write(\"\\n\" + plc_servers)\n utils_file.write(\"\\n\" + scada_server)\n utils_file.write(\"\\n\" + plc_protocols)\n utils_file.write(\"\\n\" + scada_protocol)\n utils_file.write(\"\\n\" + path_string)\n utils_file.write(\"\\n\" + name_string + \"\\n\")\n utils_file.write(\"\\n\" + state_string + \"\\n\")\n utils_file.write(\"\\n\" + schema_string + \"\\n\")\n utils_file.write(\"\\n\" + db_tag_string)\n\n utils_file.close()\n\n with open(self.out_path, 'w') as outfile:\n yaml.dump(self.plc_list, outfile, default_flow_style=True)\n\n def configure_plc_list(self):\n for i in range(len(self.plc_list)):\n self.plc_list[i] = self.set_control_list_in_plc(self.plc_list[i], self.control_list)\n self.set_dependencies_list_in_plc(self.plc_list)\n\n def get_control_rule_with_tag(self, a_tag):\n for control in self.control_list:\n if a_tag in control['actuator_tag']:\n return control\n\n def create_control_list(self):\n control_list = []\n for control in self.wn.controls():\n control_dict = {}\n control_dict['tank_tag'] = control[1].condition.name.split(\":\")[0]\n control_dict['operator'] = control[1].condition.name.split(\"level\")[1][0:2]\n control_dict['value'] = control[1].condition.name.split(\"=\")[1]\n control_dict['actuator_tag'] = str(control[1].actions()[0].target()[0])\n control_dict['actuator_value'] = str(control[1].actions()[0]).split(\"to\")[1].strip()\n control_list.append(control_dict)\n return control_list\n\n def create_plc_list(self):\n section_exp = re.compile(r'\\[(.*)\\]')\n plc_exp = re.compile(r'^PLC')\n plcs = []\n nodes_section = False\n with open(self.cpa_file_path, 'r') as file_object:\n for line in file_object:\n if section_exp.match(line) and line == '[CYBERNODES]\\n':\n nodes_section=True\n continue\n if section_exp.match(line) and line != '[CYBERNODES]\\n':\n nodes_section=False\n if nodes_section and line[0] != \";\":\n nodes=line.split(\",\")\n if plc_exp.match(nodes[0].strip()):\n plc_dict = {}\n plc_dict['PLC'] = nodes[0].strip()\n plc_dict['Sensors'] = nodes[1].strip().split(\" \")\n plc_dict['Actuators'] = nodes[2].strip().split(\" \")\n plc_dict['Controls'] = []\n plcs.append(plc_dict)\n return plcs\n\n def set_control_list_in_plc(self, a_plc_dict, a_control_list):\n plc_controls = []\n for actuator in a_plc_dict['Actuators']:\n for control in a_control_list:\n if actuator == control['actuator_tag']:\n plc_controls.append(control)\n a_plc_dict['Controls'] = plc_controls\n return a_plc_dict\n\n def set_dependencies_list_in_plc(self, a_plc_list):\n for plc in a_plc_list:\n dependencies_list = []\n tag_set = set()\n for control in plc['Controls']:\n tag_set.add(control['tank_tag'])\n if tag_set:\n for tag in tag_set:\n for target_plc in a_plc_list:\n if plc == target_plc:\n continue\n for sensor in target_plc['Sensors']:\n if tag == sensor:\n dependency_dict = {}\n dependency_dict['tag'] = tag\n dependency_dict['PLC'] = target_plc['PLC']\n dependencies_list.append(dependency_dict)\n plc['Dependencies'] = dependencies_list\n\n def get_sensor_initial_value(self, sensor_tag):\n return self.wn.get_node(sensor_tag).init_level\n\n def get_actuator_initial_value(self, actuator_tag):\n if type(self.wn.get_link(actuator_tag).status) is int:\n return self.wn.get_link(actuator_tag).status\n else:\n return self.wn.get_link(actuator_tag).status.value\n\n def get_link_list_by_type(self, a_list, a_type):\n result = []\n for link in a_list:\n if self.wn.get_link(link).link_type == a_type:\n result.append(str(link))\n return result\n\n def get_node_list_by_type(self, a_list, a_type):\n result = []\n for node in a_list:\n if self.wn.get_node(node).node_type == a_type:\n result.append(str(node))\n return result\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description='Script that parses an EPANET inp and epanetCPA file to build PLC behaviour')\n parser.add_argument(\"--inp\", \"-i\",help=\"Path to the EPANET inp file\")\n parser.add_argument(\"--cpa\", \"-a\", help=\"Path to the epanetCPA file\")\n parser.add_argument(\"--out\", \"-o\", help=\"Path of the output utils file\")\n\n args = parser.parse_args()\n parser = EpanetParser(args.inp, args.cpa, args.out)\n parser.main()","sub_path":"ICS_topologies/general/epanet_parser.py","file_name":"epanet_parser.py","file_ext":"py","file_size_in_byte":12824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"156335532","text":"\"\"\"\nContains some common upy project context_processors\n\"\"\"\nfrom django.conf import settings\nimport upy\n\ndef use_upy_admin(request):\n \"\"\"\n Adds settings.USE_UPY_ADMIN and settings.JQUERY_LIB to context dictionary\n \"\"\"\n context_extras = {}\n context_extras['USE_UPY_ADMIN'] = settings.USE_UPY_ADMIN\n context_extras['JQUERY_LIB'] = settings.JQUERY_LIB\n context_extras['USE_UPY_JQUERY_LIB'] = settings.USE_UPY_JQUERY_LIB\n context_extras['JQUERYUI_LIB'] = settings.JQUERYUI_LIB\n context_extras['USE_UPY_JQUERYUI_LIB'] = settings.USE_UPY_JQUERY_LIB\n context_extras['JQUERYUI_CSSLIB'] = settings.JQUERYUI_CSSLIB\n context_extras['USE_UPY_CSS_RESET'] = settings.USE_UPY_CSS_RESET\n context_extras['USE_UPY_ROSETTA'] = settings.USE_UPY_ROSETTA\n context_extras['UPY_VERSION'] = upy.__version__\n return context_extras","sub_path":"upy/template_context/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"212661030","text":"#! /usr/bin/env python3\n#encoding: UTF-8\n\nimport threading, random, time\n\n# Exemple lancement de thread\n# def f(x, y):\n# # fonction à exécuter sur un thread à part\n# # ...\n# pass\n#\n# # création du thread\n# th = threading.Thread(target=f, kwargs={'x' : valeur1, 'y' : valeur2})\n# # démarrage du thread\n# th.start()\n# # attente de la fin du thread\n# th.join()\n\ndef tri_bulle(list):\n if len(list) <= 1:\n return\n temp = 0\n while temp != None:\n temp = None\n for i in range(len(list)-2, -1, -1):\n if list[i] > list[i+1]:\n # permutation => temp != None\n temp = list[i]\n list[i] = list[i+1]\n list[i+1] = temp\n\ndef tri_sable(list):\n ...\n\n# création liste non-ordonnée pour les tests\nN = 1000\nliste = []\nfor i in range(N):\n liste.insert(random.randint(0, i), i)\nprint(liste)\n\n# tri\ntri_bulle(liste)\nprint(liste)\n\n","sub_path":"LabSessionsSol/TP81_squelette.py","file_name":"TP81_squelette.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"384266960","text":"import rospy, ros_hardware, greenhouse_behaviors, ping_behavior, layers, camera_behavior\n\nimport sys, os\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + \"/../lib\")\nfrom terrabot_utils import time_since_midnight\n\nclass LayeredGreenhouseAgent:\n\n def __init__(self,schedulefile):\n rospy.set_param('use_sim_time', True)\n rospy.init_node('greenhouseagent', anonymous = True)\n\n #your code from Assignment 1 plus Ping here\n self.sensors = ros_hardware.ROSSensors()\n self.actuators = ros_hardware.ROSActuators()\n self.ping_behavior = ping_behavior.Ping()\n self.camera_behavior = camera_behavior.TakeImage()\n behavior_list = [greenhouse_behaviors.Light(),greenhouse_behaviors.LowerHumid(), greenhouse_behaviors.RaiseTemp(), greenhouse_behaviors.LowerTemp()\n , greenhouse_behaviors.LowerSMoist(), greenhouse_behaviors.RaiseSMoist(), self.ping_behavior, self.camera_behavior]\n\n self.behavioral_layer = layers.BehavioralLayer(self.sensors, self.actuators, behavior_list)\n self.executive_layer = layers.ExecutiveLayer()\n self.planning_layer = layers.PlanningLayer(schedulefile)\n self.executive_layer.setBehavioralLayer(self.behavioral_layer)\n self.executive_layer.setPlanningLayer(self.planning_layer)\n self.executive_layer.requestNewSchedule()\n self.planning_layer.setExecutive(self.executive_layer)\n\n\n def main(self):\n rospy.sleep(2)\n while rospy.get_time() == 0: rospy.sleep(1)\n #your code here if necessary\n last_ping = rospy.get_time() \n self.ping_behavior.act()\n \n while not rospy.core.is_shutdown():\n t = time_since_midnight(self.sensors.getTime())\n self.planning_layer.doStep(t)\n rospy.sleep(1)\n self.executive_layer.doStep(t)\n rospy.sleep(1)\n self.behavioral_layer.doStep()\n rospy.sleep(1)\n\n\nif __name__ == '__main__':\n agent = LayeredGreenhouseAgent(\"greenhouse_schedule.txt\")\n agent.main()\n\n","sub_path":"agents/CV Assignment/greenhouse_agent.py","file_name":"greenhouse_agent.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"8215235","text":"class Solution:\n \"\"\"\n 字符串中寻找子串\n \"\"\"\n def strStr(self, haystack: str, needle: str) -> int:\n \"\"\"\n What should we return when needle is an empty string?\n This is a great question to ask during an interview.\n For the purpose of this problem, we will return 0 when needle is an empty string.\n This is consistent to C's strstr() and Java's indexOf().\n \"\"\"\n if haystack is None:\n return -1\n elif needle is None:\n return 0\n try:\n index = haystack.index(needle)\n return index\n except:\n return -1\n\n def brute_strStr(self, haystack: str, needle: str) -> int:\n \"\"\"\n 暴力破解\n \"\"\"\n if needle is None or haystack is None:\n return\n tlen = len(haystack)\n plen = len(needle) # p 模式\n if plen == 0:\n return 0\n elif tlen == 0:\n return -1\n tindex, pindex = 0, 0\n for tindex in range(tlen-plen+1):\n for pindex in range(plen):\n if needle[pindex] == haystack[pindex+tindex]:\n pindex += 1\n else:\n break\n if pindex == plen: # matched\n return tindex\n else:\n pindex = 0\n tindex += 1\n else:\n return -1\n\n def Horspool_strStr(self, haystack: str, needle: str):\n \"\"\"\n :param pattern:\n :param string:\n :return:\n \"\"\"\n pattern_len = len(needle)\n text_len = len(haystack)\n # 以字母表中可打印字符为索引的数组\n move_tabel = [pattern_len] * 96\n for index in range(0, pattern_len - 1):\n # 模式串中每个字符的移动距离,从左至右扫描模式,相同字符的最后一次改写恰好是该字符在模式串的最右边\n move_tabel[ord(needle[index])-32] = pattern_len-1-index\n pattern_lastIndex = pattern_len-1 # 模式中最后一个字符在文本中的位置\n while pattern_lastIndex < text_len:\n k = 0\n while k < pattern_len and needle[pattern_len-1-k] == haystack[pattern_lastIndex-k]:\n k += 1\n if k == pattern_len:\n return pattern_lastIndex - pattern_len + 1\n else: # 模式向右移动\n pattern_lastIndex += move_tabel[ord(haystack[pattern_lastIndex])-32]\n return -1\n\n def BoyerMoore_strStr(self, haystack: str, needle: str):\n pattern_len = len(needle)\n text_len = len(haystack)\n badCharacterMoveTable = [pattern_len] * 96 # 坏符号移动表\n for index in range(0, pattern_len-1):\n badCharacterMoveTable[ord(needle[index])-32] = pattern_len-1-index\n goodsuffixMoveTable = self.suffix(needle, pattern_len)\n pattern_lastIndex = pattern_len -1\n while pattern_lastIndex < text_len:\n k = 0\n while k < pattern_len and needle[pattern_len-1-k] == haystack[pattern_lastIndex-k]:\n k += 1\n if k == pattern_len:\n return pattern_lastIndex - pattern_len +1\n else:\n if k == 0:\n pattern_lastIndex += badCharacterMoveTable[ord(haystack[pattern_lastIndex])-32]\n else:\n pattern_lastIndex += max(max(1, badCharacterMoveTable[ord(haystack[pattern_lastIndex])-32]-k),\n goodsuffixMoveTable[pattern_len-1-k])\n return -1\n\n def suffix(self, pattern: str, pattern_len: int):\n \"\"\"\n 计算好后缀移动表\n :param pattern:\n :return:\n \"\"\"\n \"\"\"\n Each entry shift[i] contain the distance pattern will shift if mismatch occur at position i-1. \n That is, the suffix of pattern starting at position i is matched and a mismatch occur at position i-1\n \"\"\"\n\n \"\"\"\n Each entry bpos[i] contains the starting index of border for suffix starting at index i \n in given pattern P.\n -----------------------------------------------------------------------------------------\n lping: for suffix starting at index i(substring of pattern) , bpos[i] is the starting of \n border in pattern T\n -----------------------------------------------------------------------------------------\n The suffix φ beginning at position m has no border, so bpos[m] is set to m+1 where m \n is the length of the pattern.\n \"\"\"\n \"\"\"\n if border[i] = j then border[i-1] = j-1\n \"\"\"\n goodsuffix_shift = [0] * (pattern_len+1)\n bPos = [0] * (pattern_len+1)\n i = pattern_len\n j = pattern_len + 1\n bPos[i] = j\n while i > 0:\n while j <= pattern_len and pattern[i-1] != pattern[j-1]:\n\n if goodsuffix_shift[j] == 0:\n goodsuffix_shift[j] = j - i\n j = bPos[j]\n i -= 1\n j -= 1\n bPos[i] = j\n\n # case 2\n j = bPos[0]\n for i in range(pattern_len+1):\n if goodsuffix_shift[i] == 0:\n goodsuffix_shift[i] = j\n if i == j:\n j = bPos[j]\n return goodsuffix_shift\n\n def KMP_strStr(self, haystack: str, needle: str) -> int:\n \"\"\"\"\"\"\n \"\"\"\n lps[i] = the longest proper prefix of pattern[0..i] which is also a suffix of pattern[0..i]. \n A proper prefix is prefix with whole string not allowed. \n when mismatch:\n j = lps[j-1]\n txt[i] and pat[j] do NOT match and j is 0, we do i++.\n \"\"\"\n\n pattern_len = len(needle)\n text_len = len(haystack)\n text_index = 0\n pattern_index = 0\n lps = self.computeLPArray(needle, pattern_len)\n while text_index < text_len:\n if needle[pattern_index] == haystack[text_index]:\n pattern_index += 1\n text_index += 1\n if pattern_index == pattern_len: # Found\n return text_index-pattern_index\n elif text_index < text_len and needle[pattern_index] != haystack[text_index]:\n if pattern_index != 0:\n pattern_index = lps[pattern_index-1]\n else:\n text_index += 1\n return -1\n\n def computeLPArray(self, pattern, pattern_len):\n lps = [0] * pattern_len # lps[0] is always 0\n index = 1\n _len = 0 # length of the previous longest prefix suffix\n while index < pattern_len: # the loop calculates lps[i] for i = 1 to pattern_len\n if pattern[index] == pattern[_len]:\n _len += 1\n lps[index] = _len\n index += 1\n else:\n # This is tricky. Consider the example. AAACAAAA and i = 7. The idea is similar to search step.\n if _len != 0:\n _len = lps[_len - 1]\n else:\n lps[index] = 0\n index += 1\n return lps\n","sub_path":"easy/strStr.py","file_name":"strStr.py","file_ext":"py","file_size_in_byte":7167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"422566094","text":"import random as rd\r\nimport collections\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nimport wireless_cache_network as cache\r\nimport numpy as np\r\nfrom conventional_method import *\r\nimport DNN_model\r\nimport time\r\nimport matplotlib.pyplot as plt\r\nfrom celluloid import Camera\r\n\r\nimport matplotlib as mpl\r\nmpl.rc('xtick', labelsize=10)\r\nmpl.rc('ytick', labelsize=10)\r\n\r\nmax_episode = 10\r\nenv = cache.cache_replacement()\r\nnode = 400\r\nw_node = 1\r\ninput_size = 5 * env.F_packet + 4\r\noutput_size = 4 * env.F_packet\r\ny_layer = []\r\n\r\ndef main():\r\n\r\n # main_DQN = DNN_model.Qnet_FCN(input_size, node, output_size) #FCN\r\n main_DQN = DNN_model.Qnet_v6(env.Num_packet, env.Num_file, env.F_packet, node, output_size) #CNN\r\n main_DQN.load_state_dict(torch.load(\".pth\", map_location='cpu'))\r\n main_DQN.eval()\r\n\r\n # view parameter\r\n # print(\"main_DQN:\", main_DQN)\r\n # print(\"main_DQN1 value:\", list(main_DQN.Lc.parameters())\r\n\r\n state_1 = np.zeros([env.F_packet])\r\n state_2 = np.zeros([env.F_packet])\r\n state_3 = np.zeros([env.F_packet])\r\n state_4 = np.zeros([env.F_packet])\r\n\r\n env.Zip_funtion()\r\n interval = 1\r\n request = 1000\r\n cost = 0.0\r\n start_time = time.time()\r\n\r\n for episode in range(max_episode):\r\n state = env.reset()\r\n file = env.file_request[0]\r\n user = env.user_location\r\n for i in range(request * env.Num_packet):\r\n # cache_state\r\n state_1 += env.state[0]\r\n state_2 += env.state[1]\r\n state_3 += env.state[2]\r\n state_4 += env.state[3]\r\n\r\n # CD\r\n # action = CD(env.Memory, env.BS_Location, user, env.state, env.point, file, env.F_packet)\r\n # SD\r\n # action = SD(env.Memory, env.BS_Location, user, env.state, env.point, env.F_packet)\r\n # No cache\r\n # action = NO(env.Memory, env.BS_Location, user, env.state, env.point, env.F_packet)\r\n\r\n # CNN\r\n s = torch.from_numpy(state).float().unsqueeze(0)\r\n with torch.no_grad():\r\n aa = main_DQN(s).cpu().detach().numpy()\r\n Noise = np.zeros(4 * env.F_packet)\r\n action = env.action_select(aa, Noise)\r\n\r\n next_state, reward, done, file, user = env.step(action, file, user)\r\n\r\n # If you want to see the environment status by time step, remove the comment.\r\n # print(\"----------------------------------\")\r\n # print(\"file\", file)\r\n # print(\"user\", user)\r\n # print(\"action_sbs\", action // env.F_packet)\r\n # print(\"action_rep\", action % env.F_packet)\r\n # print(\"state\")\r\n # env.print()\r\n # print(\"reward\", reward)\r\n # print(\"----------------------------------\")\r\n\r\n state = next_state\r\n \r\n cost += env.cost\r\n\r\n if episode % interval == (interval - 1):\r\n y_layer.append(cost / interval)\r\n print(\"Episode: {} cost: {}\".format(episode, (cost / interval)))\r\n cost = 0.0\r\n print(env.MS_error)\r\n\r\n state_1 = state_1 / di\r\n state_2 = state_2 / di\r\n state_3 = state_3 / di\r\n state_4 = state_4 / di\r\n\r\n two_bottom = np.add(state_1, state_2)\r\n three_bottom = np.add(two_bottom, state_3)\r\n\r\n state_all = np.array([state_1, state_2, state_3, state_4])\r\n\r\n x = range(env.F_packet)\r\n x_1 = range(0, env.F_packet+1, env.Num_packet)\r\n x_2 = [\"{:0^d}\".format(x) for x in np.arange(0, env.F_packet + 1, env.Num_packet)]\r\n p1 = plt.bar(x, state_1, color='b', hatch='/')\r\n plt.xticks(x_1, x_2, rotation=-30)\r\n p2 = plt.bar(x, state_2, color='r', hatch='\\\\', bottom=state_1)\r\n plt.xticks(x_1, x_2, rotation=-30)\r\n p3 = plt.bar(x, state_3, color='g', hatch='-', bottom=two_bottom)\r\n plt.xticks(x_1, x_2, rotation=-30)\r\n p4 = plt.bar(x, state_4, color='silver', hatch='o', bottom=three_bottom)\r\n plt.xticks(x_1, x_2, rotation=-30)\r\n plt.ylabel(\"Sum cache rate of 4 SBSs\", fontsize=10)\r\n plt.xlabel(\"index $\\it{j}$ chunks\", fontsize=11)\r\n\r\n plt.legend((p4[0], p3[0], p2[0], p1[0]), (\"Small-cell BS4\", \"Small-cell BS3\", \"Small-cell BS2\", \"Small-cell BS1\"))\r\n plt.ylim(0, 4.0)\r\n plt.show()\r\n\r\n print(\"start_time\", start_time)\r\n print(\"--- %s seconds ---\" % (time.time() - start_time))\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"Performance_test/main_testing.py","file_name":"main_testing.py","file_ext":"py","file_size_in_byte":4438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"562095718","text":"# -*- coding: utf-8 -*-\nimport os\nimport shutil\nimport ctypes\n\ndef copyEnvFile():\n houdiniEnvPath=os.getenv(\"HOMEDRIVE\")+os.getenv(\"HOMEPATH\")+r'\\Documents\\houdini16.0'\n if os.path.exists(houdiniEnvPath)==1:\n shutil.copy(r'\\\\file-cluster\\GDC\\Resource\\Development\\Maya\\GDC\\Plug\\Python\\GDC\\Houdini\\Houdini16.0\\env\\houdini.env'\n ,houdiniEnvPath+'\\houdini.env')\n ctypes.windll.user32.MessageBoxW(0, u'已经配置完成', u'警告', 64)\n else:\n ctypes.windll.user32.MessageBoxW(0, u'配置未完成', u'警告', 64)\n\nif __name__ == \"__main__\":\n copyEnvFile()\n","sub_path":"OLD/idmt/standalone/copyEnvFile_houdni16.py","file_name":"copyEnvFile_houdni16.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"528330234","text":"import paho.mqtt.client as mqtt\nimport time\nimport json\n# feel free to change out print\ntopic= [(\"/team18/s\", 0), (\"/team18/ahmed\",0), (\"/team18/jacob\", 0), (\"/team18/rocky\", 0), (\"/team18/jie\",0)]\n\n\ndef on_connect(client, userdata, flags, rc):\n\t#print(\"connected with result code\"+str(rc) )\n\t#print(\"subscribing on \"+str(topic) )\n\tclient.subscribe(topic) #<----subscribing topie\n\ncount=0\nlast_msg=dict()\nrocky1=0\nahmed2=0\njacob3=0\njie4=0\nlast_time= \" \"\nRo_stat=0\nAh_stat=0\nJa_stat=0\nji_stat=0\n\ndef on_message(client, userdata, msg):\n\t#readIN=str( msg.payload.decode())\n\tglobals_dict = globals()\n\t#print(globals_dict)\n#\ttry:\n\treadIN=json.loads( msg.payload.decode() ) #<---change into dictionary\n#\texcept:\n#\t\tprint(\"~~ERROR~~\")\n#\tprint(msg.topic)\n\t#print(readIN)\n\tif msg.topic == \"/team18/s\":\n\t\t#print(readIN)\n\t\tif readIN['Board_ID'] == \"rocky\":\n\t\t\tsend={'From':\"rocky\",'Number of publish':readIN['Number_of_times_publish'],'successfully published:':rocky1,'Board Miss from Jacob':readIN['Number_of_missed_message_Jacob'],'Board Miss from ahmed':readIN['Number_of_missed_message_Ahmed'],'Board Miss from jie':readIN['Number_of_missed_message_Jie'],'Time':last_time}\n\t\tif readIN['Board_ID']==\"ahmed\":\n\t\t\tsend={'From':\"ahmed\",'Number of publish':readIN['Number_of_times_publish'],'successfully published:':ahmed2,'Board Miss from Jacob':readIN['Number_of_missed_message_Jacob'],'Board Miss from Jie':readIN['Number_of_missed_message_Jie'],'Board Miss from rocky':readIN['Number_of_missed_message_Rocky'],'Time':last_time}\n\t\tif readIN['Board_ID']==\"jacob\":\n\t\t\tsend={'From':\"jacob\",'Number of publish':readIN['Number_of_times_publish'],'successfully published:':jacob3,'Board Miss from Jie':readIN['Number_of_missed_message_Jie'],'Board Miss from ahmed':readIN['Number_of_missed_message_Ahmed'],'Board Miss from rocky':readIN['Number_of_missed_message_Rocky'],'Time':last_time}\n\t\tif readIN['Board_ID']==\"jie__\":\n\t\t\tsend={'From':\"jie\",'Number of publish':readIN['Number_of_times_publish'],'successfully published:':jie4,'Board Miss from Jacob':readIN['Number_of_missed_message_Jacob'],'Board Miss from ahmed':readIN['Number_of_missed_message_Ahmed'],'Board Miss from rocky':readIN['Number_of_missed_message_Rocky'],'Time':last_time}\n\t\t#print(\"successfully published: \"+str(ID) )\n\t\t#print(\"Board Miss: \"+ str(readIN['Missed']) )\n\t\t#print(\"Time: \"+ last_time)\n\t\t#print(\"~~~~~fuck~~~~~\")\n\t\t#send={'Board ID':readIN['Board_ID'],'Number of publish':readIN['Number_of_times_publish'],'successfully published:':ID,'Board Miss: ':readIN['Number_of_missed_message_T1'],'Time: ':last_time }\n\t\tj=json.dumps(send)\n\t\tclient.publish(\"topic/display\", j)\n\tif msg.topic == \"/team18/rocky\":\n\t\tglobals_dict['last_time']= time.asctime(time.localtime(time.time()) )\n\t\tif last_msg!= readIN:\n\t\t\tglobals_dict['rocky1']+=1\n\tif msg.topic == \"/team18/ahmed\":\n\t\tglobals_dict['last_time']= time.asctime(time.localtime(time.time()) )\n\t\tif last_msg!= readIN:\n\t\t\tglobals_dict['ahmed2']+=1\n\tif msg.topic == \"/team18/jacob\":\n\t\tglobals_dict['last_time']= time.asctime(time.localtime(time.time()) )\n\t\tif last_msg!= readIN:\n\t\t\tglobals_dict['jacob3']+=1\n\tif msg.topic == \"/team18/jie\":\n\t\tglobals_dict['last_time']= time.asctime(time.localtime(time.time()) )\n\t\tif last_msg!= readIN:\n\t\t\tglobals_dict['jie4']+=1\n\n\tglobals_dict['last_msg'] = readIN\n\t#globals_dict['last_time']= time.asctime(time.localtime(time.time()) )\n\nclient=mqtt.Client()\n#client.connect(\"localhost\",1883,60)\nclient.connect(\"192.168.4.1\",1883,60) #<--this ip address of broker\nclient.on_connect=on_connect\nclient.on_message=on_message\nclient.loop_forever()\n","sub_path":"subscriber_math.py","file_name":"subscriber_math.py","file_ext":"py","file_size_in_byte":3582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"288269604","text":"from django.urls import re_path\nfrom .views import QuizListView, CategoriesListView, \\\n ViewQuizListByCategory, QuizUserProgressView, QuizMarkingList, \\\n QuizMarkingDetail, QuizDetailView, QuizTake, index, login_user, logout_user, signup\n\nurlpatterns = [\n re_path(r'^$', index, name='index'),\n re_path(r'^login/$', login_user, name='login'),\n re_path(r'^logout/$', logout_user, name='logout'),\n re_path(r'^signup/$', signup, name='signup'),\n re_path(r'^quizzes/$', QuizListView.as_view(), name='quiz_index'),\n re_path(r'^category/$', CategoriesListView.as_view(), name='quiz_category_list_all'),\n re_path(r'^category/(?P[\\w|\\W-]+)/$', ViewQuizListByCategory.as_view(), name='quiz_category_list_matching'),\n re_path(r'^progress/$', QuizUserProgressView.as_view(), name='quiz_progress'),\n re_path(r'^marking/$', QuizMarkingList.as_view(), name='quiz_marking'),\n re_path(r'^marking/(?P[\\d.]+)/$', QuizMarkingDetail.as_view(), name='quiz_marking_detail'),\n # passes variable 'quiz_name' to quiz_take view\n re_path(r'^(?P[\\w-]+)/$', QuizDetailView.as_view(), name='quiz_start_page'),\n re_path(r'^(?P[\\w-]+)/take/$', QuizTake.as_view(), name='quiz_question'),\n]\n","sub_path":"quiz/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"160112739","text":"import struct\nimport asyncio\nimport packets_pb2\n\n#https://asyncio.readthedocs.io/en/latest/\n\n\nasync def write(writer, msg):\n msgName = msg.DESCRIPTOR.name\n data = msg.SerializeToString()\n msgNameLen = len(msgName)\n dataLen = len(data)\n msgLen = 4 + 4 + msgNameLen + dataLen\n\n print(\"msgLen {} msgName {} dataLen {} data {}\".format(msgLen, msgName, dataLen, data))\n\n fmt = '!II%ds%ds' % (msgNameLen, dataLen)\n frame = struct.pack(fmt, msgLen, msgNameLen, msgName.encode(), data)\n\n print(\"frame {}\".format(frame))\n\n writer.write(frame)\n await writer.drain()\n\n\nasync def tcp_echo_client(message, loop):\n reader, writer = await asyncio.open_connection('127.0.0.1', 8081,\n loop=loop)\n\n login = packets_pb2.LoginRequest()\n login.userID = \"jaeseok\"\n\n await write(writer, login)\n\n data = await reader.read(100)\n print('Received: %r' % data.decode())\n\n\n getFriends = packets_pb2.GetFriendsRequest()\n\n await write(writer, getFriends)\n data = await reader.read(100)\n print('Received: %r' % data.decode())\n \n print('Close the socket')\n writer.close()\n\n\nmessage = 'Hello World!'\nloop = asyncio.get_event_loop()\nloop.run_until_complete(tcp_echo_client(message, loop))\nloop.close()","sub_path":"bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"428476209","text":"\"\"\"\nTime Complexity : O(LogN)\nSpace Complexity : O(1)\nDid this code successfully run on Leetcode : yes\nAny problem you faced while coding this : no\n\"\"\"\nclass Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n \n # Just find the first position of target or leftmost\n # Because array is sorted, moving right is keeping same increasing, moving left is keeping same or decreasing.\n def findtarget(nums, target):\n low = 0\n high = len(nums) - 1\n found = len(nums)\n\n while(low <= high):\n\n mid = low + (high - low) // 2\n\n # Move to left, if target found and keep recording last place where we hit target\n if(nums[mid] >= target):\n found = mid\n high = mid - 1\n \n # Stop moving left, if curr < target, move right\n else:\n low = mid + 1\n return found\n \n first_pos = findtarget(nums, target)\n last_pos = findtarget(nums, target +1) - 1\n if(first_pos <= last_pos):\n return [first_pos, last_pos]\n else:\n return [-1,-1]\n ","sub_path":"findFirstandLast.py","file_name":"findFirstandLast.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"151230311","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# ylgongPw @ 2020-02-27 15:25:03\nfrom __future__ import unicode_literals\nfrom __future__ import absolute_import\n\nfrom typing import List\n\n\nclass Solution:\n def dailyTemperatures(self, T: List[int]) -> List[int]:\n vals = [0]*len(T)\n stack = []\n\n for i,tmp in enumerate(T):\n #后一位大于前一位\n while stack and tmp > stack[-1][1]:\n index,_ = stack.pop()\n vals[index] = i - index \n\n stack.append((i,tmp))\n\n return vals\n\n\n\n\nif __name__ == '__main__':\n alist = [55,38,53,81,61,93,97,32,43,78]\n S = Solution()\n ret = S.dailyTemperatures(alist)\n","sub_path":"739/739-my.py","file_name":"739-my.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"367023749","text":"import sqlite3 as sql\nimport tkinter as tk\nfrom tkinter.constants import NONE\nimport tkinter.messagebox\ndef get_table():\n db_mail = sql.connect('mail_list.db')\n return db_mail\n\ndef set_frame(): \n win=tk.Tk()\n win.title('Mail List')\n win.geometry('512x512')\n #建立窗口 \n menu_1=tk.Menu(win)\n win.config(menu=menu_1)\n #建立菜单\n menu_1.add_command(label='增加', command=func_add)\n\n menu_1.add_command(label='删除', command=func_delete)\n\n menu_1.add_command(label='查询', command=func_inquire)\n\n menu_1.add_command(label='修改', command=func_change)\n\n menu_1.add_command(label='查看', command=func_examine)\n win.mainloop()\n\ndef func_add():\n global win1,member_name,member_gender,member_age,member_phone\n win1=tk.Toplevel()\n #提供一个对话框进行输入\n win1.title('增加') \n win1.geometry('400x300')\n\n L1= tk.Label(win1, text=\"姓名\",bg='white',width=6, height=1).grid(row=1,column=0,padx=20, pady=10)\n L2= tk.Label(win1, text=\"性别\",bg='white',width=6, height=1).grid(row=2,column=0,padx=20, pady=10)\n L3= tk.Label(win1, text=\"年龄\",bg='white',width=6, height=1).grid(row=3,column=0,padx=20, pady=10)\n L4= tk.Label(win1, text=\"电话\",bg='white',width=6, height=1).grid(row=4,column=0,padx=20, pady=10)\n\n member_name=tk.StringVar()\n member_name.set('')\n member_gender=tk.StringVar()\n member_gender.set('')\n member_age=tk.StringVar()\n member_age.set('')\n member_phone=tk.StringVar()\n member_phone.set('')\n\n entry_name=tk.Entry(win1,textvariable=member_name).grid(row=1,column=1,padx=20, pady=10)\n entry_gender=tk.Entry(win1,textvariable=member_gender).grid(row=2,column=1,padx=20, pady=10)\n entry_age=tk.Entry(win1,textvariable=member_age).grid(row=3,column=1,padx=20, pady=10)\n entry_phone=tk.Entry(win1,textvariable=member_phone).grid(row=4,column=1,padx=40, pady=10)\n\n button_add=tk.Button(win1,text='增加',width=20,height=2,command=insert_data)\n button_add.grid(row=5,column=1,padx=20, pady=10)\n win1.mainloop()\n\ndef insert_data():\n args=(member_name.get(),member_gender.get(),member_age.get(),member_phone.get())\n try:\n table = get_table()\n c = table.cursor()\n c.execute(\"SELECT * FROM mail WHERE phone =(?)\",(member_phone.get(),))\n result=c.fetchone()\n #判断电话是否存在\n if result == None:\n c.execute(\"INSERT INTO mail VALUES (?,?,?,?)\",args) \n tkinter.messagebox.showinfo(title='恭喜', message='增加成功' )\n win1.destroy()\n #不存在即插入信息\n else:\n tkinter.messagebox.showinfo(title='警告',message='该电话已存在') \n member_name.set('') \n member_gender.set('')\n member_age.set('')\n member_phone.set('')\n #若存在则清空输入的信息,并提示该电话已存在\n except Exception as ex:\n tkinter.messagebox.showinfo(title='警告', message=ex )\n win1.destroy()\n table.commit()\n c.close()\n table.close()\n #保存修改并关闭连接\n\ndef func_delete():\n global win2,member_name,member_phone\n win2=tk.Toplevel()\n win2.title('删除') \n win2.geometry('400x300')\n \n L1= tk.Label(win2, text=\"姓名\",bg='white',width=6, height=1).grid(row=1,column=0,padx=20, pady=10)\n L4= tk.Label(win2, text=\"电话\",bg='white',width=6, height=1).grid(row=2,column=0,padx=20, pady=10)\n\n member_name=tk.StringVar()\n member_name.set('')\n member_phone=tk.StringVar()\n member_phone.set('')\n\n entry_name=tk.Entry(win2,textvariable=member_name).grid(row=1,column=1,padx=20, pady=10)\n entry_phone=tk.Entry(win2,textvariable=member_phone).grid(row=2,column=1,padx=40, pady=10)\n\n button_inquire=tk.Button(win2,text='删除',width=20,height=2,command=delete_data)\n button_inquire.grid(row=5,column=1,padx=20, pady=10)\n win2.mainloop()\n\ndef delete_data():\n try:\n table = get_table()\n c = table.cursor()\n c.execute(\"SELECT * FROM mail WHERE phone =(?)\",(member_phone.get(),))\n result=c.fetchone()\n if result == None:\n tkinter.messagebox.showinfo(title='警告',message='该电话不存在')\n member_name.set('') \n member_phone.set('')\n else:\n c.execute(\"DELETE FROM mail WHERE NAME =(?) AND PHONE =(?)\",(member_name.get(),member_phone.get())) \n tkinter.messagebox.showinfo(title='恭喜', message='删除成功' )\n win2.destroy()\n except Exception as ex:\n tkinter.messagebox.showinfo(title='警告', message=ex )\n win2.destroy()\n table.commit()\n c.close()\n table.close()\n \ndef func_inquire():\n global win3,member_name\n win3=tk.Toplevel()\n win3.title('查询') \n win3.geometry('400x300')\n \n L1= tk.Label(win3, text=\"姓名\",bg='white',width=6, height=1).grid(row=1,column=0,padx=20, pady=10)\n\n member_name=tk.StringVar()\n member_name.set('')\n\n entry_name=tk.Entry(win3,textvariable=member_name).grid(row=1,column=1,padx=20, pady=10)\n\n button_inquire=tk.Button(win3,text='查询',width=20,height=2,command=inquire_data)\n button_inquire.grid(row=5,column=1,padx=20, pady=10)\n win3.mainloop()\n\ndef inquire_data():\n try:\n table=get_table()\n c=table.cursor()\n c.execute(\"SELECT * FROM mail WHERE NAME =(?)\",(member_name.get(),))\n #参数后面带有一个逗号,当不带有这个逗号时会报错\n results = c.fetchone()\n if results == None:\n tkinter.messagebox.showinfo(title='警告', message='未查询到该信息')\n member_name.set('') \n else:\n win_inquire=tk.Toplevel()\n win_inquire.title('查询结果')\n win_inquire.geometry('400x300')\n L1= tk.Label(win_inquire, text=\"姓名\",bg='white',width=6, height=1).grid(row=1,column=0,padx=20, pady=10)\n L2= tk.Label(win_inquire, text=\"性别\",bg='white',width=6, height=1).grid(row=2,column=0,padx=20, pady=10)\n L3= tk.Label(win_inquire, text=\"年龄\",bg='white',width=6, height=1).grid(row=3,column=0,padx=20, pady=10)\n L4= tk.Label(win_inquire, text=\"电话\",bg='white',width=6, height=1).grid(row=4,column=0,padx=20, pady=10)\n\n L5= tk.Label(win_inquire, text=results[0],bg='white',width=6, height=1).grid(row=1,column=1,padx=20, pady=10)\n L6= tk.Label(win_inquire, text=results[1],bg='white',width=6, height=1).grid(row=2,column=1,padx=20, pady=10)\n L7= tk.Label(win_inquire, text=results[2],bg='white',width=6, height=1).grid(row=3,column=1,padx=20, pady=10)\n L8= tk.Label(win_inquire, text=results[3],bg='white',width=6, height=1).grid(row=4,column=1,padx=20, pady=10)\n\n def close_win_inquire():\n c.close() \n win_inquire.destroy()\n \n button_close=tk.Button(win_inquire,text='关闭',width=20,height=2,command=close_win_inquire)\n button_close.grid(row=5,column=1)\n win_inquire.mainloop()\n except Exception as ex:\n tkinter.messagebox.showinfo(title='警告', message=ex)\n win3.destroy()\n\ndef func_change():\n global win4\n win4=tk.Toplevel()\n win4.title('修改')\n win4.geometry('400x300')\n\n L1= tk.Label(win4, text=\"姓名\",bg='white',width=6, height=1).grid(row=1,column=0,padx=20, pady=10)\n L4= tk.Label(win4, text=\"电话\",bg='white',width=6, height=1).grid(row=2,column=0,padx=20, pady=10)\n\n global member_name,member_phone\n\n member_name=tk.StringVar()\n member_name.set('')\n member_phone=tk.StringVar()\n member_phone.set('') \n\n entry_name=tk.Entry(win4,textvariable=member_name).grid(row=1,column=1,padx=20, pady=10)\n entry_phone=tk.Entry(win4,textvariable=member_phone).grid(row=2,column=1,padx=40, pady=10)\n\n button_change=tk.Button(win4,text='修改',width=20,height=2,command=change_data)\n button_change.grid(row=5,column=1,padx=20, pady=10)\n win4.mainloop()\n\ndef change_data():\n try:\n table = get_table()\n c = table.cursor()\n c.execute(\"SELECT * FROM mail WHERE NAME =(?)\",(member_name.get(),))\n result=c.fetchone()\n if result ==None:\n tkinter.messagebox.showinfo(title='警告',message='该信息不存在')\n member_name.set('')\n member_phone.set('')\n else:\n c.execute(\"UPDATE mail set PHONE = (?) where NAME=(?)\",(member_phone.get(),member_name.get())) \n tkinter.messagebox.showinfo(title='恭喜', message='修改成功' )\n win4.destroy()\n except Exception as ex:\n tkinter.messagebox.showinfo(title='警告', message=ex)\n win4.destroy()\n table.commit()\n c.close()\n table.close()\n\ndef func_examine():\n win5= tk.Toplevel()\n win5.title('查看')\n win5.geometry('400x800')\n\n try:\n table=get_table()\n c=table.cursor()\n c.execute(\"SELECT * FROM mail \")\n results = c.fetchall()\n L1= tk.Label(win5, text=\"姓名\",bg='white',width=18, height=1).grid(row=0,column=0)\n L2= tk.Label(win5, text=\"性别\",bg='white',width=6, height=1).grid(row=0,column=1)\n L3= tk.Label(win5, text=\"年龄\",bg='white',width=6, height=1).grid(row=0,column=2)\n L4= tk.Label(win5, text=\"电话\",bg='white',width=6, height=1).grid(row=0,column=3)\n for x in range (0,len(results)):\n L5= tk.Label(win5, text=results[x][0],bg='white',width=18, height=1).grid(row=x+1,column=0)\n L6= tk.Label(win5, text=results[x][1],bg='white',width=6, height=1).grid(row=x+1,column=1)\n L7= tk.Label(win5, text=results[x][2],bg='white',width=6, height=1).grid(row=x+1,column=2)\n L8= tk.Label(win5, text=results[x][3],bg='white',width=6, height=1).grid(row=x+1,column=3)\n c.close()\n win5.mainloop()\n except Exception as ex:\n tkinter.messagebox.showinfo(title='警告', message=ex )\n\ndef register_frame():\n global user,password,win_login\n win_login = tk.Tk()\n win_login.title('通讯录')\n \n # 禁止拉伸窗口\n win_login.resizable(width = False, height = False)\n win_login.geometry('400x300')\n \n tk.Label(win_login,text='用户名',width=8).grid(row=1,column=1,padx=25,pady=20)\n tk.Label(win_login,text='密码',width=8).grid(row=2,column=1,padx=25,pady=20)\n \n user = tk.StringVar(win_login,value='')\n entry_user = tk.Entry(win_login,width=8,textvariable=user)\n entry_user.grid(row=1,column=2,padx=25,pady=20)\n \n password = tk.StringVar(win_login,value='')\n entry_passwd = tk.Entry(win_login,width=8,textvariable=password)\n entry_passwd.grid(row=2,column=2,padx=25,pady=20)\n \n tk.Button(win_login,text='登录',width=8,command=logon).grid(row=3,column=1,padx=25,pady=20)\n tk.Button(win_login,text='注册',width=8,command=register).grid(row=3,column=2,padx=25,pady=20)\n tk.Button(win_login,text='取消',width=8,command=cancel).grid(row=3,column=3,padx=25,pady=20)\n \n win_login.mainloop()\n\ndef register():\n try:\n table_user = sql.connect('user_restore.db')\n c = table_user.cursor()\n #连接到储存账号信息的库\n user_name = user.get()\n user_password = password.get()\n # 判断用户名是否存在\n c.execute('SELECT * FROM users WHERE user_name=(?)',(user_name,))\n result = c.fetchone()\n if result is None:\n try:\n c.execute('INSERT INTO users VALUES (?,?)',(user_name,user_password))\n table_user.commit()\n except:\n tkinter.messagebox.showinfo(title='警告', message='注册失败')\n else:\n tkinter.messagebox.showinfo(title='警告', message='用户名已经存在,请重新注册') \n\n except Exception as ex:\n tkinter.messagebox.showinfo(title='警告', message='注册失败,原因是:%s' % ex)\n\n c.close()\n table_user.close()\n\ndef logon():\n try:\n table_user = sql.connect('user_restore.db')\n c = table_user.cursor()\n #连接数据库\n user_name = user.get()\n user_password = password.get()\n c.execute('SELECT user_password FROM users WHERE user_name = (?)',(user_name,) )\n result=c.fetchone()\n if result==None:\n tkinter.messagebox.showinfo(title='警告', message='用户名错误,登录失败')\n elif result[0] == user_password:\n tkinter.messagebox.showinfo(title='恭喜', message='登录成功')\n win_login.destroy()\n set_frame()\n else:\n tkinter.messagebox.showinfo(title='警告', message='密码错误,登录失败')\n\n except Exception as ex:\n print(\"登录失败,失败原因为:%s\"% ex)\n c.close()\n table_user.close()\n\ndef cancel():\n\tuser.set('')\n\tpassword.set('')\n # 清空用户输入的用户名和密码\n\ndef main():\n register_frame()\n\nif __name__ == '__main__':\n main()\n","sub_path":"带登录功能的通讯录/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":13043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"429224509","text":"import os\nfrom fuzzyparsers import parse_date\nimport dateutil.parser as dparser\nimport datetime\nimport json\ncount = 0\nfor p,d,files in os.walk('col_sim'):\n for f in files:\n if f.endswith('.json'):\n to_read = os.path.join(p,f)\n with open(to_read, 'r') as f:\n doc = json.loads(f.read())\n for k, news in doc.items():\n for vv in news.get('links'):\n entities = vv.get('entities')\n transformed_date1 = None\n for entity in entities:\n try:\n transformed_date1 = dparser.parse(entities,fuzzy=True)\n break\n except:\n pass\n #print(transformed_date1)\n #print(vv.get('title'))\n #print(vv.get('text'))\n #print('******')\n count += 1\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"213297686","text":"# -*- coding: utf-8 -*-\n\nimport scrapy\nfrom DataCollector.items import DatacollectorItem\nimport re\n\n\nclass MoeGirlSpider(scrapy.Spider):\n\n name = \"MoeGirlSpider\"\n allowed_domains = [\"moegirl.org\"]\n base_url = \"https://zh.moegirl.org/\"\n urls = []\n\n def __init__(self, url=None, keyword=None, *args, **kwargs):\n super(MoeGirlSpider, self).__init__(*args, **kwargs)\n if url is None:\n self.start_urls = [self.base_url + keyword]\n else:\n self.start_urls = [url]\n self.urls = []\n self.offset = 0\n self.item = DatacollectorItem()\n self.item['polysemy'] = []\n\n def parse(self, response):\n self.item['reference'] = \"(引用来源:\" + response.url + \", 萌娘百科遵守的知识共享协议:CC BY-NC-SA 3.0)\\n\\n\"\n item_div = response.xpath(\"//div[@class='mw-body']\")\n self.item['title'] = item_div.xpath(\"./h1[@class='firstHeading']/text()\").extract()[0] + \"\\n\\n\"\n content_dom = response.xpath(\"//div[@class='mw-parser-output']\")\n content = ''\n\n for each in content_dom.xpath(\"./p | ./h2 | ./h3 | ./ul| ./div | ./table[@class='wikitable']\"):\n html_str = str(each.extract())\n dom_regex = re.compile(\"|\"\n \"|\"\n \"|
\"\n \"|\")\n html_str = html_str.replace(\"\", \"\\n\")\n html_str = html_str.replace(\"\\n\", \" \")\n html_str = re.compile(\"

|||
\").sub(\"\\n\\n\", html_str)\n html_str = html_str.replace(\"\\n\", \"(CRLFMark)\")\n html_str = dom_regex.sub(\"\", html_str)\n html_str = re.compile(\"<[^>]+>\").sub(\"\", html_str)\n html_str = re.compile(\"\\[([^\\]].*?)\\]\").sub(\"\", html_str)\n content += html_str\n\n content = content.replace(\"(CRLFMark)\", \"\\n\")\n content = content.replace(\"<\", \"<\")\n content = content.replace(\">\", \">\")\n content = content.replace(\"&\", \"&\")\n self.item['content'] = content\n\n yield self.item\n","sub_path":"DataCollector/spiders/moegirl_spider.py","file_name":"moegirl_spider.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"270412493","text":"import itertools\nimport warnings\nimport numpy\n\nclass CategoricalComparator(object):\n def __init__(self, category_names) :\n if '' in category_names :\n raise ValueError(\"'' is an invalid category name. \"\n \"'' is reserved for missing values.\")\n if '' in category_names :\n raise ValueError(\"None is an invalid category name. \"\n \"None is reserved for missing values.\")\n\n\n vector_length = vectorLength(len(category_names))\n \n categories = [(name, name) for name in category_names]\n categories += itertools.combinations(category_names, 2)\n self.dummy_names = categories[1:]\n \n self.categories = {}\n for i, (a, b) in enumerate(categories) :\n response = responseVector(i, vector_length)\n self.categories[(a,b)] = response\n self.categories[(b,a)] = response\n\n self.missing_response = numpy.array([numpy.nan] * int(vector_length))\n\n self.levels = set(category_names)\n\n def __call__(self, field_1, field_2):\n categories = (field_1, field_2)\n if categories in self.categories :\n return self.categories[categories]\n elif field_1 == '' or field_2 == '' :\n warnings.warn('In the dedupe 1.2 release, missing data will have to have a value of None. See http://dedupe.readthedocs.org/en/latest/Variable-definition.html#missing-data')\n return self.missing_response\n else :\n unmatched = set(categories) - self.levels\n\n raise ValueError(\"value(s) %s not among declared \"\\\n \"set of categories: %s\" %\n (unmatched, self.levels))\n\ndef vectorLength(n) :\n vector_length = (n + 1) * n / 2 # (n + r - 1) choose r\n vector_length -= 1 \n return vector_length\n \n\ndef responseVector(value, vector_length) :\n response = numpy.zeros(vector_length)\n if value :\n response[value - 1] = 1\n return response\n\n","sub_path":"categorical/categorical.py","file_name":"categorical.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"622164400","text":"import numpy as np, matplotlib.pyplot as mpl_plt, scipy.optimize as sci_opt\n\n# K, Pa\nTc, Pc = 647, 22064000\n# 1 atm\nP = 101325\n# molar mass\nLiCl, H2O = 42.394, 18.01\n\n\n# Input T is in C\ndef p_vap_water(T):\n A = [-7.585230, 1.839910, -11.781100, 22.670500, -15.939300, 1.755160]\n tau = 1 - (T + 273)/Tc\n\n if T == 0:\n return 0\n else:\n return Pc * np.exp((A[0]*tau + A[1]*np.power(tau, 1.5) + A[2]*np.power(tau, 3) + A[3]*np.power(tau, 3.5) + A[4]*np.power(tau, 4) + A[5]*np.power(tau, 7.5))/(1-tau))\n\n\n# Input T is in C\ndef p_vap_solution(x, T):\n pi = [0.28, 4.3, 0.6, 0.21, 5.1, 0.49, 0.362, -4.75, -0.4, 0.03]\n # convert mass to mole fraction\n w = x*LiCl / (x*LiCl + (1-x)*H2O)\n theta = (T + 273)/Tc\n\n A = 2 - np.power((1 + np.power((w/pi[0]), pi[1])), pi[2])\n B = np.power((1 + np.power((w/pi[3]), pi[4])), pi[5]) - 1\n f = A + B*theta\n pi25 = 1 - np.power((1 + np.power((w/pi[6]), pi[7])), pi[8]) - pi[9]*np.exp(-np.power((w - 0.1), 2)/0.005)\n\n return pi25 * f * p_vap_water(T)\n\n\ndef sol_limit(T):\n\n if -75.5 < T < -68.2:\n A = [-0.005340, 2.015890, -3.114590]\n elif -68.2 < T < -19.9:\n A = [-0.560360, 4.723080, -5.811050]\n elif -19.9 < T < 19.1:\n A = [-0.351220, 2.882480, -2.624330]\n elif 19.1 < T < 93.8:\n A = [-1.312310, 6.177670, -5.034790]\n else:\n A = [-1.356800, 3.448540, 0.0]\n\n theta = (T + 273) /Tc\n #quadratic formula\n # A[2]x^2 + A[1]x + A[0] = theta\n a, b, c = A[2], A[1], A[0] - theta\n w = (-b + np.sqrt(np.power(b, 2) - 4*a*c)) / (2*a)\n limit = w*(1/LiCl) / (w*(1/LiCl) + (1-w)*(1/H2O))\n\n return limit\n\n\ndef convert_F_to_C(T):\n return (T - 32) * 5/9\n\n\ndef convert_RH_to_Pa(RH, T):\n return RH * p_vap_water(T)\n\n\n# Input T is in F\ndef plot_VLE(Tin, Tout, Treg, RHin, RHout):\n Tin, Tout, Treg = convert_F_to_C(Tin), convert_F_to_C(Tout), convert_F_to_C(Treg),\n\n #linspace(0,1,100) generates 100 numbers between 0 and 1\n x_range_Tin = np.linspace(0.00001, sol_limit(Tin), 100)\n y_range_Tin = p_vap_solution(x_range_Tin, Tin)\n mpl_plt.plot(x_range_Tin, y_range_Tin, color = 'b', label = \"Indoor\")\n mpl_plt.plot(x_range_Tin[99], y_range_Tin[99], color = 'b', marker = 'o')\n\n # Creates straight line between two points\n x_range_RHin = (0, sol_limit(Tin))\n y_range_RHin = (convert_RH_to_Pa(RHin, Tin), convert_RH_to_Pa(RHin, Tin))\n mpl_plt.plot(x_range_RHin, y_range_RHin, linestyle = '--', label = \"Indoor R.H\")\n\n x_range_Treg = np.linspace(0.00001, sol_limit(Treg), 100)\n y_range_Treg = p_vap_solution(x_range_Treg, Treg)\n mpl_plt.plot(x_range_Treg, y_range_Treg, color = 'g', label = \"Regenerator\")\n mpl_plt.plot(x_range_Treg[99], y_range_Treg[99], color = 'g', marker = 'o')\n\n x_range_RHout = (0, sol_limit(Treg))\n y_range_RHout = (convert_RH_to_Pa(RHout, Tout), convert_RH_to_Pa(RHout, Tout))\n mpl_plt.plot(x_range_RHout, y_range_RHout, linestyle = '--', label = \"Outdoor R.H\")\n\n mpl_plt.legend()\n mpl_plt.xlabel(\"LiCl mole fraction\")\n mpl_plt.ylabel(\"Water Vapor Pressure (Pa)\")\n mpl_plt.show()\n\n return\n\n\n# T1 = operating, T2 = indoor/outdoor (only different for regen/outdoor)\ndef get_mole_fraction(T1, T2, RH, guess):\n T1, T2 = convert_F_to_C(T1), convert_F_to_C(T2)\n f = lambda x: p_vap_solution(x, T1) - convert_RH_to_Pa(RH, T2)\n\n return sci_opt.fsolve(f, guess)\n\n\ndef find_operating_range(Tin, Tout, Treg, RHin, RHout, guess):\n x_low = get_mole_fraction(Tin, Tin, RHin, guess)\n x_hi = get_mole_fraction(Treg, Tout, RHout, guess)\n\n return [x_low, x_hi]\n\n\ndef get_k(T):\n T = convert_F_to_C(T)\n operating_range = find_operating_range(72, 85, 105, .6, .8, .1)\n\n P_hi = p_vap_solution(operating_range[0], T)\n P_low = p_vap_solution(operating_range[1], T)\n\n return (P_hi + P_low) / P / 2\n\n\ndef find_water_removed(x_in, RH, T):\n T = convert_F_to_C(T)\n K = get_k(T)\n # 50 mol/s basis for air\n V_in = 50\n # 1 mol/s basis for LiCl -> L_in * x_in = 1\n L_in = 1 / x_in\n A = L_in/K*V_in\n percent_abs = (np.power(A, 2) - A) / (np.power(A, 2) - 1)\n return V_in * x_in * percent_abs\n\n\ndef plot_water_removed():\n range = find_operating_range(72, 85, 105, .6, .8, .1)\n x_range = np.linspace(range[0], range[1], 100)\n y_range = find_water_removed(x_range, .6, 72)\n\n mpl_plt.plot(x_range, y_range)\n mpl_plt.xlabel(\"LiCl mole fraction\")\n mpl_plt.ylabel(\"Water Removed (mol/s per mol/s of LiCl)\")\n mpl_plt.savefig(\"Water_Removed.png\")\n mpl_plt.show()\n\n return\n\n# plot_VLE(72, 85, 105, .6, .8)\nplot_water_removed()","sub_path":"VLE.py","file_name":"VLE.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"401810158","text":"# Definition for singly-linked list.\r\n# class ListNode(object):\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.next = None\r\n\r\nclass Solution(object):\r\n def swapPairs(self, head):\r\n \"\"\"\r\n :type head: ListNode\r\n :rtype: ListNode\r\n \"\"\"\r\n if head is None: return None\r\n elif head.next is None: return head\r\n newHead = head.next\r\n cur = head\r\n prev = None\r\n while cur is not None:\r\n if cur.next is None: break\r\n nextNextNode = cur.next.next\r\n nextNode = cur.next\r\n if prev is not None:\r\n prev.next = cur.next\r\n cur.next, nextNode.next = nextNextNode, cur\r\n prev = cur\r\n cur = nextNextNode\r\n return newHead ","sub_path":"leetcode/24.swap-nodes-in-pairs/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"101634536","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"A custom DNS server resolving uWSGI subscribed domains to localhost.\"\"\"\n\nimport copy\nimport binascii\nimport threading\n\ntry:\n import socketserver\nexcept ImportError:\n import SocketServer as socketserver\n\nfrom dnslib import RR, QTYPE\nfrom dnslib.server import BaseResolver, DNSRecord, UDPServer, DNSError\n\nfrom uwsgidns.logging import logger\nfrom uwsgidns.constants import LOCALHOST_ZONE, UWSGI_SUBSCRIPTIONS_KEY\n\n\nclass LocalDNSLogger(object):\n\n \"\"\"\n The class provides a default set of logging functions for the various\n stages of the request handled by a DNSServer instance which are\n enabled/disabled by flags in the 'log' class variable.\n\n To customise logging create an object which implements the LocalDNSLogger\n interface and pass instance to DNSServer.\n\n The methods which the logger instance must implement are:\n\n log_recv - Raw packet received\n log_send - Raw packet sent\n log_request - DNS Request\n log_reply - DNS Response\n log_truncated - Truncated\n log_error - Decoding error\n log_data - Dump full request/response\n \"\"\"\n\n def log_recv(self, handler, data):\n logger.debug(\"Received: [%s:%d] (%s) <%d> : %s\",\n handler.client_address[0],\n handler.client_address[1],\n handler.protocol,\n len(data),\n binascii.hexlify(data))\n\n def log_send(self, handler, data):\n logger.debug(\"Sent: [%s:%d] (%s) <%d> : %s\",\n handler.client_address[0],\n handler.client_address[1],\n handler.protocol,\n len(data),\n binascii.hexlify(data))\n\n def log_request(self, handler, request):\n logger.debug(\"Request: [%s:%d] (%s) / '%s' (%s)\",\n handler.client_address[0],\n handler.client_address[1],\n handler.protocol,\n request.q.qname,\n QTYPE[request.q.qtype])\n self.log_data(request)\n\n def log_reply(self, handler, reply):\n logger.debug(\"Reply: [%s:%d] (%s) / '%s' (%s) / RRs: %s\",\n handler.client_address[0],\n handler.client_address[1],\n handler.protocol,\n reply.q.qname,\n QTYPE[reply.q.qtype],\n \",\".join([QTYPE[a.rtype] for a in reply.rr]))\n self.log_data(reply)\n\n def log_truncated(self, handler, reply):\n logger.debug(\"Truncated Reply: [%s:%d] (%s) / '%s' (%s) / RRs: %s\",\n handler.client_address[0],\n handler.client_address[1],\n handler.protocol,\n reply.q.qname,\n QTYPE[reply.q.qtype],\n \",\".join([QTYPE[a.rtype] for a in reply.rr]))\n self.log_data(reply)\n\n def log_error(self, handler, e):\n logger.error(\"Invalid Request: [%s:%d] (%s) :: %s\",\n handler.client_address[0],\n handler.client_address[1],\n handler.protocol,\n e)\n\n def log_data(self, dnsobj):\n logger.debug(\"\\n\" + dnsobj.toZone(\" \") + \"\\n\")\n\n\nclass LocalResolver(BaseResolver):\n\n \"\"\"Respond with fixed localhost responses to specified domains requests.\n Proxy to the upstream server the other or drop them (proxy argument).\n \"\"\"\n\n def __init__(self, proxy=False, upstream=None):\n # Prepare the RRs\n self.rrs = RR.fromZone(LOCALHOST_ZONE)\n\n # Set which domain to serve\n self.domains = set()\n\n # Set the upstream DNS server\n if proxy and upstream:\n try:\n self.upstream, self.upstream_port = upstream.split(\":\")\n self.upstream_port = int(self.upstream_port)\n except ValueError:\n self.upstream = upstream\n self.upstream_port = 53\n finally:\n self.proxy = True\n else:\n self.proxy = False\n\n self.lock = threading.Lock()\n\n def add_domain_from_uwsgi(self, uwsgi_dict):\n \"\"\"\n If the uwsgi_dict is a valid subscription info dictionary,\n add its domain to the local domain list.\n \"\"\"\n try:\n # Unicode sandwich\n domain = uwsgi_dict[UWSGI_SUBSCRIPTIONS_KEY.encode()]\n domain = domain.decode()\n\n if not domain.endswith(\".\"):\n domain += \".\"\n\n if domain not in self.domains:\n with self.lock:\n self.domains.add(domain)\n logger.debug(\"add_domain_from_uwsgi added {}\".format(domain))\n except KeyError:\n logger.error(\"add_domain_from_uwsgi received a malformed dictionary.\")\n\n def add_domains(self, domains):\n \"\"\"\n Add each domain in domains to localhost.\n \"\"\"\n domains = {\n d + \".\" if not d.endswith(\".\") else d\n for d in domains\n }\n\n if domains != self.domains:\n with self.lock:\n self.domains = domains\n logger.debug(\"add_domains added {}\".format(domains))\n\n def resolve(self, request, handler):\n \"\"\"\n If the requested domain is local, resolve it to localhost.\n Otherwise, proxy or drop the request.\n \"\"\"\n\n reply = request.reply()\n qname = request.q.qname\n\n with self.lock:\n local_domain = str(qname) in self.domains\n\n if local_domain: # If we have to handle this domain:\n # Replace labels with request label\n for rr in self.rrs:\n a = copy.copy(rr)\n a.rname = qname\n reply.add_answer(a)\n else: # Otherwise proxy to upstream\n if not self.proxy:\n # Signal to the handler that this request has to be ignored.\n raise DNSError(\n \"{} not in local domain list and upstream proxy disabled.\".format(str(qname))\n )\n else:\n if handler.protocol == 'udp':\n proxy_r = request.send(self.upstream, self.upstream_port)\n else:\n proxy_r = request.send(\n self.upstream, self.upstream_port, tcp=True)\n reply = DNSRecord.parse(proxy_r)\n\n return reply\n\n\nclass ThreadedUDPServer(socketserver.ThreadingMixIn, UDPServer):\n\n \"\"\"Threads, yeah, better use them!\"\"\"\n pass\n","sub_path":"uwsgidns/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"205795323","text":"#!/usr/bin/python3\n\"\"\" Setting up API \"\"\"\n\nfrom models import storage\nfrom api.v1.views import app_views\nfrom flask import Flask, make_response, jsonify\nfrom flask_cors import CORS\nimport os\n\n\napp = Flask(__name__)\ncors = CORS(app, resources={r\"/*\": {\"origins\": \"0.0.0.0\"}})\napp.config['JSONIFY_PRETTYPRINT_REGULAR'] = True\napp.register_blueprint(app_views)\nHBNB_API_HOST = os.getenv(\"HBNB_API_HOST\")\nHBNB_API_PORT = os.getenv(\"HBNB_API_PORT\")\n\n\n@app.teardown_appcontext\ndef teardown_db(exception):\n \"\"\" teardown: declare a method to handle @app.teardown_appcontext that\n calls storage.close()\"\"\"\n storage.close()\n\n\n@app.errorhandler(404)\ndef found_not(error):\n \"\"\" 404 not found error \"\"\"\n return (make_response(jsonify({'error': 'Not found'}), 404))\n\nif __name__ == '__main__':\n if not HBNB_API_HOST:\n HBNB_API_HOST = \"0.0.0.0\"\n if not HBNB_API_PORT:\n HBNB_API_PORT = \"5000\"\n app.run(host=HBNB_API_HOST, port=HBNB_API_PORT, threaded=True)\n","sub_path":"api/v1/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"614662115","text":"import asyncio\nimport unittest\nfrom concurrent.futures import Future\nfrom threading import Thread\n\nimport rclpy\nimport rclpy.node\nfrom fastapi.testclient import TestClient\n\nfrom ..app import app\n\n\nclass RouteFixture(unittest.IsolatedAsyncioTestCase):\n @classmethod\n def setUpClass(cls):\n cls.asd = []\n cls.rcl_ctx = rclpy.Context()\n rclpy.init(context=cls.rcl_ctx)\n cls.rcl_executor = rclpy.executors.SingleThreadedExecutor(context=cls.rcl_ctx)\n\n cls.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(cls.loop)\n cls.client = TestClient(app)\n cls.client.__enter__()\n\n cls.node = rclpy.node.Node(\"test_node\", context=cls.rcl_ctx)\n\n @classmethod\n def tearDownClass(cls):\n cls.node.destroy_node()\n rclpy.shutdown(context=cls.rcl_ctx)\n asyncio.set_event_loop(cls.loop)\n cls.client.__exit__()\n\n def subscribe_one(self, Message, topic: str) -> Future:\n \"\"\"\n Returns a future that is set when the first subscription message is received.\n Need to call \"spin_until\" to start the subscription.\n \"\"\"\n fut = Future()\n\n def on_msg(msg):\n self.node.destroy_subscription(sub)\n fut.set_result(msg)\n\n sub = self.node.create_subscription(Message, topic, on_msg, 1)\n return fut\n\n def host_service_one(self, Service, srv_name: str, response):\n \"\"\"\n Hosts a service until a request is received. Returns a future that is set when\n the first request is received. The node is spun in a background thread.\n \"\"\"\n ros_fut = rclpy.task.Future(executor=self.rcl_executor)\n loop = asyncio.get_event_loop()\n fut = asyncio.Future()\n\n def on_request(request, _resp):\n ros_fut.set_result(request)\n return response\n\n srv = self.node.create_service(Service, srv_name, on_request)\n\n def spin():\n rclpy.spin_until_future_complete(self.node, ros_fut, self.rcl_executor, 1)\n self.node.destroy_service(srv)\n loop.call_soon_threadsafe(fut.set_result, ros_fut.result())\n\n Thread(target=spin).start()\n cli = self.node.create_client(Service, srv_name)\n if not cli.wait_for_service(1):\n raise RuntimeError(\"fail to create service\")\n return fut\n\n def spin_until(self, fut: rclpy.task.Future):\n rclpy.spin_until_future_complete(self.node, fut, self.rcl_executor)\n return fut.result()\n","sub_path":"packages/api-server/api_server/routes/test_fixtures.py","file_name":"test_fixtures.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"356781581","text":"import pandas as pd\nimport numpy as np\nfrom tensorflow.keras.utils import to_categorical\n\nclass Encoder:\n '''\n Base class for encoders.\n Inherit from this when creating an encoder type.\n '''\n\n def __init__(self, input_size, data_path, logger):\n self.input_size = input_size\n self.data_path = data_path\n self.logger = logger\n self.sample_classifier = [] \n \n def load_data(self):\n '''Read CSV file into pandas dataframe'''\n self.logger.debug('Reading data from CSV file: ' + self.data_path)\n self.df = pd.read_csv(self.data_path).drop('index', axis=1)\n return self.df\n\nclass ScalerEncoder(Encoder):\n def __init__(self, overlap=50, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.load_data()\n self.overlap = overlap\n\n def get_sample(self, index):\n self.sample_classifier = self.df.data.values\n sample = self.serialize_data(self.df.data.values)\n self.logger.debug(f'Serialized sample {index} ({len(sample)} elements)')\n\n # Feed the data continuosly until training stops\n # FOOD FOR THOUGHT: This will return the data in a loop\n # and will NEVER stop\n while True:\n for data in sample:\n yield data\n\n def serialize_data(self, sample):\n\n # Round the data to 3 decimal places then times it up to become an index\n sample = sample.round(3) * 1000\n # Number of buckets is the input size divided by the largest input in the sequence\n element_bucket_length = int(self.input_size) + 1\n # Converts the sample into categorical data\n\n serialized_sample = []\n\n for element in sample:\n element = int(element)\n # Get the index of the data in the categorical sample\n # minus_gap = 1 if index == 0 or index == len(element) - self.overlap else 0\n # Pad the left and right of the data with 0s and the data in the middle with 1s\n # padding_left = [0] * (index * element_bucket_length - self.overlap)\n # element_padding = [1] * (element_bucket_length + self.overlap * 2 - minus_gap)\n # padding_right = [0] * ((len(element) - index - 1) * element_bucket_length - self.overlap)\n # Add them all together and slap that shit into a new sample\n # serialized_sample.append(padding_left + element_padding + padding_right)\n new_sample = list(np.zeros(element_bucket_length, dtype=int))\n for i in range(element - self.overlap, element + self.overlap + 1):\n if i < 0 or i > len(new_sample) - 1:\n continue\n\n try:\n new_sample[i] = 1\n except:\n continue\n serialized_sample.append(new_sample)\n self.sample = sample\n return serialized_sample\n\nclass DiscreteEncoder(Encoder):\n ''' \n Converts input data to list of categorical data with padding\n that extends the index to the size of the bucket divided by\n the number of unique inputs\n '''\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.load_data()\n\n def get_sample(self, index):\n self.sample_classifier = self.df.data.values\n sample = self.serialize_data(self.df.data)\n self.logger.debug(f'Serialized sample {index} ({len(sample)} elements)')\n\n \n\n # Feed the data continuosly until training stops\n # FOOD FOR THOUGHT: This will return the data in a loop\n # and will NEVER stop\n while True:\n for data in sample:\n yield data\n\n def serialize_data(self, sample):\n sample = np.array(sample.values)\n # Number of buckets is the input size divided by the largest input in the sequence\n element_bucket_length = int(self.input_size / max(sample))\n # Converts the sample into categorical data\n categorical_sample = to_categorical(sample)[:, 1:]\n serialized_sample = []\n\n for element in categorical_sample:\n # Get the index of the data in the categorical sample\n index = np.argmax(element)\n # Pad the left and right of the data with 0s and the data in the middle with 1s\n padding_left = [0] * index * element_bucket_length\n element_padding = [1] * element_bucket_length\n padding_right = [0] * (len(element) - index - 1) * element_bucket_length\n # Add them all together and slap that shit into a new sample\n serialized_sample.append(padding_left + element_padding + padding_right)\n\n return serialized_sample","sub_path":"htm_latest/htm/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"481385629","text":"import random\nfrom ast import literal_eval\n\nfrom player import Player\nfrom room import Room\nfrom world import World\n\n# Load world\nworld = World()\n\n# You may uncomment the smaller graphs for development and testing purposes.\n# map_file = \"maps/test_line.txt\"\n# map_file = \"maps/test_cross.txt\"\n# map_file = \"maps/test_loop.txt\"\n# map_file = \"maps/test_loop_fork.txt\"\nmap_file = \"maps/main_maze.txt\"\n\n# Loads the map into a dictionary\nroom_graph = literal_eval(open(map_file, \"r\").read())\nworld.load_graph(room_graph)\n\n# Print an ASCII map\nworld.print_rooms()\n\nplayer = Player(world.starting_room)\n\n# Fill this out with directions to walk\n# e.g. traversal_path = ['n', 'n']\ntraversal_path = []\n\n##########################################################################\n# Solution\n##########################################################################\n# helper function\ndirections = ['n', 'e', 's', 'w']\ndef change_direction(direction, num): \n # clockwise\n return directions[(directions.index(direction) + num) % len(directions)]\n\n# initial values\nrooms_visited = dict() # e.g.{0:'w', 7:'w', ...}\nexits_not_visited = dict()\ncurrent_loop = []\nloops = [] # e.g. [current_loop, ...]\n\nexit = player.current_room.get_exits()[0] # get a random possible exit\nmoves = [(None, exit)]\n\ncount = 0\nwhile len(rooms_visited) < 500 and count < 2000: # early stop\n # current values\n exits = player.current_room.get_exits() # get all possible exits\n entry, next_entry, next_room = change_direction(exit, 2), None, None \n exit = entry\n\n # if exit is not valid, find a new direction\n while exit not in exits or next_room is None:\n exit = change_direction(exit, 1)\n next_entry = change_direction(exit, 2) # e.g. if exit current room at 'e', you will enter next room at 'w'.\n next_room = player.current_room.get_room_in_direction(exit)\n\n # get exits not visited yet\n if player.current_room.id not in exits_not_visited:\n exits_not_visited[player.current_room.id] = exits\n l = exits_not_visited[player.current_room.id]\n if entry in l: l.remove(entry)\n if exit in l: l.remove(exit)\n exits_not_visited[player.current_room.id] = l\n\n # handle a loop: if exit and enter the room at different exits, it is a loop.\n if next_room is not None and next_room.id in rooms_visited \\\n and rooms_visited[next_room.id] != next_entry:\n print(f'There is a loop starting at {next_room.id} ending at {player.current_room.id}!')\n # get all exits in the loop that are visited\n # check whether all exits in the loop are visited\n current_loop, move = [(player.current_room.id, exit)], (None, None)\n flag_all_visited = True\n for i in range(-1, -1-len(moves), -1):\n r, e = moves[i]\n current_loop.insert(0, moves[i])\n if r != next_room.id:\n if exits_not_visited[r]:\n flag_all_visited = False\n else:\n break\n \n # print(f'current loop: {current_loop}')\n # print(f'visited rooms: {rooms_visited}')\n # print(f'exits not visited: {exits_not_visited}')\n\n # if not all exits in the loop are visited, go back to the beginning of the loop\n if flag_all_visited == False:\n loops.append(current_loop) # store the current loop information\n while move[0] != next_room.id:\n move = moves.pop() # remove move history\n rooms_visited.pop(move[0], None) # remove room visit history accordingly\n player.travel(exit)\n exit = moves[-1][1]\n continue\n\n # if the move is part of current loop, visit the non-loop exit first\n if (player.current_room.id, exit) in current_loop:\n if player.current_room.id == current_loop[0]: # at the beginning of the loop\n continue\n else: # at some other vertex of the loop\n if player.current_room.id in exits_not_visited:\n l = exits_not_visited[player.current_room.id]\n if l: exit = l.pop()\n\n # log and move\n rooms_visited[player.current_room.id] = exit\n moves.append((player.current_room.id, exit))\n player.travel(exit)\n\n count += 1\ntraversal_path = [m[1] for m in moves[1:]]\n\n##########################################################################\n# TRAVERSAL TEST\n##########################################################################\nvisited_rooms = set()\nplayer.current_room = world.starting_room\nvisited_rooms.add(player.current_room.id)\n\nfor move in traversal_path:\n player.travel(move)\n visited_rooms.add(player.current_room.id)\n\nif len(visited_rooms) == len(room_graph):\n print(f\"TESTS PASSED: {len(traversal_path)} moves, {len(visited_rooms)} rooms visited\")\nelse:\n print(\"TESTS FAILED: INCOMPLETE TRAVERSAL\")\n print(f\"{len(room_graph) - len(visited_rooms)} unvisited rooms:\")\n print([r for r in range(500) if r not in visited_rooms])\n\n##########################################################################\n# UNCOMMENT TO WALK AROUND\n##########################################################################\n# player.current_room.print_room_description(player)\n# while True:\n# cmds = input(\"-> \").lower().split(\" \")\n# if cmds[0] in [\"n\", \"s\", \"e\", \"w\"]:\n# player.travel(cmds[0], True)\n# elif cmds[0] == \"q\":\n# break\n# else:\n# print(\"I did not understand that command.\")\n","sub_path":"adv_loops.py","file_name":"adv_loops.py","file_ext":"py","file_size_in_byte":5447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"596105307","text":"#! /usr/bin/env python\n\nimport angr\nfrom angrutils import plot_cfg, plot_cdg, hook0\n\n\ndef analyze(b, addr, name=None):\n start_state = b.factory.blank_state(addr=addr)\n start_state.stack_push(0x0)\n with hook0(b):\n cfg = b.analyses.CFGEmulated(fail_fast=True, starts=[addr], initial_state=start_state, context_sensitivity_level=2, keep_state=True, call_depth=100, normalize=True)\n\n plot_cfg(cfg, \"%s_cfg\" % (name), asminst=True, vexinst=False, debug_info=False, remove_imports=True, remove_path_terminator=True)\n\n cdg = b.analyses.CDG(cfg=cfg, start=addr)\n plot_cdg(cfg, cdg, \"%s_cdg\" % name, pd_edges=True, cg_edges=True)\n\n\nif __name__ == \"__main__\":\n proj = angr.Project(\"../samples/1.6.26-libjsound.so\", load_options={'auto_load_libs':False, 'main_opts': {'base_addr': 0x0}})\n main = proj.loader.main_object.get_symbol(\"Java_com_sun_media_sound_MixerSequencer_nAddControllerEventCallback\")\n analyze(proj, main.rebased_addr, \"libjsound\")\n\n proj = angr.Project(\"../samples/simple1\", load_options={'auto_load_libs':False})\n main = proj.loader.main_object.get_symbol(\"main\")\n analyze(proj, main.rebased_addr, \"simple1\")\n","sub_path":"examples/plot_cdg/plot_cdg_example.py","file_name":"plot_cdg_example.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"132487820","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom BarkleySimulation import BarkleySimulation\nfrom matplotlib.widgets import Button\nfrom matplotlib.widgets import Slider\n\ndef demo_chaotic():\n #for chaotic u^3 simulation\n Nx = 150\n Ny = 150\n deltaT = 1e-2\n epsilon = 0.08\n delta_x = 0.1\n D = 1/50\n h = D/delta_x**2#1.0#0.2\n print(h)\n #h = D over delta_x\n a = 0.75\n b = 0.06\n\n return BarkleySimulation(Nx, Ny, deltaT, epsilon, h, a, b)\n\ndef demo_oscillating():\n #for oscillations\n Nx = 200\n Ny = 200\n deltaT = 1e-2\n epsilon = 0.01\n h = 1.0#0.2\n a = 0.75\n b = 0.002\n\n return BarkleySimulation(Nx, Ny, deltaT, epsilon, h, a, b)\n\nsim = demo_chaotic()\n#sim.initialize_two_spirals()\nsim.initialize_random(42, 0.1)\n\nframe = 0\ndef update_new(data):\n global sim, frame\n for j in range(int(sskiprate.val)):\n sim.explicit_step(chaotic=True)\n frame += 1\n mat.set_data(sim._u)\n plt.title(frame, x = -0.15, y=-2)\n return [mat]\n\nfig, ax = plt.subplots()\n\nmat = ax.matshow(sim._u, vmin=0, vmax=1, interpolation=None, origin=\"lower\")\nplt.colorbar(mat)\nani = animation.FuncAnimation(fig, update_new, interval=0, save_count=50)\n\nclass StorageCallback(object):\n def save(self, event):\n global sim\n\n np.save(\"simulation_cache_u.cache\", sim._u)\n np.save(\"simulation_cache_v.cache\", sim._v)\n\n print(\"Saved!\")\n\n def load(self, event):\n global sim\n\n sim._u = np.load(\"simulation_cache_u.cache.npy\")\n sim._v = np.load(\"simulation_cache_v.cache.npy\")\n\n print(\"Loaded!\")\n\ncallback = StorageCallback()\naxsave = plt.axes([0.15, 0.01, 0.1, 0.075])\naxload = plt.axes([0.65, 0.01, 0.1, 0.075])\naxskiprate = plt.axes([0.15, 0.95, 0.60, 0.03])\n\nsskiprate = Slider(axskiprate, 'Skip rate', 1, 500, valinit=10, valfmt='%1.0f')\nbnext = Button(axsave, 'Save')\nbnext.on_clicked(callback.save)\nbprev = Button(axload, 'Load')\nbprev.on_clicked(callback.load)\n\nplt.show()\n","sub_path":"src/draft/barkley/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"201430111","text":"import os\nimport platform\nimport sys\n\nplatform.platform()\n\ndef get_commands(env, firmware):\n platform_name = platform.system().lower()\n\n BL_CMD = []\n APP_CMD = []\n\n flash_start = app_start = 0x08000000\n bootloader = None # env['UPLOAD_FLAGS'][0]\n upload_flags = env.get('UPLOAD_FLAGS', [])\n\n for line in upload_flags:\n flags = line.split()\n for flag in flags:\n if \"BOOTLOADER=\" in flag:\n bootloader = flag.split(\"=\")[1]\n elif \"VECT_OFFSET=\" in flag:\n offset = flag.split(\"=\")[1]\n if \"0x\" in offset:\n offset = int(offset, 16)\n else:\n offset = int(offset, 10)\n app_start = flash_start + offset\n env_dir = env['PROJECT_PACKAGES_DIR']\n if \"windows\" in platform_name:\n TOOL = os.path.join(\n env_dir,\n \"tool-stm32duino\", \"stlink\", \"ST-LINK_CLI.exe\")\n TOOL = '\"%s\"' % TOOL\n if bootloader is not None:\n BL_CMD = [TOOL, \"-c SWD SWCLK=8 -P\",\n bootloader, hex(flash_start)]\n APP_CMD = [TOOL, \"-c SWD SWCLK=8 -P\",\n firmware, hex(app_start), \"-RST\"]\n elif \"linux\" in platform_name:\n TOOL = os.path.join(\n env_dir,\n \"tool-stm32duino\", \"stlink\", \"st-flash\")\n if bootloader is not None:\n BL_CMD = [TOOL, \"write\", bootloader, hex(flash_start)]\n APP_CMD = [TOOL, \"--reset\", \"write\", firmware, hex(app_start)]\n elif \"os x\" in platform_name:\n print(\"OS X not supported at the moment\\n\")\n raise OSError\n else:\n print(\"Unknown operating system...\\n\")\n raise OSError\n\n return \" \".join(BL_CMD), \" \".join(APP_CMD)\n\n\ndef on_upload(source, target, env):\n firmware_path = str(source[0])\n\n BL_CMD, APP_CMD = get_commands(env, firmware_path)\n\n # flash bootloader\n if BL_CMD:\n print(\"Cmd: {}\".format(BL_CMD))\n env.Execute(BL_CMD)\n # flash application\n if APP_CMD:\n print(\"Cmd: {}\".format(APP_CMD))\n env.Execute(APP_CMD)\n","sub_path":"src/python/stlink.py","file_name":"stlink.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"573530304","text":"import requests\n\nLINK = 'http://stats.nba.com/stats/scoreboard?DayOffset=0&LeagueID=00&gameDate=01/18/2016'\n\n\ndef get_daily_standings():\n response = get(LINK)\n\n raw_json = response.json()\n\n team_daily_standings = {\n 'east': [],\n 'west': []\n }\n\n team_daily_standings['east'] += [\n {\n 'team': row[5],\n 'wins': row[7],\n 'losses': row[8],\n 'percentage': row[9],\n } for row in raw_json['resultSets'][4]['rowSet']\n ]\n\n team_daily_standings['west'] += [\n {\n 'team': row[5],\n 'wins': row[7],\n 'losses': row[8],\n 'percentage': row[9],\n } for row in raw_json['resultSets'][5]['rowSet']\n ]\n\n pretty_print(team_daily_standings)\n\n\ndef get(link):\n return requests.get(link)\n\n\ndef pretty_print(team_standings):\n for conf in team_standings:\n conf_standings = sorted(team_standings[conf], key=lambda t: t['percentage'], reverse=True)\n print()\n for team in conf_standings:\n print(' {team:<15}{wins:>2}\\t{losses:>2}\\t{percentage}\\t'.format(**team), print_spark_lines(team), team['team'])\n print()\n\n\ndef print_spark_lines(team):\n pluses = round(team['percentage'] * 85)\n return ''.join(['-'] * round(pluses))\n\n\ndef main():\n get_daily_standings()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"async.py","file_name":"async.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"535945677","text":"from tkinter import ttk\nimport tkinter as tk\n\n\nclass Fr_finalizacao(ttk.Frame):\n def __init__(self, parent):\n super().__init__(parent)\n\n\n # self.lb_entrega = ttk.Label(self, text='É para entrega:')\n \n self.cbt_cpf = ttk.Checkbutton(self, text='CPF na nota')\n self.cbt_entrega = ttk.Checkbutton(self, text='É para a entrega')\n \n # self.lb_cpf.grid()\n self.cbt_cpf.grid()\n self.cbt_entrega.grid()\n \n \n \nif __name__ == '__main__':\n root = tk.Tk()\n frame = Fr_finalizacao(root)\n frame.pack()\n root.geometry('500x500')\n root.mainloop()","sub_path":"17-EmDev/frameVenda_frFinalizacao.py","file_name":"frameVenda_frFinalizacao.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"550134858","text":"# Comment (Syed Rafay): Try returning appropriate response instead of 'abort(400)' so that the developer could know the reason for API failure response\n# Everything else seems to be fine and modular!!\n\nfrom flask import Flask,request,jsonify\nimport functools\n\napp = Flask(__name__)\n\n# Inverse Decorator : \n# - To reverse the incoming 'op' field in json request\n# - Example: {'op':'+', ... } should do '-' (subtraction) operation and vice versa. \n\ninverse_dict = {\n \"+\": \"-\",\n \"-\": \"+\",\n \"*\": \"/\",\n \"/\": \"*\"\n}\n\n# here 'f' is the function which is passed to this decorator\n# In this case, since we are applying this decorator to /calc, so it will be calculator_api view \ndef inverse(f):\n @functools.wraps(f)\n def inverse_logic(*args, **kwargs):\n # Access request object and modify incoming json request\n data = request.json\n if 'op' in data:\n operation = data['op']\n if operation in inverse_dict:\n request.json['op'] = inverse_dict[operation]\n else:\n abort(400)\n return f(*args, **kwargs)\n return inverse_logic\n\n\n@app.route(\"/\")\ndef hello_world():\n return 'Hello Task3 Flask API'\n\ndef calculate(op1,op2,op):\n if op == \"+\":\n return op1+op2\n if op == \"-\":\n return op1-op2\n if op == \"*\":\n return op1*op2\n if op == \"/\":\n return op1/op2\n else:\n return \"Invalid Operation\"\n\n\n@app.route(\"/calc\", methods=['POST'])\n@inverse\ndef calculator_api():\n try:\n data = request.json\n print(data)\n op = data[\"op\"]\n op1 = data[\"op1\"]\n op2 = data[\"op2\"]\n\n\n ans = calculate(op1,op2,op)\n resp = {\"result\": ans}\n \n except:\n resp = {\"result\": \"Bad json object\"}\n\n return jsonify(resp)\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", debug=True)\n\n","sub_path":"task4/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"632689226","text":"from datetime import datetime\nfrom datetime import date\nfrom datetime import time\n# python3 python.basics.py\nprint(\"hello\")\n\n# python functions\npython_global_var = 9\n\n\ndef python_functions():\n python_global_var = 10\n print(\"inside func\", python_global_var)\n\n\nprint(\"outside func\", python_global_var)\npython_functions()\n\n# python *args and params of functions\n\n\ndef _arg_function_(*args):\n for item in args:\n print(item)\n\n\n_arg_function_(1, 2, 3, 4, 5, 6)\n\n\ndef _params_function_(x, y, *nums):\n print(\"pass params without order. x is \", x, \" y is \", y)\n\n\n_params_function_(y=9, x=10)\n\n# conditions statement\nsmall = 0\nbig = 0\nif(small < big):\n print(\"Correct\")\nelif(small == big):\n print(\"They are all equal\")\nelse:\n print(\"incorrect\")\n\n# while loop\nwhileloop_var = 0\nwhile (whileloop_var < 10):\n print(whileloop_var)\n whileloop_var += 1\n\n# for loop\narr = [\"A\", \"B\", \"C\", \"D\"]\nfor target_list in arr:\n print(target_list)\n\n# for loop with index\nfor index, val in enumerate(arr):\n print(\"Index is \", index, \" and value is \", val)\n\n# class and inheritance\n\n\nclass Class1():\n def main(self):\n return \"This is Class1\"\n\n\nclass Class2(Class1):\n def mainClass2(self):\n c = Class1()\n print(c.main())\n print(\"this is Class2\")\n\n\nc = Class2()\nc.mainClass2()\n\n# Python Time\n\n\ntodaysDate = date.today()\nprint('todaysDate: ', todaysDate)\ngettodayday = todaysDate.day\nprint('gettodayday: ', gettodayday)\ntimeRightNow = datetime.now()\nprint('timeRightNow: ', timeRightNow)\n","sub_path":"python.basic.py","file_name":"python.basic.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"180102890","text":"from dodo_commands import Dodo\n\n\ndef _args():\n Dodo.parser.add_argument('--cov', action='store_true')\n Dodo.parser.add_argument('pytest_args', nargs=\"*\")\n args = Dodo.parse_args()\n args.no_capture = not Dodo.get_config(\"/PYTEST/capture\", True)\n args.reuse_db = Dodo.get_config(\"/PYTEST/reuse_db\", False)\n args.html_report = Dodo.get_config(\"/PYTEST/html_report\", None)\n args.test_file = Dodo.get_config(\"/PYTEST/test_file\", None)\n args.pytest_ini_filename = Dodo.get_config(\"/PYTEST/pytest_ini\", None)\n args.maxfail = Dodo.get_config(\"/PYTEST/maxfail\", None)\n args.pytest = Dodo.get_config(\"/PYTEST/pytest\", \"pytest\")\n args.coverage_dirs = Dodo.get_config(\"/PYTEST/coverage_dirs\", [])\n args.cwd = Dodo.get_config(\"/PYTEST/cwd\", Dodo.get_config(\"/ROOT/src_dir\"))\n return args\n\n\ndef _cov_args(args):\n cov_args = [\"--cov=%s\" % x for x in args.coverage_dirs]\n cov_args.extend(['--cov-report', 'html:/opt/pincamp/website/cov_html'])\n cov_args.extend(\n ['--cov-report', 'annotate:/opt/pincamp/website/cov_annotate'])\n return cov_args if args.cov else ['--no-cov'] if args.coverage_dirs else []\n\n\nif Dodo.is_main(__name__):\n args = _args()\n\n run_args = [\n *(args.pytest if isinstance(args.pytest, list) else [args.pytest]),\n *([args.test_file] if args.test_file else []),\n *_cov_args(args),\n *([\"--capture\", \"no\"] if args.no_capture else []),\n *([\"--reuse-db\"] if args.reuse_db else []),\n *([\"-c\", args.pytest_ini_filename]\n if args.pytest_ini_filename else []),\n *([\"--maxfail\", str(args.maxfail)] if args.maxfail else []),\n *([\"--html\", args.html_report] if args.html_report else []),\n ]\n\n Dodo.run(run_args, cwd=args.cwd)\n","sub_path":"dodo_webdev_commands/pytest.py","file_name":"pytest.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"570228791","text":"import json\n\n\"\"\"\nCreated by Carrie Yan 2017\n\nResponsed to: https://docs.google.com/document/d/1FijCJUC3WgwGgiz1TAiDrAuC5RG-iHzkjIsWf-ThRjo/edit\n\n\"\"\"\n\nclass Student:\n \"\"\"\n Docstring\n \"\"\"\n\n def __init__(self, name, coursetaken=list()):\n \"\"\"\n Docstring\n \"\"\"\n self.name = str(name)\n self.coursetaken = coursetaken\n\n def add_course(self, course_id):\n \"\"\"\n Docstring\n \"\"\"\n self.coursetaken.append(int(course_id))\n\n\nclass Course:\n \"\"\"\n Docstring\n \"\"\"\n def __init__(self, identifier, name, prof):\n \"\"\"\n Docstring\n \"\"\"\n self.identifier = int(identifier)\n self.name = str(name)\n self.prof = str(prof)\n\n\nclass Course_list:\n \"\"\"\n Docstring\n \"\"\"\n def __init__(self):\n \"\"\"\n Docstring\n \"\"\"\n self.courselist = list()\n\n def add_course(self, newcourse):\n \"\"\"\n @type newcourse: Course object\n \"\"\"\n if isinstance(newcourse, Course):\n self.courselist.append(newcourse)\n else:\n raise Exception('Invalid Type: Not class Student type')\n\n def get_course_id(self, coursename):\n \"\"\"\n Get course id from course name\n \"\"\"\n for cour22 in self.courselist:\n if cour22.name == coursename:\n return cour22.id\n else:\n return 'Not found'\n\n def get_course_name(self, courseid):\n \"\"\"\n Get course name from course id\n \"\"\"\n for cour in self.courselist:\n if cour.identifier == courseid:\n return cour.name\n else:\n return 'Not found'\n\n def lu_class(self, profname):\n \"\"\"\n Look up list of course id by professor name\n \"\"\"\n class_list = list()\n\n for cour in self.courselist:\n if cour.professor == profname:\n class_list.append(cour.identifier)\n return class_list\n\n\n\nclass Student_list:\n \"\"\"\n Docstring\n \"\"\"\n def __init__(self):\n \"\"\"\n Docstring\n \"\"\"\n self.studentlist = list()\n\n def add_student(self, newstudent):\n \"\"\"\n @type newstudent: Student object\n \"\"\"\n if isinstance(newstudent, Student):\n self.studentlist.append(newstudent)\n else:\n raise Exception('Invalid Type: Not class Student type')\n\n def lu_student(self, courseid):\n \"\"\"\n Look up student name by course id\n \"\"\"\n student_name = list()\n for stu in self.studentlist:\n if courseid in stu.coursetaken:\n student_name.append(stu.name)\n return student_name\n\nclass Professor:\n \"\"\"\n docstring\n \"\"\"\n def __init__(self, name, teaching=list()):\n \"\"\"\n\n \"\"\"\n self.name = name\n self.teaching = [str(teaching)] # course name\n\nclass Professor_list:\n \"\"\"\n docstring\n \"\"\"\n def __init__(self):\n \"\"\"\n\n \"\"\"\n self.proflist = list()\n\n def add_prof(self, professor):\n \"\"\"\n docstring\n \"\"\"\n self.proflist.append(professor)\n\n def prof_exist(self, professorname):\n \"\"\"\n Note that prof are identified by his name\n \"\"\"\n for prof_name in self.proflist:\n if prof_name.name == professorname:\n return True\n return False\n\n def add_prof_teaching(self, profname, classname):\n \"\"\"\n docstring\n \"\"\"\n for prof22 in self.proflist:\n if prof22.name == profname:\n prof22.teaching.append(classname)\n\n\nif __name__ == '__main__':\n with open('student_courses.json') as data_file:\n data = json.load(data_file)\n\n # new Student_list and Course_list object\n course_ = Course_list()\n student_ = Student_list()\n prof_ = Professor_list()\n\n # create Student list and Course List\n for i in data['courses']:\n new_course = Course(i['id'], i['name'], i['professor'])\n course_.add_course(new_course)\n\n for i in data['students']:\n new_student = Student(i['name'], i['courses'])\n student_.add_student(new_student)\n\n # create Professor list\n for i in data['courses']:\n if prof_.prof_exist(i['professor']):\n prof_.add_prof_teaching(i['professor'], i['name'])\n else:\n new_prof = Professor(i['professor'], i['name'])\n prof_.add_prof(new_prof)\n\n # for each course print out a list of students who are taking that course. Using the above example,\n # for the course Calculus A, you would print out Alice and any other students who are taking that course.\n print(' ')\n print('=============================')\n print('Question 1: student taken specific course:')\n\n for cour in course_.courselist:\n print(cour.name, ':', end='')\n print(student_.lu_student(cour.identifier))\n\n # Write a script that reads in the data from “student_courses.json”,\n # and for each professor print out a list of students who have taken a course taught by that professor.\n\n print(' ')\n print('=============================')\n print('Question 2: professor teaching students')\n\n for prof in prof_.proflist:\n print(prof.name, ':', end='')\n print(prof.teaching)\n\n","sub_path":"YNCN2017 Recruit/yncn.py","file_name":"yncn.py","file_ext":"py","file_size_in_byte":5323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"486137250","text":"from detectron2.structures import BoxMode\nimport detectron2.data.dataset_mapper as mapper\nfrom projects.ComplexRCNN.complexrcnn.augmentation import SSDAugmentation\nimport logging\nimport copy\nimport detectron2.data.detection_utils as utils\nimport numpy as np\nimport torch\n\n\nclass SSDMapper:\n \"\"\"\n SSD mapper for dataset_dict\n \"\"\"\n\n def __init__(self, cfg, is_train=True):\n self.aug = SSDAugmentation(cfg, is_train)\n logging.getLogger(mapper.__name__).info(\"SSD Mapper is enabled.\")\n\n self.img_format = cfg.INPUT.FORMAT\n self.mask_on = cfg.MODEL.MASK_ON\n self.mask_format = cfg.INPUT.MASK_FORMAT\n self.keypoint_on = cfg.MODEL.KEYPOINT_ON\n self.is_train = is_train\n\n def __call__(self, dataset_dict):\n \"\"\"\n Args:\n dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format.\n\n Returns:\n dict: a format that builtin models in detectron2 accept\n \"\"\"\n dataset_dict = copy.deepcopy(dataset_dict) # it will be modified by code below\n # USER: Write your own image loading if it's not from a file\n image = utils.read_image(dataset_dict[\"file_name\"], format=self.img_format)\n utils.check_image_size(dataset_dict, image)\n\n image = image.astype(np.float32)\n if self.is_train:\n bbox = np.array([x[\"bbox\"] for x in dataset_dict[\"annotations\"]], dtype=np.float32)\n label = np.array([x[\"category_id\"] for x in dataset_dict[\"annotations\"]])\n image, bbox, label = self.aug(image, bbox, label)\n\n assert len(label) == len(bbox)\n annos = []\n for i in range(len(label)):\n annos.append({\"category_id\": label[i], \"bbox\": bbox[i], \"bbox_mode\": BoxMode.XYXY_ABS})\n else:\n image = self.aug(image, None, None)\n\n image_shape = image.shape[:2] # h, w\n\n # Pytorch's dataloader is efficient on torch.Tensor due to shared-memory,\n # but not efficient on large generic data structures due to the use of pickle & mp.Queue.\n # Therefore it's important to use torch.Tensor.\n dataset_dict[\"image\"] = torch.as_tensor(image.transpose(2, 0, 1).astype(\"float32\"))\n # Can use uint8 if it turns out to be slow some day\n if not self.is_train:\n dataset_dict.pop(\"annotations\", None)\n dataset_dict.pop(\"sem_seg_file_name\", None)\n return dataset_dict\n\n if \"annotations\" in dataset_dict:\n # USER: Modify this if you want to keep them for some reason.\n for anno in dataset_dict[\"annotations\"]:\n if not self.mask_on:\n anno.pop(\"segmentation\", None)\n if not self.keypoint_on:\n anno.pop(\"keypoints\", None)\n\n # USER: Implement additional transformations if you have other types of data\n instances = utils.annotations_to_instances(\n annos, image_shape, mask_format=self.mask_format\n )\n dataset_dict[\"instances\"] = utils.filter_empty_instances(instances)\n\n return dataset_dict\n","sub_path":"projects/ComplexRCNN/complexrcnn/dataset_mapper.py","file_name":"dataset_mapper.py","file_ext":"py","file_size_in_byte":3135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"192950250","text":"import numpy as np\nimport os\n\n\ndistributions = ['uniform20']\nmodels = ['rnntanh', 'lstm']\nfor i in np.arange(0.1, 1, 0.1):\n distributions.append('geometric%s' % i)\n\nfoutput = open('averagetabletotal_lrate5.txt', 'wt')\nfoutput.write(('%15s'+'%10s'*2) % ('distribution', 'model', 'epochs*50'))\nfoutput.write('\\n')\nfor distribution in distributions:\n for model in models:\n if os.path.isfile('averagetables/%s/%s_layers1_units10_T20_lrate0.050_batch50_mom0.00_learningdecay1.00sgd.txt' % (distribution, model)):\n with open('averagetables/%s/%s_layers1_units10_T20_lrate0.050_batch50_mom0.00_learningdecay1.00sgd.txt' % (distribution, model)) as fhand:\n for line in fhand:\n tablelist = line.split()\n foutput.write('%15s' % distribution)\n foutput.write('%10s'*len(tablelist) % tuple(tablelist))\n foutput.write('\\n')\nfoutput.close() \n \n\n\n","sub_path":"tablegeneratorlrate5.py","file_name":"tablegeneratorlrate5.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"159320081","text":"'''\n:Copyright: 2015, EUMETSAT, All Rights Reserved.\n\nThis software was developed within the context of\nthe EUMETSAT Satellite Application Facility on\nNumerical Weather Prediction (NWP SAF), under the\nCooperation Agreement dated 25 November 1998, between\nEUMETSAT and the Met Office, UK, by one or more partners\nwithin the NWP SAF. The partners in the NWP SAF are\nthe Met Office, ECMWF, KNMI and MeteoFrance.\n\nThis module defines descriptors that will be used to control the access\nto the Options, Profiles and Rttov classes attributes.\n'''\n\nfrom __future__ import absolute_import, print_function\nimport os\nimport numpy as np\nfrom .rttype import wrapfloat\n\n\nclass GenericDescriptorRO(object):\n '''A descriptor that handles Read-Only values of any type.'''\n\n _doc_extra = \"This attribute is Read-Only.\"\n\n def __init__(self, category, target, doc='Undocumented attribute'):\n '''\n :param str category: name of the dictionary that will store the\n attribute value\n :param str target: name of the dictionary key that will be used to store\n the attribute value\n :param str doc: optional documentation string\n '''\n self._doc_update(doc)\n self._thedict = '_{}'.format(category)\n self._target = target\n\n def _doc_update(self, doc):\n self.__doc__ = doc + \"\\n\\n\" + self._doc_extra\n\n def __get__(self, instance, objtype=None): # @UnusedVariable\n if instance is None:\n return self\n return getattr(instance, self._thedict).get(self._target, None)\n\n def __set__(self, instance, value):\n raise AttributeError('This is a Read-Only attribute')\n\n\nclass _GenericDescriptorRW(GenericDescriptorRO):\n '''An abstract class for Read/Write descriptors.'''\n\n _doc_extra = \"This is a Read/Write attribute.\"\n\n def _target_init(self, instance, value):\n getattr(instance, self._thedict)[self._target] = value\n\n def __set__(self, instance, value):\n self._target_init(instance, value)\n\n\nclass _GenericDescriptorRWD(_GenericDescriptorRW):\n '''An abstract class for Read/Write/Delete descriptors.'''\n\n _doc_extra = \"This is a Read/Write attribute. \" \\\n \"It can be emptied using `del`.\"\n\n def __delete__(self, instance):\n if self._target in getattr(instance, self._thedict):\n del getattr(instance, self._thedict)[self._target]\n\n\nclass TypedDescriptorRW(_GenericDescriptorRW):\n '''A descriptor that handles Read/Write values of a given type.'''\n\n _doc_extra = \"This is a Read/Write attribute of type {!r}.\"\n\n def __init__(self, category, target, thetype,\n doc='Undocumented attribute'):\n '''\n :param str category: name of the dictionary that will store the\n attribute value\n :param str target: name of the dictionary key that will be used to store\n the attribute value\n :param type thetype: type of the attribute\n :param str doc: optional documentation string\n '''\n self._type = thetype\n super(TypedDescriptorRW, self).__init__(category, target, doc)\n\n def _doc_update(self, doc):\n self.__doc__ = doc + \"\\n\\n\" + self._doc_extra.format(self._type)\n\n def _target_init(self, instance, value):\n if isinstance(value, (tuple, list)):\n getattr(instance, self._thedict)[\n self._target] = self._type(* value)\n else:\n getattr(instance, self._thedict)[self._target] = self._type(value)\n\n\nclass FilepathDescriptorRWD(_GenericDescriptorRWD):\n\n \"\"\"A descriptor that handles a file's path (Read/Write).\"\"\"\n\n _doc_extra = \"This is a Read/Write attribute that contains a valid \" \\\n \"pathname to a file. It can be emptied using `del`.\"\n\n def _target_init(self, instance, value):\n if not os.path.isfile(value):\n raise ValueError(\"%s does not exists or is not a file\", value)\n super(FilepathDescriptorRWD, self)._target_init(instance, value)\n\n\nclass DirpathDescriptorRWD(_GenericDescriptorRWD):\n\n \"\"\"A descriptor that handles a directory's path (Read/Write/Delete).\"\"\"\n\n _doc_extra = \"This is a Read/Write attribute that contains a valid \" \\\n \"pathname to a directory. It can be emptied using `del`.\"\n\n def _target_init(self, instance, value):\n if not os.path.isdir(value):\n raise ValueError(\"%s does not exists or is not a directory\", value)\n super(DirpathDescriptorRWD, self)._target_init(instance, value)\n\n\nclass _GenericNumpyRW(_GenericDescriptorRW):\n\n '''An abstract class that handles ``numpy.ndarray`` objects.'''\n\n _doc_extra = \"This is a Read/Write attribute that holds a \" \\\n \"``numpy.ndarray`` of shape [{dim:s}]. When a new array is \" \\\n \"assigned to this attribute it will casted to a {dtype!r} \"\\\n \"array.\"\n _doc_dim = '?'\n\n def __init__(self, category, target, dtype=wrapfloat,\n doc='Undocumented attribute'):\n '''\n :param str category: name of the dictionary that will store the\n attribute value\n :param str target: name of the dictionary key that will be used to store\n the attribute value\n :param type dtype: desired typed for the ``numpy.ndarray``\n :param str doc: optional documentation string\n '''\n self._dtype = dtype\n super(_GenericNumpyRW, self).__init__(category, target, doc)\n\n def _doc_update(self, doc):\n self.__doc__ = (doc + \"\\n\\n\" +\n self._doc_extra.format(dim=self._doc_dim,\n dtype=self._dtype))\n\n def _cast2dtype(self, value):\n # Try to convert the input to a ndarray\n if not isinstance(value, np.ndarray):\n try:\n npvalue = np.array(value, dtype=self._dtype)\n except(StandardError):\n raise TypeError(\"Should be castable in a numpy.ndarray \" +\n \"with type {:s}\".format(self._dtype))\n # If it's already a ndarray, check the type...\n else:\n if value.dtype is not np.dtype(self._dtype):\n try:\n npvalue = np.array(value, dtype=self._dtype)\n except(StandardError):\n raise TypeError(\"Should be a numpy.ndarray of type \" +\n \"{:s}. \".format(self._dtype) +\n \"Or something compatible\")\n else:\n npvalue = value\n return npvalue\n\n def _target_init(self, instance, value):\n getattr(instance, self._thedict)[\n self._target] = self._cast2dtype(value)\n\n\nclass VerticalProfilesRW(_GenericNumpyRW):\n '''\n A descriptor that handles Read/Write values of a nprofiles/nlevels array.\n '''\n\n _doc_dim = 'nprofiles,nlevels'\n\n def _target_init(self, instance, value):\n npvalue = self._cast2dtype(value)\n # Check the array's shape\n if npvalue.shape == (instance.Nprofiles, instance.Nlevels):\n getattr(instance, self._thedict)[self._target] = npvalue\n else:\n raise ValueError(\"Incorrect number of profiles and/or levels\")\n\n\nclass VerticalProfilesRWD(VerticalProfilesRW, _GenericDescriptorRWD):\n '''\n A descriptor that handles Read/Write/Delete values of a nprofiles/nlevels\n array.\n '''\n\n _doc_extra = (VerticalProfilesRW._doc_extra +\n ' It can be emptied using `del`.')\n\n\nclass ArbitraryProfilesRW(_GenericNumpyRW):\n '''\n A descriptor that handles Read/Write values of a 2D array with a\n nprofiles first dimension and an arbitrary leading dimension.\n '''\n\n def __init__(self, category, target, dtype=wrapfloat, leadingdim=1,\n doc='Undocumented attribute'):\n '''\n :param str category: name of the dictionary that will store the\n attribute value\n :param str target: name of the dictionary key that will be used to store\n the attribute value\n :param int leadingdim: size of the leading dimension of the\n ``numpy.ndarray``\n :param type dtype: desired typed for the ``numpy.ndarray``\n :param str doc: optional documentation\n '''\n self._leadingdim = leadingdim\n if leadingdim > 1:\n self._doc_dim = 'nprofiles,{:d}'.format(leadingdim)\n else:\n self._doc_dim = 'nprofiles'\n super(ArbitraryProfilesRW, self).__init__(\n category, target, dtype, doc)\n\n def _target_init(self, instance, value):\n npvalue = self._cast2dtype(value)\n # Check the array's shape\n if self._leadingdim > 1:\n if npvalue.shape != (instance.Nprofiles, self._leadingdim):\n raise ValueError(\"Incorrect dimension\")\n else:\n if npvalue.shape != (instance.Nprofiles,):\n raise ValueError(\"Incorrect dimension\")\n getattr(instance, self._thedict)[self._target] = npvalue\n\n\nclass ArbitraryProfilesRWD(ArbitraryProfilesRW, _GenericDescriptorRWD):\n '''\n A descriptor that handles Read/Write/Del values of a 2D array with a\n nprofiles first dimension and an arbitrary leading dimension.\n '''\n\n _doc_extra = (ArbitraryProfilesRW._doc_extra +\n ' It can be emptied using `del`.')\n\n\nclass PickGasesRO(GenericDescriptorRO):\n '''A descriptor that handles a particular Gas of a gases array.'''\n\n def __init__(self, callback, gas_id, doc='Undocumented attribute'):\n '''\n :param func callback: method that will be called to return the\n appropriate gas\n :param str doc: optional documentation\n '''\n self._doc_update(doc)\n self._callback = callback\n self._gas_id = gas_id\n\n def __get__(self, instance, objtype=None): # @UnusedVariable\n if instance is None:\n return self\n return self._callback(instance, self._gas_id)\n","sub_path":"pyrttov/descriptor.py","file_name":"descriptor.py","file_ext":"py","file_size_in_byte":10033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"364438170","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nimport pandas as pd\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import datasets\nfrom sklearn import metrics\n\n# Importing dataset\ndata = pd.read_csv(\"C:/Users/Santhosh/Downloads/iris.csv\")\niris=datasets.load_iris()\nx_train,x_test,y_train,y_test=train_test_split(iris.data,iris.target,test_size=0.4,random_state=0)\nMltiNB= MultinomialNB()\nMltiNB.fit(x_train,y_train)\nprint(MltiNB)\ny_expect=y_test\ny_pred=MltiNB.predict(x_test)\nprint(y_pred)\nprint(y_test)\nprint(metrics.accuracy_score(y_test,y_pred))\nprint(metrics.precision_score(y_test,y_pred,average='macro'))\nprint(metrics.f1_score(y_test,y_pred,average='macro'))\nprint(metrics.recall_score(y_test,y_pred,average='macro'))","sub_path":"ICP4/icp4-1.py","file_name":"icp4-1.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"311585349","text":"from django.utils import timezone\nfrom django.core import exceptions\nfrom test_plus.test import TestCase\nfrom common.testhelpers.database import validate_save_and_reload\nfrom common.testhelpers.random_test_values import a_float, an_integer, a_string\nfrom qa_tool.tests.helpers import AlgorithmBuilder, SearchLocationBuilder\nfrom qa_tool.models import RelevancyScore\nfrom human_services.services_at_location.tests.helpers import ServiceAtLocationBuilder\nfrom newcomers_guide.tests.helpers import create_topic\n\n\nclass TestAlgorithmModel(TestCase):\n\n def test_has_name(self):\n algorithm = AlgorithmBuilder().build()\n algorithm_from_db = validate_save_and_reload(algorithm)\n self.assertEqual(algorithm_from_db.name, algorithm.name)\n\n def test_name_field_cannot_be_empty(self):\n name = ''\n algorithm = AlgorithmBuilder().with_name(name).build()\n with self.assertRaises(exceptions.ValidationError):\n algorithm.full_clean()\n\n def test_has_url(self):\n algorithm = AlgorithmBuilder().build()\n algorithm_from_db = validate_save_and_reload(algorithm)\n self.assertEqual(algorithm_from_db.url, algorithm.url)\n\n def test_url_field_cannot_be_empty(self):\n algorithm_url = ''\n algorithm = AlgorithmBuilder().with_url(algorithm_url).build()\n with self.assertRaises(exceptions.ValidationError):\n algorithm.full_clean()\n\n def test_has_notes(self):\n algorithm = AlgorithmBuilder().build()\n algorithm_from_db = validate_save_and_reload(algorithm)\n self.assertEqual(algorithm_from_db.notes, algorithm.notes)\n\n def test_notes_field_can_be_empty(self):\n algorithm = AlgorithmBuilder().with_notes('').build()\n algorithm_from_db = validate_save_and_reload(algorithm)\n self.assertEqual(algorithm_from_db.notes, '')\n\n\nclass TestSearchLocationModel(TestCase):\n def test_has_name(self):\n search_location = SearchLocationBuilder().build()\n search_location_from_db = validate_save_and_reload(search_location)\n self.assertEqual(search_location_from_db.name, search_location.name)\n\n def test_name_field_can_be_empty(self):\n search_location = SearchLocationBuilder().with_name('').build()\n search_location_from_db = validate_save_and_reload(search_location)\n self.assertEqual(search_location_from_db.name, '')\n\n def test_can_create_and_retrieve_point(self):\n location = SearchLocationBuilder().with_long_lat(a_float(), a_float()).build()\n location_from_db = validate_save_and_reload(location)\n self.assertEqual(location_from_db.point, location.point)\n\n\nclass TestScore(TestCase):\n def setUp(self):\n self.user = self.make_user()\n\n def test_can_create_row(self):\n value = an_integer()\n time_stamp = timezone.now()\n algorithm = AlgorithmBuilder().create()\n search_location = SearchLocationBuilder().create()\n service_at_location = ServiceAtLocationBuilder().create()\n topic = create_topic(a_string())\n score = RelevancyScore(value=value,\n time_stamp=time_stamp,\n algorithm=algorithm,\n search_location=search_location,\n service_at_location=service_at_location,\n topic=topic,\n user=self.user\n )\n score_from_db = validate_save_and_reload(score)\n\n self.assertEqual(score_from_db.value, value)\n self.assertEqual(score_from_db.algorithm, algorithm)\n self.assertEqual(score_from_db.time_stamp, time_stamp)\n self.assertEqual(score_from_db.search_location, search_location)\n self.assertEqual(score_from_db.service_at_location, service_at_location)\n self.assertEqual(score_from_db.user, self.user)\n","sub_path":"qa_tool/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":3909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"129844097","text":"# META_filename - name of the meta-file.json\n# GT_filename - name of the ground-truth.json\n# OUT_filename - file to write the output in (answers.json)\n# encoding - encoding of the texts (from json)\n# language - language of the texts (from json)\n# u_path - path of the 'unknown' dir in the corpus (from json)\n# candidates - list of candidate author names (from json)\n# unknowns - list of unknown filenames (from json)\n# trainings - dictionary with lists of filenames of training texts for each author\n# {\"candidate2\":[\"file1.txt\", \"file2.txt\", ...], \"candidate2\":[\"file1.txt\", ...] ...}\n# trueAuthors - list of true authors of the texts (from GT_filename json)\n# corresponding to 'unknowns'\n\n\"\"\"\nEXAMPLE:\n\nimport jsonhandler\n\ncandidates = jsonhandler.candidates\nunknowns = jsonhandler.unknowns\njsonhandler.load_json(\"test_corpus\")\n\n# If you want to do training:\njsonhandler.load_training()\nfor can in candidates:\n for file in jsonhandler.trainings[can]:\n # Get content of training file 'file' of candidate 'can' as a string with:\n # jsonhandler.get_training_text(can, file)\n\n# Create lists for your answers (and scores)\nauthors = []\nscores = []\n\n# Get Parameters from json-file:\nl = jsonhandler.language\ne = jsonhandler.encoding\n\nfor file in unknowns:\n # Get content of unknown file 'file' as a string with:\n # jsonhandler.get_unknown_text(file)\n # Determine author of the file, and score (optional)\n author = \"oneAuthor\"\n score = 0.5\n authors.append(author)\n scores.append(score)\n\n# Save results to json-file out.json (passing 'scores' is optional)\njsonhandler.store_json(unknowns, authors, scores)\n\n# If you want to evaluate the ground-truth file\nload_ground_truth()\n# find out true author of document unknowns[i]:\n# trueAuthors[i]\n\"\"\"\n\nimport os\nimport json\nimport codecs\n\nMETA_FILENAME = \"meta-file.json\"\nOUT_FILENAME = \"answers.json\"\nGT_FILENAME = \"ground-truth.json\"\n\n# initialization of global variables\nencoding = \"\"\nlanguage = \"\"\ncorpus_dir = \"\"\nu_path = \"\"\ncandidates = []\nunknowns = []\ntrainings = {}\ntrueAuthors = []\n\n\ndef load_json(corpus):\n \"\"\"\n always run this method first to evaluate the meta json file. Pass the\n directory of the corpus (where meta-file.json is situated)\n \"\"\"\n global corpus_dir, u_path, candidates, unknowns, encoding, language\n corpus_dir += corpus\n m_file = open(os.path.join(corpus_dir, META_FILENAME), \"r\")\n meta_json = json.load(m_file)\n m_file.close()\n\n u_path += os.path.join(corpus_dir, meta_json[\"folder\"])\n encoding += meta_json[\"encoding\"]\n language += meta_json[\"language\"]\n candidates += [author[\"author-name\"]\n for author in meta_json[\"candidate-authors\"]]\n unknowns += [text[\"unknown-text\"] for text in meta_json[\"unknown-texts\"]]\n\n\ndef load_training():\n \"\"\"\n run this method next, if you want to do training (read training files etc)\n \"\"\"\n for can in candidates:\n trainings[can] = []\n for subdir, dirs, files in os.walk(os.path.join(corpus_dir, can)):\n for doc in files:\n trainings[can].append(doc)\n\n\ndef get_training_text(can, filename):\n \"\"\"\n get training text 'filename' from candidate 'can' (obtain values from\n 'trainings', see example above)\n \"\"\"\n d_file = codecs.open(os.path.join(corpus_dir, can, filename), \"r\", \"utf-8\")\n s = d_file.read()\n d_file.close()\n return s\n\n\ndef get_training_bytes(can, filename):\n \"\"\"\n get training file as bytearray\n \"\"\"\n d_file = open(os.path.join(corpus_dir, can, filename), \"rb\")\n b = bytearray(d_file.read())\n d_file.close()\n return b\n\n\ndef get_unknown_text(filename):\n \"\"\"\n get unknown text 'filename' (obtain values from 'unknowns', see example above)\n \"\"\"\n d_file = codecs.open(os.path.join(u_path, filename), \"r\", \"utf-8\")\n s = d_file.read()\n d_file.close()\n return s\n\n\ndef get_unknown_bytes(filename):\n \"\"\"\n get unknown file as bytearray\n \"\"\"\n d_file = open(os.path.join(u_path, filename), \"rb\")\n b = bytearray(d_file.read())\n d_file.close()\n return b\n\n\ndef store_json(path, texts, cans, scores=None):\n \"\"\"\n run this method in the end to store the output in the 'path' directory as OUT_filename\n pass a list of filenames (you can use 'unknowns'), a list of your\n predicted authors and optionally a list of the scores (both must of\n course be in the same order as the 'texts' list)\n \"\"\"\n answers = []\n if scores is None:\n scores = [1 for _ in texts]\n for i in range(len(texts)):\n answers.append(\n {\"unknown_text\": texts[i], \"author\": cans[i], \"score\": scores[i]})\n f = open(os.path.join(path, OUT_FILENAME), \"w\")\n json.dump({\"answers\": answers}, f, indent=2)\n f.close()\n\n\ndef load_ground_truth():\n \"\"\"\n if you want to evaluate your answers using the ground-truth.json, load\n the true authors in 'trueAuthors' using this function\n \"\"\"\n t_file = open(os.path.join(corpus_dir, GT_FILENAME), \"r\")\n t_json = json.load(t_file)\n t_file.close()\n\n global trueAuthors\n for i in range(len(t_json[\"ground-truth\"])):\n trueAuthors.append(t_json[\"ground-truth\"][i][\"true-author\"])\n","sub_path":"jsonhandler.py","file_name":"jsonhandler.py","file_ext":"py","file_size_in_byte":5198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"417027041","text":"from Services.FacesRecognitionServices import FacesRecognitionService\nfrom Services.BodyRecognitionServices import BodyRecognitionServices\nfrom Domain.BodyCollection import BodyCollection\nfrom Services.SaveEmbeddingPkl import SaveEmbeddingPkl\nfrom datetime import timedelta\nfrom Utils.fileUtils import getNumber, getTime\nfrom Utils.constant import PLACES, MINIMUM_DURATION, timers, GAP\nfrom sklearn.metrics import average_precision_score\nfrom sklearn.ensemble import RandomForestRegressor\nfrom joblib import parallel_backend\nimport matplotlib.pyplot as plt\n\n\nimport os\nimport numpy as np\nimport pandas as pd\n\nclass RecognitionsController:\n\n def __init__(self, databaseFaces: str = \"\"):\n self._face_recognition = FacesRecognitionService(databaseFaces)\n self._body_recognition = BodyRecognitionServices()\n self.alignedGallery = os.path.join(\"data\", \"TCG_alignedReId\")\n file_df = os.path.join(\"data\", \"tgc_2020_tiempos_pasos_editado.xlsx\")\n self._step_time = GAP\n self._df = pd.read_excel(file_df)\n keys = self._df.keys()\n self._times = list(keys[7:18])\n self._cls_positions = list(keys[18:])\n self._loadServices = SaveEmbeddingPkl(self.alignedGallery)\n self._jobs = 4\n\n np.random.seed(1000)\n\n def _calculateAveragePrecision(self, dorsalList: list, dist: list, query: int) -> float:\n if not dorsalList or query not in dorsalList:\n return 0.\n\n gallery_match = np.array([1 if i == query else 0 for i in dorsalList])\n dist = np.array(dist)\n similarity = 1 - dist / np.amax(dist)\n return average_precision_score(gallery_match, similarity, average='macro', pos_label=1)\n\n def _apply_regression(self, time, classification, runners_times, index):\n regr = RandomForestRegressor(max_depth=10, n_estimators=250)\n y = []\n X = []\n for t, c in zip(runners_times, classification):\n y.append(pd.to_timedelta(self._df[t][index]))\n d = self._df[c][index]\n X.append(d)\n y = abs(time - np.array(y))\n y = [y_.total_seconds() for y_ in y]\n X = np.array(X).reshape(-1, 1)\n with parallel_backend('threading', n_jobs = self._jobs):\n regr.fit(X, y)\n seconds = regr.predict(np.array([index+1]).reshape(-1, 1))[0]\n return timedelta(seconds=seconds + self._step_time)\n\n def _filter_faces_by_regression(self, query, gallery, classification, runners_times, index):\n time = getTime(query)\n delta = self._apply_regression(time, classification, runners_times, index)\n return [sample for sample in gallery if time - delta <= sample[2] <= time + delta]\n\n def identificationRunnersByFaces(self, probe: str, model: str, metric: str,\n galleryPlace: str, topNum: int = 107,\n pca: bool = False, temporalCoherence: bool = False,\n filling: bool = False, regression: bool = False, verbose: bool = False) -> tuple:\n\n self._face_recognition.checkMetricAndModel(model, metric)\n probe_places = os.path.basename(probe)\n\n matches = np.zeros(topNum)\n average_precision = []\n index_probe = PLACES.index(os.path.basename(probe))\n index_gallery = PLACES.index(os.path.basename(galleryPlace))\n isOrder = index_probe < index_gallery\n\n model_file = \"representations_%s.pkl\" % (model if not pca else \"%s_pca\" % model).lower().replace(\"-\", \"_\")\n probe = os.path.join(probe, model_file)\n gallery = os.path.join(galleryPlace, model_file)\n\n probes = self._loadServices.loadInformation(probe)\n gallery = [(getNumber(os.path.basename(file)), embedding, getTime(os.path.basename(file)))\n for file, embedding in self._loadServices.loadInformation(gallery)]\n probes.sort(key = lambda x: getTime(x[0]))\n\n last_query = getNumber(os.path.basename(probes[0][0]))\n queries_done = []\n average_dist_success = []\n average_dist_fail = []\n average_dist_position_fail = []\n\n file2Save = os.path.join(\"Results\", \"dist\", \"faces\")\n\n for i, query in enumerate(probes):\n dorsal = getNumber(os.path.basename(query[0]))\n gallery_query = gallery\n\n if regression:\n if last_query != dorsal:\n if dorsal in queries_done:\n queries_done.remove(dorsal)\n queries_done.append(last_query)\n last_query = dorsal\n index_probe_ds = self._cls_positions.index(probe_places)\n cls = self._cls_positions[:index_probe_ds]\n runners_times = self._times[:index_probe_ds]\n index = list(self._df[probe_places]).index(i + 1)\n gallery_query = [\n sample\n for sample in self._filter_faces_by_regression(query[0], gallery, cls, runners_times, index)\n if sample[0] not in queries_done\n ]\n\n classification, dist = self._face_recognition.computeClassification(query, gallery_query, model_file,\n metric = metric,\n temporalCoherence=temporalCoherence,\n index=(index_probe, index_gallery),\n isOrder=isOrder,\n filledGallery=filling)\n try:\n matches[classification.index(dorsal)] += 1\n except Exception:\n pass\n\n if verbose:\n if dorsal != classification[0] and dorsal in classification:\n print(os.path.basename(query[0]))\n print(\"index:\", classification.index(dorsal) + 1)\n print(\"positions:\", classification[0:classification.index(dorsal)+1])\n print(\"distances:\", dist[0:classification.index(dorsal)+1])\n self._plot_dist(dist, \"%s distance fail\" % metric, os.path.join(file2Save, os.path.basename(query[0])))\n average_dist_position_fail.append(dist[classification.index(dorsal)])\n average_dist_fail.append(dist[0])\n elif dorsal != classification[0]:\n average_dist_success.append(dist[0])\n\n average_precision.append(\n self._calculateAveragePrecision(classification, dist, dorsal)\n )\n\n cmc = np.cumsum(matches) / len(probes)\n\n if verbose:\n print(\"Average distance success: \", np.mean(average_dist_success))\n print(\"Average distance fail: \", np.mean(average_dist_fail))\n print(\"Average distance fail position dorsal: \", np.mean(average_dist_position_fail))\n\n return cmc, np.mean(average_precision)\n\n def _filter_bodies_by_regression(self, query, gallery, classification, runners_times, index):\n delta = self._apply_regression(query.date, classification, runners_times, index)\n return [sample for sample in gallery.bodies if query.date - delta <= sample.date <= query.date + delta]\n\n def _plot_dist(self, dist, title, fileSave):\n plt.plot(dist)\n plt.title(title)\n plt.xlabel(\"Classification\")\n plt.ylabel(\"Distances\")\n plt.savefig(fileSave)\n plt.clf()\n\n\n def identificationRunnersByBody(self, probe: str, metric: str, galleryPlace: str,\n topNum: int = 107, temporalCoherence: bool = False,\n filling: bool = False, regression: bool = False,\n model: str = \"\", verbose: bool = False) -> tuple:\n matches = np.zeros(topNum)\n average_precision = []\n probe_places = os.path.basename(probe).replace(\".pkl\", '').split('_')[0]\n index_probe = PLACES.index(probe_places)\n index_gallery = PLACES.index(os.path.basename(galleryPlace).replace(\".pkl\", '').split('_')[0])\n isOrder = index_probe < index_gallery\n\n probe = self._loadServices.loadInformation(probe)\n gallery = self._loadServices.loadInformation(galleryPlace)\n\n queries = probe.bodies\n queries.sort(key = lambda query: query.date)\n\n last_query = 1\n queries_done = []\n average_dist_success = []\n average_dist_fail = []\n average_dist_position_fail = []\n\n file2Save = os.path.join(\"Results\", \"dist\", \"body\")\n\n for i, query in enumerate(queries):\n if query.dorsal not in [body.dorsal for body in gallery.bodies]:\n continue\n\n gallery_query = gallery\n if regression:\n if last_query != query.dorsal:\n if query.dorsal in queries_done:\n queries_done.remove(query.dorsal)\n queries_done.append(last_query)\n last_query = query.dorsal\n index_probe_ds = self._cls_positions.index(probe_places)\n cls = self._cls_positions[:index_probe_ds]\n runners_times = self._times[:index_probe_ds]\n index = list(self._df[probe_places]).index(i + 1)\n gallery_query = BodyCollection(\n collection=[\n sample\n for sample in self._filter_bodies_by_regression(query, gallery, cls, runners_times, index)\n if sample.dorsal not in queries_done\n ]\n )\n\n classification, dist = self._body_recognition.computeClassification(query,\n gallery_query,\n metric,\n temporalCoherence=temporalCoherence,\n index=(index_probe, index_gallery),\n isOrder=isOrder,\n filledGallery=filling,\n model=model)\n\n try:\n matches[classification.index(query.dorsal)] += 1\n except Exception:\n pass\n\n if verbose:\n if query.dorsal != classification[0] and query.dorsal in classification:\n print(query.file)\n print(\"index:\", classification.index(query.dorsal) + 1)\n print(\"positions:\", classification[0:classification.index(query.dorsal)+1])\n print(\"distances:\", dist[0:classification.index(query.dorsal)+1])\n self._plot_dist(dist, \"%s distance fail\" % metric, os.path.join(file2Save, query.file))\n average_dist_position_fail.append(dist[classification.index(query.dorsal)])\n average_dist_fail.append(dist[0])\n elif query.dorsal != classification[0]:\n average_dist_success.append(dist[0])\n\n\n average_precision.append(\n self._calculateAveragePrecision(classification, dist, query.dorsal)\n )\n\n cmc = np.cumsum(matches) / len(probe.bodies)\n if verbose:\n print(\"Average distance success: \", np.mean(average_dist_success))\n print(\"Average distance fail: \", np.mean(average_dist_fail))\n print(\"Average distance fail position dorsal: \", np.mean(average_dist_position_fail))\n return cmc, np.mean(average_precision)\n\n\n\n\n","sub_path":"Controller/RecognitionsController.py","file_name":"RecognitionsController.py","file_ext":"py","file_size_in_byte":11977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"539276245","text":"#-*- coding: UTF-8 -*-\r\nimport select\r\nimport socket\r\nimport os, sys\r\n#import Queue\r\nimport struct\r\nimport json\r\nimport hashlib\r\nimport platform\r\n\r\nsettings = {\r\n 'hostip': '0.0.0.0',\r\n 'port':10001,\r\n 'to_dir':'./to_dir' #linux path\r\n #'to_dir':'D:\\\\mytest' #windows path\r\n }\r\n\r\nmessage_queues = {}\r\nfile_head_info_list = {}\r\n\r\ndef get_os_type():\r\n sysstr = platform.system()\r\n if(sysstr ==\"Windows\"):\r\n return 'Windows'\r\n elif(sysstr == \"Linux\"):\r\n return 'Linux'\r\n else:\r\n return 'Other'\r\n \r\ndef get_head_info(recv_socket):\r\n head_len_container = recv_socket.recv(4) \r\n \r\ndef judge_is_new_connect(recv_socket): \r\n #print('judge_is_new_connect', recv_socket, file_head_info_list)\r\n if recv_socket in file_head_info_list:\r\n return False\r\n return True\r\n\r\ndef get_filename(filename):\r\n filename_dict = {'filename':filename}\r\n file_head = json.dumps(filename_dict) # 将字典转换成字符串\r\n return file_head.encode('utf-8') \r\n \r\ndef get_filename_len(filename):\r\n filename_dict = {'filename':filename}\r\n filename_len = len(json.dumps(filename_dict).encode('utf-8')) # 将字典转换成字符串\r\n return filename_len\r\n\r\ndef create_dir(path):\r\n # 去除首位空格\r\n path=path.strip()\r\n path=path.rstrip(\"/\")\r\n if not os.path.exists(path):\r\n os.makedirs(path) \r\n return True\r\n else:\r\n # 如果目录存在则不创建,并提示目录已存在\r\n return False\r\n\r\ndef start_recv_file_server(settings):\r\n #创建套接字并设置该套接字为非阻塞模式\r\n server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\r\n server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n server.setblocking(0)\r\n \r\n #绑定套接字\r\n server_address = ( settings['hostip'], settings['port'] )\r\n print (sys.stderr,'starting up on %s port %s'% server_address)\r\n server.bind(server_address)\r\n \r\n #将该socket变成服务模式\r\n #backlog等于5,表示内核已经接到了连接请求,但服务器还没有调用accept进行处理的连接个数最大为5\r\n #这个值不能无限大,因为要在内核中维护连接队列\r\n server.listen(5)\r\n \r\n #初始化读取数据的监听列表,最开始时希望从server这个套接字上读取数据\r\n inputs = [server]\r\n \r\n #初始化写入数据的监听列表,最开始并没有客户端连接进来,所以列表为空\r\n outputs = []\r\n \r\n \r\n while inputs:\r\n #print ( sys.stderr,'waiting for the next event....' )\r\n #调用select监听所有监听列表中的套接字,并将准备好的套接字加入到对应的列表中\r\n readable,writable,exceptional = select.select(inputs,outputs,inputs)\r\n '''\r\n 如果server这个套接字可读,则说明有新链接到来\r\n 此时在server套接字上调用accept,生成一个与客户端通讯的套接字\r\n 并将与客户端通讯的套接字加入inputs列表,下一次可以通过select检查连接是否可读\r\n 然后在发往客户端数据。 select系统调用是用来让我们的程序监视多个文件句柄(file descrīptor)的状态变化的。程序会停在select这里等待,\r\n 直到被监视的文件句柄有某一个或多个发生了状态改变\r\n\r\n 若可读的套接字不是server套接字,有两种情况:一种是有数据到来,另一种是链接断开\r\n 如果有数据到来,先接收数据,然后将收到的数据填入往客户端的缓存区中的对应位置,最后\r\n 将于客户端通讯的套接字加入到写数据的监听列表:\r\n 如果套接字可读.但没有接收到数据,则说明客户端已经断开。这时需要关闭与客户端连接的套接字\r\n 进行资源清理\r\n '''\r\n for s in readable: \r\n if s is server:\r\n connection,client_address = s.accept()\r\n connection.setblocking(0)#设置非阻塞\r\n inputs.append(connection)\r\n #message_queues[connection] = Queue.Queue()\r\n print ('--->start connection from: [%s]' % str(client_address) )\r\n else:\r\n if judge_is_new_connect(s):\r\n head_len_container = s.recv(4) #接收struct.pack的头长度。\r\n if head_len_container:\r\n head_info_len = struct.unpack('i', head_len_container)[0] # 解析出报头的字符串大小\r\n while True:\r\n head_info = ''\r\n try:\r\n recv_str = s.recv(head_info_len) # 接收长度为head_len的报头内容的信息\r\n print ('recv file info is:%s' % recv_str)\r\n except:\r\n #print ('recv file head is err.')\r\n continue\r\n \r\n head_info = head_info + recv_str\r\n if head_info_len <= len(head_info):\r\n break;\r\n head_info = json.loads(head_info.decode('utf-8'))\r\n \r\n file_head_info_list[s]= head_info\r\n #print ('start recv newfile, head_info is:', head_info)\r\n \r\n if s not in outputs:\r\n outputs.append(s)\r\n \r\n if not os.path.exists(settings['to_dir']):\r\n create_dir(settings['to_dir'])\r\n \r\n if get_os_type() == 'Linux':\r\n adbfilename = head_info['filename'].replace('\\\\','/')\r\n fn = adbfilename.split('/')[-1]\r\n else:\r\n adbfilename = head_info['filename'].replace('/','\\\\')\r\n fn = adbfilename.split('\\\\')[-1]\r\n pathname = adbfilename.split(fn)[0] \r\n if pathname:\r\n create_dir(settings['to_dir']+pathname)\r\n #f = open('recv_file.mkv', 'wb')\r\n f = open(settings['to_dir']+'/'+pathname+'/'+fn, 'wb')\r\n f_myhash = hashlib.md5()\r\n f_len = 0\r\n f_count = 0\r\n else:\r\n print (sys.stderr,'closing..',client_address)\r\n if s in outputs:\r\n outputs.remove(s)\r\n inputs.remove(s)\r\n s.close()\r\n f.close()\r\n else:\r\n #print ('this is not new connnect...')\r\n data = s.recv(1448)\r\n if data:\r\n #print ('filename is ', json.loads(filename.decode('utf-8'))['filename'] )\r\n #接收文件\r\n f.write(data)\r\n f_myhash.update(data)\r\n \r\n f_len = f_len + len(data)\r\n #print (f_len, head_info['filesize_bytes'], f_len, len(data))\r\n if f_len >= head_info['filesize_bytes']: #接收完成\r\n recv_md5sum = f_myhash.hexdigest()\r\n #print ('recv md5sum is [%s]' % recv_md5sum)\r\n #print ('orig md5sum is [%s]' % head_info['md5sum'])\r\n if recv_md5sum == head_info['md5sum']: \r\n s.send(struct.pack('i',0)) #当文件传输的md5sum校验对的时候,代表文件传输正确\r\n print ('[%s] Receive complete, md5sum is ok.' % (head_info['filename']) )\r\n else:\r\n s.send(struct.pack('i',1))\r\n #print ('is not ok..')\r\n else:\r\n f_count = f_count+1448\r\n if f_count % 1448 == 5:\r\n s.send(struct.pack('i',1))\r\n #print ('555555555555')\r\n else:\r\n print (\"++>closed.[%s]\\n\" % str(client_address))\r\n if s in outputs:\r\n outputs.remove(s)\r\n inputs.remove(s)\r\n s.close()\r\n f.close()\r\n\r\n #处理可写的套接字\r\n '''\r\n 在发送缓冲区中取出响应的数据,发往客户端。\r\n 如果没有数据需要写,则将套接字从发送队列中移除,select中不再监视\r\n '''\r\n for s in writable: \r\n print ('send filename to client.')\r\n if s in file_head_info_list:\r\n file_head_info_msg = file_head_info_list[s]\r\n file_head = get_filename(file_head_info_msg['filename'])\r\n print ('Respond to client requests: filename[%s].' % file_head_info_msg['filename'])\r\n s.send(file_head)\r\n outputs.remove(s)\r\n\r\n #处理异常情况\r\n for s in exceptional:\r\n for s in exceptional: \r\n print (sys.stderr,'exception condition on' )\r\n inputs.remove(s)\r\n if s in outputs:\r\n outputs.remove(s)\r\n s.close()\r\n #del message_queues[s]\r\n \r\n \r\n \r\nstart_recv_file_server(settings)\r\n\r\n ","sub_path":"dir_backup/filebackup/servers3.py","file_name":"servers3.py","file_ext":"py","file_size_in_byte":9926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"651698014","text":"import json\nimport argparse\nfrom lib.target_creator import TargetCreator\nfrom lib.ptdb_request import PTDBRequest\n\ndef upload_targets(user_input): \n for target in TargetCreator(user_input).targets:\n PTDBRequest(target, user_input).post_target()\n \nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"\"\"This program was written to upload 45 \n variations of the CD19 McAbody molecule. In order for the program to run users must provide\n a file path to an Excel workbook, a file path to a directory of FASTA files, and a token\n to communicate with the PTDB API.\"\"\")\n parser.add_argument('--excel_file_location', help='Use the --excel_file_location flag to specify the location of the excel document that contains the subunit naming data.')\n parser.add_argument('--fasta_location', help='Use the --fasta_location flag to specify the loaction of a directory of FASTA files.')\n parser.add_argument('--API_URL', help='Use the --API_URL flag to set the destination of POST request.')\n parser.add_argument('--token', help='Use the --token flag to set the API key needed to upload data to the PTDB API.')\n args = parser.parse_args()\n args = vars(args)\n upload_targets(args)\n","sub_path":"target_uploader.py","file_name":"target_uploader.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"654062619","text":"\"\"\"\n\tThis module contains the specific logic needed to add an if block to the control flow graph.\n\tIt uses the special headers defined in the PBG module to perform the linking from the first if in the CFG i.e. the\n\telif header will link the original if to the elif. Same with the else.\n\tIt inherits from other common classes if other constructs are defined within the if block.\n\tNote: though it is possible for a test to be impossible to get to, this will still link it in.\n\"\"\"\n\nfrom CFConstants import *\nfrom CFCommonClasses import *\n\nclass addIf(visitCommon, errorCommon, loopCommon, funcCommon, callCommon):\n\tdef main(self, v1, adders):\n\t\tself.makeAdders(adders)\n\t\tself.v1 = v1\n\t\ti = v1+1\n\t\tself.origins = [v1]\n\t\tself.isCont = self.isBreak = self.isErr = newStart = False\n\t\twhile not \"IfEnd\" == objType(v[i-1][0]) or newStart:\n\t\t\tCF = newStart = False\n\t\t\tfor oIX in range(len(v[i])):\n\t\t\t\tnewStart = self.visit(v[i][oIX], i)\n\t\t\t\tif CFs.get(objType(v[i][oIX])): CF = True\n\t\t\tif canLink(CF, i): addLink(i-1, i)\n\t\t\telif ends.get(objType(v[i][0])) and ends.get(objType(v[i-1][0])):\n\t\t\t\taddLink(i-1, i)\n\t\t\ti = newStart if newStart else i+1\n\t\treturn i\n\t\t\n\tdef visit_ElifHeader(self, obj, i):\n\t\taddLink(self.v1, i)\n\t\tif not breaks.get(objType(v[i-1][len(v[i-1])-1])):\n\t\t\tif not (\"Call\" == objType(v[i-1][len(v[i-1])-1]) and\n\t\t\t\t\t (seenFuncs.get(v[i-1][len(v[i-1])-1].func.id) or\n\t\t\t\t\t funcAliases.get(v[i-1][len(v[i-1])-1].func.id))):\n\t\t\t\tself.origins.append(i-1) #prev block can go to end if true\n\t\t\n\tdef visit_IfElse(self, obj, i):\n\t\taddLink(self.v1, i)\n\t\tif not breaks.get(objType(v[i-1][len(v[i-1])-1])):\n\t\t\tif not (\"Call\" == objType(v[i-1][len(v[i-1])-1]) and\n\t\t\t\t\t (seenFuncs.get(v[i-1][len(v[i-1])-1].func.id) or\n\t\t\t\t\t funcAliases.get(v[i-1][len(v[i-1])-1].func.id))):\n\t\t\t\tself.origins.append(i-1)\n\t\tself.origins.remove(self.v1) #double links initial if otherwise\n\t\t\n\tdef visit_IfEnd(self, obj, i):\n\t\tif not breaks.get(objType(v[i-1][len(v[i-1])-1])):\n\t\t\tif not (\"Call\" == objType(v[i-1][len(v[i-1])-1]) and\n\t\t\t\t\t (seenFuncs.get(v[i-1][len(v[i-1])-1].func.id) or\n\t\t\t\t\t funcAliases.get(v[i-1][len(v[i-1])-1].func.id))):\n\t\t\t\tself.origins.append(i-1) #adds block previous to possible end-branch\n\t\tfor block in self.origins: addLink(block, i)\n\t\t\n","sub_path":"GraphBuilder/addIf.py","file_name":"addIf.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"301657136","text":"import tkinter as tk\nfrom tkinter import messagebox\nfrom tkinter import ttk\nfrom tkinter.filedialog import askopenfilename\nfrom PIL import Image, ImageTk\nfrom datetime import datetime, date\nfrom mfrc522 import SimpleMFRC522\nimport RPi.GPIO as GPIO\nfrom pyfingerprint.pyfingerprint import PyFingerprint\nimport pymysql\n\nclass Registration_User(tk.Toplevel):\n def __init__(self, parent):\n super().__init__(parent)\n self.title(\"Thesis\")\n self.attributes(\"-fullscreen\", True)\n \n self.main_frame = tk.Frame(self)\n self.main_frame.pack(fill = \"both\", expand = 1)\n \n self.ws = self.winfo_screenwidth()\n self.hs = self.winfo_screenheight()\n print(self.ws, self.hs) \n self.db = pymysql.connect(host = \"192.168.1.11\",port = 3306, user = \"root\",passwd = \"justin\",db= \"thesis_db\")\n self.cursor = self.db.cursor()\n GPIO.setwarnings(False)\n self.reader = SimpleMFRC522()\n \n self.attributes('-fullscreen', True)\n #self.wm_attributes('-type', 'splash')\n \n \n self.img_register_info = (Image.open(\"background_kiosk.png\"))\n self.image_register_info = self.img_register_info.resize((self.ws,self.hs))\n self.img_background_register_info = ImageTk.PhotoImage(self.image_register_info)\n self.imglabel_register_info = tk.Label(self.main_frame, image = self.img_background_register_info).place(x=0,y=0)\n \n \n first_name = tk.StringVar()\n middle_name = tk.StringVar()\n last_name = tk.StringVar()\n sex = tk.StringVar()\n birth_day = tk.StringVar()\n civil_status = tk.StringVar()\n year_of_residency = tk.StringVar()\n place_of_birth = tk.StringVar()\n security_question = tk.StringVar()\n answer = tk.StringVar()\n \n self.label_head = tk.Label(self.main_frame, text = \"Fill up all informations below\",bg = \"white\", font = (\"Times New Roman\", 25))\n self.label_head.grid(row = 0, column = 1, columnspan = 2)\n \n self.space_label= tk.Label (self.main_frame, text = \"\\t\\t\", bg = \"white\")\n self.space_label.grid(row = 1, column = 0)\n\n self.label_first_name = tk.Label(self.main_frame, text = \"First Name\\t:\", relief = \"ridge\",bg = \"white\")\n self.label_first_name.grid(row = 1, column = 1, padx = 5, pady = 15)\n self.entry_first_name = tk.Entry(self.main_frame, textvariable = first_name,bg = \"white\", width = \"45\")\n self.entry_first_name.grid(row = 1, column = 2, pady = 15)\n #self.entry_first_name.bind('', self.first_name_keyboard_resident)\n \n\n self.label_middle_name = tk.Label(self.main_frame, text = \"Middle Name\\t:\",bg = \"white\", relief = \"ridge\")\n self.label_middle_name.grid(row = 2, column = 1)\n self.entry_middle_name = tk.Entry(self.main_frame, textvariable = middle_name,bg = \"white\", width = \"45\")\n self.entry_middle_name.grid(row = 2, column = 2, pady = 15)\n #self.entry_middle_name.bind('', self.middle_name_keyboard_resident)\n \n self.label_last_name = tk.Label(self.main_frame, text = \"Last Name\\t:\",bg = \"white\", relief = \"ridge\")\n self.label_last_name.grid(row = 3, column = 1)\n self.entry_last_name = tk.Entry(self.main_frame, textvariable = last_name,bg = \"white\", width = \"45\")\n self.entry_last_name.grid(row = 3, column = 2, pady = 15)\n #self.entry_last_name.bind('', self.last_name_keyboard_resident)\n \n self.label_sex = tk.Label(self.main_frame, text = \"Sex\\t\\t:\",bg = \"white\", relief = \"ridge\")\n self.label_sex.grid(row = 4, column = 1)\n \n self.option_list_sex = [\"Male\", \"Female\"]\n self.option = ttk.Combobox(self.main_frame, state = \"readonly\", textvariable = sex, width = \"43\", values = self.option_list_sex)\n self.option.grid(row = 4, column = 2, pady = 15)\n \n self.label_birth_day = tk.Label(self.main_frame, text = \"Birth Day\\t\\t:\",bg = \"white\", relief = \"ridge\")\n self.label_birth_day.grid(row = 5, column = 1)\n self.entry_birth_day = tk.Entry(self.main_frame, textvariable = birth_day,bg = \"white\", width = \"45\")\n self.entry_birth_day.grid(row = 5, column = 2, pady = 15)\n \n #self.entry_birth_day.bind('',self.birth_day_keyboard_resident)\n \n self.label_civil_status = tk.Label(self.main_frame, text = \"Civil Status\\t:\",bg = \"white\", relief = \"ridge\")\n self.label_civil_status.grid(row = 6, column = 1)\n \n self.option_list_cs = [\"Single\", \"Married\", \"Widdow\", \"Separated\", \"Live-in\", \"Unkown\"]\n self.option_cs = ttk.Combobox(self.main_frame, state=\"readonly\", textvariable = civil_status, width = \"43\", values = self.option_list_cs)\n self.option_cs.grid(row = 6, column = 2, pady = 15)\n \n self.label_year_of_residency = tk.Label(self.main_frame, text = \"Date of Residency\\t:\",bg = \"white\", relief = \"ridge\")\n self.label_year_of_residency.grid(row = 7, column = 1, pady = 15)\n self.entry_year_of_residency = tk.Entry(self.main_frame, textvariable = year_of_residency,bg = \"white\", width = \"45\")\n self.entry_year_of_residency.grid(row = 7, column = 2)\n \n self.label_place_of_birth = tk.Label(self.main_frame, text = \"Place of Birth\\t:\",bg = \"white\", relief = \"ridge\")\n self.label_place_of_birth.grid(row = 8, column = 1)\n self.entry_place_of_birth = tk.Entry(self.main_frame, textvariable = place_of_birth,bg = \"white\", width = \"45\")\n self.entry_place_of_birth.grid(row = 8, column = 2, pady = 15)\n #self.entry_place_of_birth.bind('',self.place_of_birth_keyboard_resident)\n \n self.label_question = tk.Label(self.main_frame, text = \"Security Question\\t:\",bg = \"white\", relief = \"ridge\")\n self.label_question.grid(row= 9, column = 1)\n self.question_list = [\"What was your childhood nickname?\",\n \"In what city did you meet your spouse/significant other?\",\n \"What is the name of your favorite childhood friend?\",\n \"What street did you live on in third grade?\",\n \"What is the middle name of your youngest child?\",\n \"What is your oldest sibling's middle name?\",\n \"What school did you attend for sixth grade?\",\n \"What is your oldest cousin's first and last name?\",\n \"What was the name of your first stuffed animal?\",\n \"In what city or town did your mother and father meet?\",\n \"Where were you when you had your first kiss?\",\n \"What is the first name of the boy or girl that you first kissed?\",\n \"What was the last name of your third grade teacher?\",\n \"In what city does your nearest sibling live?\",\n \"What is your maternal grandmother's maiden name?\",\n \"In what city or town was your first job?\",\n \"What is the name of the place your wedding reception was held?\",\n \"What is the name of a college you applied to but didn't attend?\",\n \"What was the name of your elementary / primary school?\",\n \"What is the name of the company of your first job?\",\n \"What was your favorite place to visit as a child?\",\n \"What is your spouse's mother's maiden name?\",\n \"What is the country of your ultimate dream vacation?\",\n \"What is the name of your favorite childhood teacher?\",\n \"To what city did you go on your honeymoon?\",\n \"What was your dream job as a child?\",\n \"Who was your childhood hero?\"]\n \n self.question_list= ttk.Combobox(self.main_frame, state = \"readonly\", width = \"43\", textvariable = security_question, values = self.question_list)\n self.question_list.grid(row = 9, column = 2, pady = 15)\n \n self.answer_label = tk.Label(self.main_frame, text = \"Answer\\t\\t:\", bg =\"white\", relief = \"ridge\")\n self.answer_label.grid(row = 10, column = 1)\n self.answer_entry = tk.Entry(self.main_frame, textvariable = answer, width = \"45\")\n self.answer_entry.grid(row = 10, column = 2, pady = 15)\n #self.answer_entry.bind('',self.answer_keyboard_resident)\n \n\n self.button_submit = tk.Button(self.main_frame, text = \"Proceed to Step 2\",bg = \"white\", command = lambda: self.registered(first_name.get(),\n middle_name.get(),\n last_name.get(), sex.get(),\n birth_day.get(),\n civil_status.get(),\n year_of_residency.get(),\n place_of_birth.get(),\n security_question.get(), answer.get()))\n self.button_submit.grid(row = 11, column = 2, pady = 5)\n \n tk.Label(self.main_frame, text = \"\\t \\t \\t \",bg = \"white\").grid(row = 3, column = 3)\n\n # self.label_place_of_birth = tk.Label(self.main_frame, text = \"Upload Excel File\",bg = \"white\", font = (\"Times New Roman\" , 15))\n # self.label_place_of_birth.place(x= 780, y = 80)\n # self.excel_upload = Button(self.main_frame, text = \"Upload Excel File\",bg = \"white\", command = self.Upload_Button)\n \n # self.excel_upload.grid(row = 2, column = 4)\n # self.excel_submit = Button(self.main_frame, text = \"Submit Excel File\",bg = \"white\", command = self.Submit_Button)\n # self.excel_submit.grid(self.main_frame = 3, column = 4, pady = 5)\n self.back_button = tk.Button(self.main_frame, text = \"Back\",bg = \"white\", command = self.destroy)\n self.back_button.grid(row = 12, column = 2)\n\n def registered(self,get_first_name,\n get_middle_name,\n get_last_name,\n get_sex,\n get_birth_day,\n get_civil_status,\n get_year_of_residency,\n get_place_of_birth,\n get_security_question,\n get_answer):\n self.get_first_name = get_first_name\n self.get_middle_name = get_middle_name\n self.get_last_name = get_last_name\n self.get_sex = get_sex\n self.get_birth_day = get_birth_day \n self.get_civil_status = get_civil_status\n self.get_year_of_residency = get_year_of_residency \n self.get_place_of_birth = get_place_of_birth\n self.get_security_question = get_security_question\n self.get_answer = get_answer\n \n print(self.get_first_name)\n print(self.get_middle_name)\n print(self.get_last_name)\n print(self.get_sex)\n print(self.get_birth_day)\n print(self.get_civil_status)\n print(self.get_year_of_residency)\n print(self.get_place_of_birth)\n print(self.get_security_question)\n print(self.get_answer)\n try: \n _year = int(self.get_birth_day[0:4])\n _month = int(self.get_birth_day[4:6])\n _day = int(self.get_birth_day[6:8])\n \n self.get_birth_day = datetime.datetime(_year, _month, _day)\n except Exception as e:\n self.get_birth_day = \"\"\n \n if (self.get_first_name == \"\" or self.get_middle_name == \"\" or\n self.get_last_name == \"\" or self.get_sex == \"\" or self.get_birth_day == \"\" or\n self.get_civil_status == \"\" or self.get_place_of_birth == \"\" or\n self.get_security_question ==\"\" or self.get_answer == \"\" or\n self.get_year_of_residency ==\"\"):\n messagebox.showerror(\"Error!\",\"Please complete the required field\", parent = self)\n else:\n self.step2_register()\n \n def step2_register(self):\n self.main_frame.pack_forget()\n self.rfid_frame = tk.Frame(self)\n self.rfid_frame.pack(fill = BOTH, expand = 1)\n \n self.img_register = (Image.open(\"RFID_register.png\"))\n self.img_background_register = ImageTk.PhotoImage(self.img_register)\n tk.Label_register = tk.Label(self.rfid_frame, image = self.img_background_register)\n tk.Label_register.grid(row = 0, column = 0)\n tk.Label_register.bind('', self.RFID_registered)\n \n\n def RFID_registered(self, event):\n self.update()\n try:\n self.id, self.text = self.reader.read()\n self.cursor.execute(\"SELECT * FROM residents_db WHERE RFID = %s\", str(self.id))\n if (self.cursor.fetchone() is not None):\n messagebox.showerror(\"Notice!\", \"RFID card is already registered\", parent = self)\n else:\n self.cursor.execute(\"SELECT * FROM residents_admin WHERE RFID = %s\", str(self.id))\n if (self.cursor.fetchone() is not None):\n messagebox.showerror(\"Notice!\", \"RFID card is already registered\", parent = self) \n else:\n messagebox.showinfo(\"Success\", \"Proceeding to step 3\", parent = self)\n self.register_fingerprint()\n \n except:\n GPIO.cleanup()\n \n def register_fingerprint(self):\n self.rfid_frame.pack_forget() \n self.img_register_finger = (Image.open(\"finger_register.png\"))\n self.img_background_register_finger = ImageTk.PhotoImage(self.img_register_finger)\n \n self.finger_frame = tk.Frame(self)\n self.finger_frame.pack(fill = BOTH, expand = True)\n \n tk.Label_register = tk.Label(self.finger_frame, image = self.img_background_register_finger)\n tk.Label_register.grid(row = 0, column = 0)\n \n tk.Label_register.bind('', self.registered_fingerprint)\n \n def registered_fingerprint(self,event):\n self.update()\n try:\n f = PyFingerprint('/dev/ttyUSB0', 57600, 0xFFFFFFFF, 0x00000000)\n\n if ( f.verifyPassword() == False ):\n raise ValueError('The given fingerprint sensor password is wrong!')\n \n except Exception as e:\n print('The fingerprint sensor could not be initialized!')\n print('Exception message: ' + str(e))\n\n ## Gets some sensor information\n print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))\n\n ## Tries to enroll new finger\n tk.Label(self, text = \"Waiting for finger...\", width = 20).place(x = 450, y = 680)\n self.update()\n\n ## Wait that finger is read\n while ( f.readImage() == False ):\n pass\n\n ## Converts read image to characteristics and stores it in charbuffer 1\n f.convertImage(0x01)\n\n ## Checks if finger is already enrolled\n result = f.searchTemplate()\n positionNumber = result[0] \n\n if ( positionNumber >= 0 ):\n messagebox.showinfo(\"Notice\", \"Fingerprint is already registered\\n please try again\", parent = self)\n \n tk.Label(self, text = \"Remove finger...\", width = 20).place(x = 450, y = 680)\n self.update()\n\n time.sleep(2)\n\n tk.Label(self, text = \"Waiting for the same finger again...\", width = 28).place(x = 410, y = 680)\n self.update()\n\n\n ## Wait that finger is read again\n while ( f.readImage() == False ):\n pass\n\n ## Converts read image to characteristics and stores it in charbuffer 2\n f.convertImage(0x02)\n\n ## Compares the charbuffers\n if ( f.compareCharacteristics() == 0 ):\n tk.Label(self.finger_frame, text = \"Finger do not match\",width = 30).place(x = 430, y = 680)\n tk.Label(self.finger_frame, text = \"Scan your finger again\").place(x = 436, y = 700)\n self.update()\n \n ## Creates a template\n else:\n f.createTemplate()\n characterics = str(f.downloadCharacteristics(0x01)).encode('utf-8')\n ## Saves template at new position number\n positionNumber = f.storeTemplate()\n self.cursor.execute(\"INSERT INTO residents_db (FIRST_NAME, MIDDLE_NAME, LAST_NAME, SEX, BIRTH_DATE, CIVIL_STATUS, YEAR_OF_RESIDENCY, PLACE_OF_BIRTH, SECURITY_QUESTION, ANSWER, RFID, FINGER_TEMPLATE) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\",(self.get_first_name,\n self.get_middle_name,\n self.get_last_name,\n self.get_sex,\n self.get_birth_day,\n self.get_civil_status,\n self.get_year_of_residency,\n self.get_place_of_birth,\n self.get_security_question,\n self.get_answer,\n str(self.id),positionNumber))\n self.db.commit()\n messagebox.showinfo(\"Success\", \"Fingerprint successfully registered\", parent = self)\n self.destroy()\n\n \n \n\nif __name__ == \"__main__\":\n Registration_User().mainloop()\n\n\n","sub_path":"register_user.py","file_name":"register_user.py","file_ext":"py","file_size_in_byte":20820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"350356310","text":"import sys\n\n\ndef sumdigit(n):\n s = 0\n while (n > 0):\n s += n % 10\n n = n // 10\n return s\n\n\ndef superDigit(n, k):\n # Complete this function\n if (n < 10) & (k == 1):\n return n\n else:\n s = sumdigit(n)\n return superDigit(k*s, 1)\n\n\nif __name__ == \"__main__\":\n n, k = [148, 3]\n print(n, k)\n result = superDigit(n, k)\n print(result)","sub_path":"HackerRank/Recursion/RecursiveDigitSum.py","file_name":"RecursiveDigitSum.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"333991594","text":"import math\n\n# The worst case storage requirement of toexplore in the bfs() function in the\n# lecture notes is Omega(V), or more precisely V-1 elements in the queue, in\n# the situation where all vertices (except the start vertex) are neighbours of\n# the start vertex.\n\n# We can reduce the storage requirement to continue to use O(1) storage within\n# each vertex object but O(1) extra memory but it comes at a cost of speed.\n# In addition to the seen flag, we can also store a queue_position flag and an\n# popped flag in each vertex, so the storage within each vertex object is still\n# constant, and we will no longer have to use extra memory for the queue, but\n# we can cycle through each vertex and visit the one with the lowest\n# queue_position that hasn't already been popped until we are done. We will\n# need to store the current first element in the queue, and a boolean storing\n# whether we are done, which is O(1) extra storage as it is just these two\n# flags regardless of how many vertices there are. Essentially what we are\n# doing is replacing the explicit queue with flags within each vertex storing\n# whether they have been popped and what their position in the queue is.\n\n\ndef bfs(g, s):\n for v in g.vertices:\n v.seen = False\n v.queue_position = math.inf\n v.popped = False\n s.seen = True\n s.queue_position = 0\n\n finished = False\n last_queue_position = 0\n\n while not finished:\n # First find the first element in the queue, i.e. smallest queue\n # position which hasn't already been popped.\n first_element = None\n finished = True\n for v in g.vertices:\n if first_element is None or \\\n (v.queue_position < first_element.queue_position and\n not v.popped):\n first_element = v\n if v.seen and not v.popped:\n finished = False\n\n # We now have the vertex that is the first element in the queue, so we\n # investigate its neighbours as before\n first_element.popped = True\n for w in first_element.neighbours:\n if not w.seen:\n w.queue_position = last_queue_position\n # We increment the last queue position\n last_queue_position += 1\n w.seen = True\n","sub_path":"20-21/Lent/Algorithms/Supervision 4/Work/Q7/q7.py","file_name":"q7.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"408250436","text":"import bs4, argparse, sys, re, datetime, time, shutil, os.path, random\nimport urllib.request as urllib\nimport urllib.parse as urlparse\nfrom hurry.filesize import size\nimport dir_time_bar as dtb\n\n\ndef get_html(url):\n try:\n hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',\n 'Accept-Encoding': 'none',\n 'Accept-Language': 'en-US,en;q=0.8',\n 'Connection': 'keep-alive'}\n req = urllib.Request(url, headers=hdr)\n res = urllib.urlopen(req)\n txt = res.read()\n txtstr = txt.decode(\"utf-8\")\n return txtstr\n except:\n parser.print_help()\n sys.exit()\n\n\ndef get_board_name(url):\n path = urlparse.urlparse(url).path.split(\"/\")[1]\n return '[' + path + ']'\n\n\ndef get_op(html):\n folder_name = ''\n soup = bs4.BeautifulSoup(html, 'html.parser')\n subjects = soup.find_all('span', {'class': 'subject'})\n subject = subjects[1].text\n op = soup.find('blockquote', {'class': 'postMessage'}).text\n if subject != \"\":\n subject = subject.replace(\"'\", \"\")\n subject = re.sub(r\"[^a-zA-Z0-9-!]+\", ' ', subject)\n subject_words = subject.split(\" \")\n folder_name += make_str(subject_words, True)\n else:\n op = op.replace(\"'\", \"\")\n op = re.sub(r\"[^a-zA-Z0-9-!]+\", ' ', op)\n op_words = op.split(\" \")\n folder_name += make_str(op_words, False)\n if folder_name[:1] == \"_\":\n return folder_name[1:-1]\n else:\n return folder_name[:-1]\n\n\ndef make_str(words, subject_bool):\n string = ''\n if not subject_bool:\n if len(words) < 7:\n for word in words:\n string += word + \"_\"\n else:\n for x in range(0, 7):\n string += words[x] + \"_\"\n else:\n for word in words:\n string += word + \"_\"\n return string\n\ndef check_fn(filename, fn_dict):\n new_fn = filename.lower()\n if new_fn in fn_dict:\n fn_l = filename.rsplit('.', 1)\n new_fn = fn_l[0] + str(random.randint(1, len(fn_dict))) + '.' + fn_l[1]\n if new_fn in fn_dict:\n check_fn(new_fn, fn_dict)\n else:\n return new_fn\n else:\n return new_fn\n\ndef get_download_links(html):\n soup = bs4.BeautifulSoup(html, 'html.parser')\n event_cells = soup.find_all('div', {'class': 'fileText'})\n url_filename_dict = {}\n for e in event_cells:\n file_url = e.select('a')[0]['href']\n file_url = \"https:\" + file_url\n filename = e.select('a')[0]\n if filename.has_attr('title'):\n filename = filename['title']\n else:\n filename = filename.text\n if filename == \"Spoiler Image\":\n filename = e[\"title\"]\n filename = check_fn(filename, url_filename_dict)\n url_filename_dict.update({filename: file_url})\n return url_filename_dict\n\n\n\ndef download_files(links_and_filenames_dict, directory, url, list_bool, time_bool, overwrite_bool, length, index=1):\n start = time.time()\n path = get_board_name(url) + get_op(get_html(url)) + '/'\n i = index\n if directory == None:\n dtb.check_dir(path, overwrite_bool, length, index)\n else:\n path = directory + path\n dtb.check_dir(path, overwrite_bool, length, index)\n for filename_key, url_value in links_and_filenames_dict.items():\n try:\n with urllib.urlopen(url_value) as dlFile:\n content = dlFile.read()\n filename = filename_key.replace('?', '')\n complete_name = os.path.join(path + filename)\n file = open(complete_name, \"wb\")\n file.write(content)\n file.close\n print(url_value + \" was saved as \" + filename)\n dtb.printProgressBar(i, length, prefix = 'Progress:', suffix = 'Complete', length = 25)\n i += 1\n except Exception as e:\n print(e)\n end = time.time()\n total_time = end - start\n if time_bool:\n dtb.get_time(total_time)\n if not list_bool:\n dir_files_list = dtb.calc_dir_size(path, list_bool)\n print(\"\\nYou downloaded \" +\n dir_files_list[1] + \" files with a combined filesize of \" + dir_files_list[0])\n else:\n return_list = [dtb.calc_dir_size(path, list_bool), i]\n return return_list\n\n\nif __name__ == '__main__':\n disk_space = 0\n amount_files = 0\n parser = argparse.ArgumentParser(\n description='A script that downloads all media files from a 4chan thread')\n parser.add_argument(\n '-u', '--url', help='URL for the 4chan thread you want to download the files from')\n parser.add_argument('-d', '--destination', help='The absolute path to the directory you want the new folder with the downloaded files to be stored in. NOTE: If left blank, a new directory will be created in the active directory from where you are running the script.')\n parser.add_argument(\n '-l', '--list', help=\"List of thread URLs you want to download the files from. List needs to be surrounded by quotation marks and URLs seperated by spaces.\", type=str)\n parser.add_argument(\n '-o', '--overwrite', help='Automatically overwrites any folders with the same name as the folders being created by the script', action='store_true')\n args = parser.parse_args()\n if args.url == None:\n if args.list == None:\n parser.print_help()\n sys.exit()\n if args.url == \"test\":\n print(\"URL: \" + str(args.url))\n print(\"Destination: \" + str(args.destination))\n print(\"URL List:\" + str(args.list))\n sys.exit()\n dest = args.destination\n if dest != None:\n if dest[-1:] != \"/\" or dest[-1:] != \"\\\\\":\n dest = dest + \"/\"\n if args.list != None:\n start = time.time()\n url_list = [str(item) for item in args.list.split(' ')]\n length = 0\n index = 1\n for url in url_list:\n length += len(get_download_links(get_html(url)))\n for url in url_list:\n return_list = download_files(get_download_links(get_html(url)),\n dest, url, True, False, args.overwrite, length, index)\n disk_space += return_list[0][0]\n amount_files += return_list[0][1]\n index = return_list[1]\n end = time.time()\n total_time = end - start\n dtb.get_time(total_time)\n else:\n download_files(get_download_links(get_html(args.url)),\n dest, args.url, False, True, args.overwrite, len(get_download_links(get_html(args.url))))\n if disk_space > 0:\n print(\"\\nYou downloaded \" +\n str(amount_files) + \" files with a combined filesize of \" + size(disk_space))\n","sub_path":"downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":6965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"242715542","text":"from time import sleep\n\nfrom selenium import webdriver\n\n\nclass Wework:\n def __init__(self):\n self.driver = webdriver.Chrome()\n # self.driver.maximize_window()\n self.driver.implicitly_wait(10)\n url = \"https://work.weixin.qq.com/wework_admin/frame#contacts\"\n self.driver.get(url)\n cookie = {\"wwrtx.i18n_lan\": \"zh\",\n \"wwrtx.d2st\": \"a1821743\",\n \"wwrtx.sid\": \"fyDmugfJ4e01ULqCxU1emKHGMfG1VHO8p_X0XbN-5U4bgjzmYna_BdY5j3zncFI5\",\n \"wwrtx.ltype\": \"1\",\n \"wxpay.corpid\": \"1970324980092056\",\n \"wxpay.vid\": \"1688850754733339\"}\n for k, v in cookie.items():\n self.driver.add_cookie({\"name\": k, \"value\": v})\n self.driver.get(url)\n\n def quit(self):\n # self.driver.quit()\n sleep(4)","sub_path":"test_po/wework_page.py","file_name":"wework_page.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"603544175","text":"import sys\n\n#array_file_name = sys.argv[1]\n#array_file = open(array_file_name, 'r')\n\n#array1_text = array_file.readline()\n#array2_text = array_file.readline()\n\narray1_text = input()\narray2_text = input()\n\ndef make_list(array_text):\n array = []\n for i in array_text.split(\" \"):\n array.append(int(i))\n return array\n\narray1 = make_list(array1_text)\narray2 = make_list(array2_text)\n\narray = array1 + array2\n\ndef merge(array):\n if len(array) > 1:\n midpoint = len(array) // 2\n left = array[midpoint:]\n right = array[:midpoint]\n \n #Reference variables for indexes\n ref1 = 0\n ref2 = 0\n ref3 = 0\n\n #recursively call function\n merge(left)\n merge(right)\n\n while True:\n if ref1 >= len(left) or ref2 >= len(right):\n break\n if left[ref1] >= right[ref2]: \n array[ref3] = right[ref2] \n ref2 = ref2 + 1\n else: \n array[ref3] = left[ref1] \n ref1 = ref1 + 1\n ref3 = ref3 + 1\n\n while True: \n if ref1 >= len(left):\n break\n array[ref3] = left[ref1] \n ref1 = ref1 + 1\n ref3 = ref3 + 1\n\n while True: \n if ref2 >= len(right):\n break\n array[ref3] = right[ref2] \n ref2 = ref2 + 1\n ref3 = ref3 + 1\n\nstring = ''\nmerge(array)\nstring = str(len(array)) + \" \"\nfor i in array:\n string = string + str(i) + ' '\nstring = string[:-1]\nprint(string)\n\n#output_file_name = sys.argv[2]\n#output_file_name = \"my-output-1.txt\"\n#sys.stdout = open(output_file_name, \"w\")\n\n#print(string)\n\n#sys.stdout = sys.__stdout__jjhhj\n\n\n\n","sub_path":"assignment1/problem1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"221338715","text":"# Assignment #2: Task #1 \n\n# importing os module \nimport os \n\n# Get the list of all files and directories in the root directory \npath =\"C:\\\\Users\\Lenovo\\Documents\\GitHub\\Python-Bootcamp-DSC-DSU\\week_1\"\ndir_list = os.listdir(path) \n\nprint(\"Files and directories in '\", path, \"' :\") \n\n# print the list \nprint(dir_list) \n\n# Printing the list by loop\n# for x in dir_list:\n# print(x)\n\n\ndef get_filepaths(directory):\n \"\"\"\n This function will generate the file names in a directory \n tree by walking the tree either top-down or bottom-up. For each \n directory in the tree rooted at directory top (including top itself), \n it yields a 3-tuple (dirpath, dirnames, filenames).\n \"\"\"\n file_paths = [] # List which will store all of the full filepaths.\n\n # Walk the tree.\n for root, directories, files in os.walk(directory):\n for filename in files:\n # Join the two strings in order to form the full filepath.\n filepath = os.path.join(root, filename)\n file_paths.append(filepath) # Add it to the list.\n\n return file_paths # Self-explanatory.\n\n# Run the above function and store its results in a variable. \nfull_file_paths = get_filepaths(\"C:\\\\Users\\Lenovo\\Documents\\GitHub\\Python-Bootcamp-DSC-DSU\\week_1\")\n","sub_path":"week_2/A2.1.py","file_name":"A2.1.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"474057680","text":"\nclass SeparatedCoderCL():\n def __init__(self, img_shape, convolution_kernel_widths, workgroup_width, template_filename):\n self.image_width = img_shape[1]\n self.image_height = img_shape[0]\n self.convolution_kernel_widths = convolution_kernel_widths\n self.workgroup_width = workgroup_width\n self.convolution_template = template_filename\n \n self.opencl_sourcecodes = {}\n for cell in convolution_kernel_widths.keys():\n if cell == \"midget\":\n continue\n self.opencl_sourcecodes[cell] = {}\n for centre in convolution_kernel_widths[cell].keys():\n self.opencl_sourcecodes[cell][centre] = self.code_separated_convolution(cell, centre)\n\n\n\n\n def code_separated_convolution(self, cell, centre):\n kernel_width = self.convolution_kernel_widths[cell][centre]\n workgroup_width = self.workgroup_width\n image_width = self.image_width\n image_height = self.image_height\n \n kernel_template_file = open(self.convolution_template, 'r')\n kernel_string = kernel_template_file.read()\n\n return_type = \"uchar\"\n float_type = \"float\"\n half_kernel_width = kernel_width/2\n mem_size = (workgroup_width + 2*half_kernel_width)*(workgroup_width)\n\n vertical_convolution_termination = \"3\" if cell == \"parasol\" else \"1\"\n horizontal_convolution_termination = \"5\" if cell == \"parasol\" else \"1\"\n\n horizontal_loading = self.load_horizontal_memory(kernel_width, workgroup_width, image_width, image_height)\n vertical_loading = self.load_vertical_memory(kernel_width, workgroup_width, image_width, image_height)\n\n first_horizontal_conv = self.horizontal_convolution_loop(kernel_width, image_width, \"first\", \"horizontal_vector\")\n first_vertical_conv = self.vertical_convolution_loop(kernel_width, image_width, workgroup_width, \"first\", \"vertical_vector\")\n\n var_dict = {\"$final_cast\": return_type,\n \"$float_type\": float_type,\n \"$half_kernel_width\": str(half_kernel_width),\n \"$img_width\": image_width,\n \"$img_height\": image_height,\n \"$right_horizontal_limit\": str(image_width - 2*half_kernel_width),\n \"$lower_vertical_limit\": str(image_height - 2*half_kernel_width),\n \"$mem_size\": str(mem_size),\n \"$mem_width_h\": str(workgroup_width + 2*half_kernel_width),\n \"$mem_width_v\": str(workgroup_width),\n \"$local_memory_load_horizontal\": horizontal_loading,\n \"$local_memory_load_vertical\": vertical_loading,\n \"$first_horizontal_loop\": first_horizontal_conv,\n \"$first_vertical_loop\": first_vertical_conv,\n \"$horizontal_convolution_termination\": horizontal_convolution_termination,\n \"$vertical_convolution_termination\": vertical_convolution_termination,\n \"$local_col_padding_horizontal\": \" + %s\"%(half_kernel_width),\n \"$local_row_padding_vertical\": \" + %s\"%(half_kernel_width),\n \"$local_row_padding_horizontal\": \" + %s\"%(half_kernel_width),\n \"$local_col_padding_vertical\": \" + %s\"%(half_kernel_width),\n }\n\n for key, val in var_dict.items():\n kernel_string = kernel_string.replace(key, str(val), 100)\n\n return kernel_string\n\n\n def load_horizontal_memory(self, kernel_width, local_width, image_width, image_height):\n\n half_kernel_width = kernel_width/2\n memory_width = local_width + 2*half_kernel_width\n\n load_template = \" srcTmp[local_coord %s %s] = srcImg[out_coord %s %s]; \\n\"\n\n load_loop = \" srcTmp[local_coord] = srcImg[out_coord];\\n\"\n\n if_left = \" if(local_col == %s ){//left\\n%s }\\n\"%(0, \"%s\")\n\n if_right = \" if(local_col == %s ){//right\\n%s }\\n\"%(local_width - 1, \"%s\")\n\n left_loop = \"\"\n for col in xrange(-half_kernel_width,0):\n left_loop = \"%s%s\"%(left_loop, load_template)\n local_diff = col\n local_sign = \"-\" if local_diff < 0 else \"+\"\n local_diff = abs(local_diff)\n\n out_diff = col\n out_sign = \"-\" if out_diff < 0 else \"+\"\n out_diff = abs(out_diff)\n\n left_loop = left_loop%(local_sign, local_diff, out_sign, out_diff)\n\n left_loop = if_left%(left_loop)\n\n\n\n right_loop = \"\"\n for col in xrange(1, half_kernel_width+1):\n right_loop = \"%s%s\"%(right_loop, load_template)\n local_diff = col\n local_sign = \"-\" if local_diff < 0 else \"+\"\n local_diff = abs(local_diff)\n\n out_diff = col\n out_sign = \"-\" if out_diff < 0 else \"+\"\n out_diff = abs(out_diff)\n\n right_loop = right_loop%(local_sign, local_diff, out_sign, out_diff)\n\n right_loop = if_right%(right_loop)\n\n\n\n load_loop = \"%s%s%s\"%(load_loop, left_loop, right_loop)\n return load_loop\n\n\n\n def load_vertical_memory(self, kernel_width, local_width, image_width, image_height):\n half_kernel_width = kernel_width/2\n memory_width = local_width\n\n load_template = \" srcTmp[local_coord %s %s] = tmpImg[out_coord %s %s]; \\n\"\n\n load_loop = \" srcTmp[local_coord] = tmpImg[out_coord];\\n\"\n\n if_top = \" if(local_row == %s){//top\\n%s }\\n\"%(0, \"%s\")\n\n if_bottom = \" if(local_row == %s){//botom\\n%s }\\n\"%(local_width - 1, \"%s\")\n\n top_loop = \"\"\n for row in xrange(-half_kernel_width,0):\n top_loop = \"%s%s\"%(top_loop, load_template)\n local_diff = row*memory_width\n local_sign = str_sign(local_diff)\n local_diff = abs(local_diff)\n\n out_diff = row*image_width\n out_sign = str_sign(out_diff)\n out_diff = abs(out_diff)\n\n top_loop = top_loop%(local_sign, local_diff, out_sign, out_diff)\n\n top_loop = if_top%(top_loop)\n\n bottom_loop = \"\"\n for row in xrange(1, half_kernel_width + 1):\n bottom_loop = \"%s%s\"%(bottom_loop, load_template)\n local_diff = row*memory_width\n local_sign = str_sign(local_diff)\n local_diff = abs(local_diff)\n\n out_diff = row*image_width\n out_sign = str_sign(out_diff)\n out_diff = abs(out_diff)\n\n bottom_loop = bottom_loop%(local_sign, local_diff, out_sign, out_diff)\n\n bottom_loop = if_bottom%(bottom_loop)\n\n\n load_loop = \"%s%s%s\"%(load_loop, top_loop, bottom_loop)\n return load_loop\n\n\n\n def horizontal_convolution_loop(self, kernel_width, image_width, output_var_name, gauss_vector_name):\n half_kernel_width = kernel_width/2\n\n op_template = \" %s += %s*%s;\\n\"%(output_var_name, \"srcTmp[local_coord %s %s]\", gauss_vector_name+\"[%s]\")\n\n kernel_weight_idx = 0\n loop_string = \"\"\n for col in xrange(-half_kernel_width, half_kernel_width + 1):\n if col == 0:\n loop_string = \"%s%s\"%(loop_string, op_template%(\"\", \"\", kernel_weight_idx))\n else:\n diff = col\n sign = str_sign(diff)\n diff = abs(diff)\n loop_string = \"%s%s\"%(loop_string, op_template%(sign, diff, kernel_weight_idx))\n\n kernel_weight_idx += 1\n\n return loop_string\n\n def vertical_convolution_loop(self, kernel_width, image_width, local_width, output_var_name, gauss_vector_name):\n half_kernel_width = kernel_width/2\n memory_width = local_width\n\n op_template = \" %s += %s*%s;\\n\"%(output_var_name, \"srcTmp[local_coord %s %s]\", gauss_vector_name+\"[%s]\")\n\n kernel_weight_idx = 0\n loop_string = \"\"\n for row in xrange(-half_kernel_width, half_kernel_width + 1):\n if row == 0:\n loop_string = \"%s%s\"%(loop_string, op_template%(\"\", \"\", kernel_weight_idx))\n else:\n diff = row*local_width\n sign = str_sign(diff)\n diff = abs(diff)\n loop_string = \"%s%s\"%(loop_string, op_template%(sign, diff, kernel_weight_idx))\n\n kernel_weight_idx += 1\n\n return loop_string\n\n\n############################################################################################\n# helper!\n############################################################################################\n\ndef str_sign(val):\n if val < 0:\n return \"-\"\n else:\n return \"+\"\n","sub_path":"convolutionCL/separatedCoderCL.py","file_name":"separatedCoderCL.py","file_ext":"py","file_size_in_byte":7923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"578977454","text":"#EC2 Instance and Attaching a 5gb EBS Volume..\r\n#################################################################################################\r\nimport boto3\r\nimport subprocess as sb\r\nec2 = boto3.resource('ec2')\r\n# Connecting to AWS..We have to configure our AWS CLI first!!!\r\n\r\ndef EC2_launch():\r\n try:\r\n #LAunching an Ec2 Instance..\r\n instance = ec2.create_instances(\r\n ImageId='ami-0ad704c126371a549',\r\n MinCount=1,\r\n MaxCount=1,\r\n InstanceType='t2.micro',\r\n SecurityGroupIds=['sg-026dd3773ee684723'],\r\n SubnetId='subnet-c8c5cca0',)\r\n return (instance[0].id) \r\n except:\r\n print(\"Configure your AWS CLI first!!\\n\")\r\n\r\n###############################################################################################################################\r\n# Creating a New EBS Volume..\r\ndef EBS_create():\r\n try:\r\n ec2 = boto3.resource('ec2')\r\n ebs = ec2.create_volume(AvailabilityZone='ap-south-1a', Size=5, VolumeType='gp2')\r\n return (ebs.id)\r\n except:\r\n print(\"Please check your internet Connectivity!!\\n\")\r\n###############################################################################################################################\r\n# Attaching NEW-EBS with the EC2 insatnce \r\ndef Attach_EBS_to_EC2(ins_id,vol_id):\r\n volume = ec2.Volume(vol_id)\r\n attach_ebs= volume.attach_to_instance(\r\n Device='/dev/sdh',\r\n InstanceId=ins_id,\r\n VolumeId=vol_id,)\r\n return 0\r\n\r\n#################################################################################################################################\r\nimport time\r\n## Using Facial Recognition..For Sending Mail!! \r\nface_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\ndef face_detector(img, size=0.5):\r\n # Convert image to grayscale\r\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n faces = face_classifier.detectMultiScale(gray, 1.3, 5)\r\n if faces is ():\r\n return img, []\r\n for (x,y,w,h) in faces:\r\n cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,255),2)\r\n roi = img[y:y+h, x:x+w]\r\n roi = cv2.resize(roi, (200, 200))\r\n return img, roi\r\n\r\n# Open Webcam\r\ncap = cv2.VideoCapture(0)\r\nf=0\r\ntrigger=0\r\nwhile True:\r\n ret, frame = cap.read()\r\n image, face = face_detector(frame)\r\n try:\r\n face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)\r\n results = vimal_model.predict(face)\r\n if results[1] < 500:\r\n confidence = int( 100 * (1 - (results[1])/400) )\r\n display_string = str(confidence) + '% Confident it is User'\r\n cv2.putText(image, display_string, (100, 120), cv2.FONT_HERSHEY_COMPLEX, 1, (255,120,150), 2) \r\n if confidence >=85:\r\n cv2.imshow(\"face\",face)\r\n f=f+1\r\n else:\r\n print(\"Come infront of the camera.....\")\r\n if f==25:\r\n trigger=1\r\n print(\"One face detected...Launching EC2 instance\")\r\n break\r\n except:\r\n pass\r\n \r\n if cv2.waitKey(10) == 13: #13 is the Enter Key\r\n break\r\n \r\ncap.release()\r\ncv2.destroyAllWindows()\r\n\r\nif trigger==1:\r\n ec2_launch = EC2_launch()\r\n ebs=EBS_create()\r\n time.sleep(30)\r\n att=Attach_EBS_to_EC2(ec2_launch,ebs)\r\n####################################################################################################################################","sub_path":"Code in parts/Launching AWS_EBS_Attaching5gb.py","file_name":"Launching AWS_EBS_Attaching5gb.py","file_ext":"py","file_size_in_byte":3452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"129275708","text":"import tensorflow as tf\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nmnist = input_data.read_data_sets(\"./MNIST_data/\",one_hot = True)\r\n\r\ntrainimg = mnist.train.images # training image\r\ntrainlabel = mnist.train.labels # training labels\r\ntestimg = mnist.test.images # test image\r\ntestlabel = mnist.test.labels # test lables\r\n\r\nx = tf.placeholder(tf.float32,[None,784],name = \"x\")\r\n\r\ny = tf.placeholder(tf.float32,[None,10],name = \"y\")\r\n\r\nW = tf.Variable(tf.zeros([784,10]))\r\nb = tf.Variable(tf.zeros([10]))\r\n\r\nactv = tf.nn.softmax(tf.matmul(x,W) + b,name = \"func\")\r\n\r\ncost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(tf.clip_by_value(actv,1e-10,1.0)),reduction_indices=1))\r\n\r\nlearning_rate = 0.01\r\noptm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\r\n\r\npred = tf.equal(tf.argmax(actv,1),tf.argmax(y,1))\r\n\r\naccr = tf.reduce_mean(tf.cast(pred,tf.float32))\r\n\r\ninit_op = tf.global_variables_initializer()\r\n\r\ntraining_epochs = 50\r\nbatch_size = 100\r\ndisplay_step = 5\r\n\r\nsaver = tf.train.Saver()\r\n\r\nwith tf.Session() as sess:\r\n sess.run(init_op)\r\n saver.restore(sess, \"./MNIST_model/MNIST.model\")\r\n for epoch in range(training_epochs):\r\n avg_cost = 0\r\n num_batch = int(mnist.train.num_examples / batch_size)\r\n\r\n for i in range(num_batch):\r\n #batch_xs is shape of [100,784],batch_ys is shape of [100,10]\r\n batch_xs,batch_ys = mnist.train.next_batch(batch_size)\r\n sess.run(optm, feed_dict={x: batch_xs, y: batch_ys})\r\n feeds = {x: batch_xs, y: batch_ys}\r\n avg_cost += sess.run(cost, feed_dict=feeds) / num_batch\r\n\r\n if epoch % display_step == 0:\r\n feed_train = {x: trainimg[1: 100], y: testlabel[1: 100]}\r\n feedt_test = {x: mnist.test.images, y: mnist.test.labels}\r\n train_acc = sess.run(accr, feed_dict=feed_train)\r\n test_acc = sess.run(accr, feed_dict=feedt_test)\r\n\r\n print(\"Eppoch: %03d/%03d cost: %.9f train_acc: %.3f test_acc: %.3f\" %\r\n (epoch, training_epochs, avg_cost, train_acc, test_acc))\r\n saver.save(sess, \"./MNIST_model/MNIST.model\")\r\n\r\nprint(\"Done.\")\r\n\r\n\r\n","sub_path":"MNIST.py","file_name":"MNIST.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"245701416","text":"'''\nExample of a fully programmatic simulation, without definition files.\n'''\nfrom soil import Simulation, agents\nfrom networkx import Graph\nimport logging\n\n\ndef mygenerator():\n # Add only a node\n G = Graph()\n G.add_node(1)\n return G\n\n\nclass MyAgent(agents.FSM):\n\n @agents.default_state\n @agents.state\n def neutral(self):\n self.info('I am running')\n\n\ns = Simulation(name='Programmatic',\n network_params={'generator': mygenerator},\n num_trials=1,\n max_time=100,\n agent_type=MyAgent,\n dry_run=True)\n\n\nlogging.basicConfig(level=logging.INFO)\nenvs = s.run()\n\ns.dump_yaml()\n\nfor env in envs:\n env.dump_csv()\n","sub_path":"examples/programmatic/programmatic.py","file_name":"programmatic.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"357938887","text":"import unittest\nimport numpy as np\nimport spectral.core as sc\n\n\nclass SinusoidalTests(unittest.TestCase):\n def setUp(self):\n self.freqs = [100, 200, 300]\n\n self.samp_freq = 1000\n self.SNR = 10\n\n def no_noise_test(self):\n expected_complex_freqs = [200, 300, 400, 600, 700, 800]\n delta = 1e-6\n\n source = sc.source.Sinusoidal(self.freqs, self.samp_freq)\n samples = source.generate(self.samp_freq)\n fft = np.abs(np.fft.fftshift(np.fft.fft(samples)))\n\n for i, v in enumerate(fft):\n if i in expected_complex_freqs:\n self.assertGreater(v, delta)\n else:\n self.assertLess(v, delta)\n","sub_path":"src/tests/source_tests/sinusoidal_tests.py","file_name":"sinusoidal_tests.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"7945323","text":"def gcd(a,b):\n if a Array where elements need to be searched\nx ==> Element to be searched\nlo ==> Starting index in arr[]\nhi ==> Ending index in arr[]\n\n\nHERE lo=0\narr[lo] will be taken from user\nhi=(n-1)\narr[hi] will be taken from user\nTIME COMPLEXITY=o(log2(log2 n))\n\n\"\"\"\ndef interpolationSearch(a,n):\n x=int(input(\"enter ele you want to search\"))\n left=0\n right= n-1\n position=0\n while(position<=(n-1)):\n if(a[position]==x):\n print(\"ele \"+str(x)+\"is present at \"+str(position)+\"index \")\n return 0\n if(a[position]>x):\n right=position-1\n position=(int)((left)+((x-a[left])*(right-left)/(a[right]-a[left])))\n print(position)\n if(a[position] 0:\n related_samples = related_samples[0]\n related_samples = {'objectID':related_samples[0], 'result':json.loads(related_samples[1])}\n if len(related_samples['result']) > 1: # if object_class=0 is related\n new_samples.append(sample)\n continue\n name = self.default_related_name\n if master_handler is not None:\n related_object = master_handler.get('objects', {'objectID':related_samples['objectID']})[0]\n name = related_object['name']\n sample['result'].append({'name':name, 'value':related_samples['result']['value']})\n new_samples.append(sample)\n return new_samples\n else:\n return samples\n\n def set_value(self, valueID, data):\n \"\"\"\n INPUT:\n valueID: valueID\n data: {'data':{'result':[...], 'date':...}}\n \"\"\"\n _data = {'valueID':valueID, 'result':json.dumps(data['data']['result'])}\n self.rec_handler.add(\"log\", \"valueID\", [_data])\n print(\"valueID:{} | Value Edited\".format(valueID))\n return {'success':True}\n\n def delete_value(self, valueID):\n self.rec_handler.delete('log', {'valueID':valueID})\n print(\"valueID:{} | Deleted\".format(valueID))\n return {'success':True}\n\nif __name__ == '__main__':\n from pprint import pprint\n rec_handler = DB_Handler('../../db/recognized.db')\n vh = Value_Handler(rec_handler)\n vh.get_values('1621', '2020-11-30', '2020-12-03', 1)\n","sub_path":"utils/value_handler.py","file_name":"value_handler.py","file_ext":"py","file_size_in_byte":4831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"473379708","text":"import ecdsa\n#import sha3\nfrom ecdsa.ecdsa import curve_secp256k1\nfrom ecdsa.curves import SECP256k1\nfrom ecpy.curves import Curve, Point\n#from ecdsa import SECP256k1 # This is useful to avoid manual curve key computations.#SECP256k1 \n# can be changed based on the desired specifications in the SEC document.\n# Refer to downloaded document in Block_chain_stuff ---- Recommended EC domain parameters.\n#\nimport os\nimport sys\nimport numpy as np\nfrom hashlib import sha256\nimport binascii\nimport re\n\n\nfrom ecdsa.util import string_to_number, number_to_string\n\n# Based on secp256k1, http://www.oid-info.com/get/1.3.132.0.10\n\n_p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F\n_r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141\n_b = 0x0000000000000000000000000000000000000000000000000000000000000007\n_a = 0x0000000000000000000000000000000000000000000000000000000000000000\n_Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798\n_Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8\n\ncurve_secp256k1 = ecdsa.ellipticcurve.CurveFp(_p, _a, _b)\ngenerator_secp256k1 = ecdsa.ellipticcurve.Point(curve_secp256k1, _Gx, _Gy, _r)\noid_secp256k1 = (1, 3, 132, 0, 10)\nSECP256k1 = ecdsa.curves.Curve(\"SECP256k1\", curve_secp256k1, generator_secp256k1, oid_secp256k1)\nec_order = _r\ncurve = curve_secp256k1\ncv = Curve.get_curve('secp256k1')\n#generator = generator_secp256k1\ngenerator = Point(_Gx, _Gy, cv) # Another way to get the G\nbyte_array=''\n\n\ndef random_secret(): # Method to generate private key. \n byte_array = os.urandom(32)\n joinArray = \"\".join([str(i) for i in byte_array])\n convert_to_int = int(joinArray)\n encode_int = int(hex(convert_to_int), 16)\n return (encode_int % ec_order)\n\n\ndef getKeyPair():\n # Now going to generate a new private key.\n secret = random_secret() #Generate a new private key.\n P = (secret*generator)\n #PublicKeyP = get_point_pubkey(P)\n PublicKeyP = (sha256(str(P).encode())).hexdigest() # Displaying Public key in hex format.\n print(\"The Public key is:\", PublicKeyP)\n return secret, P\n\n\ndef getRvalue(r):\n R = cv.mul_point(r,generator) \n return R\n\n\ndef get_point_pubkey(point):\n '''\n Converts point to hex format.\n '''\n if point.y & 1:\n key = '03' + '%064x' % point.x\n else:\n key = '02' + '%064x' % point.x\n return key\n\n\ndef ProverComputations():\n x, P = getKeyPair() # (x,P) for Prover.\n\n r = random_secret() # Prover choses random nonce value r. \n\n R = getRvalue(r)\n print(\"R value is: \", R)\n\n # Challenge e using H(R)\n e = int((sha256(str(R).encode())).hexdigest(),16)\n print(\"Value of e is: \", e)\n #x = int(x,16)\n s = hex((r + (e*x)) % ec_order) # Check this area for ecmul usage.\n s = int(s,16)\n print(\"The response s value is: \", s)\n return P,R,e,s\n\n\ndef VerifierComputations(P,R,e,s):\n leftSidePoint = (s*generator)\n leftSide = (sha256(str(leftSidePoint).encode())).hexdigest()# In hex format.\n print(\"Left side value is: \", leftSide)\n\n #px =P.x\n #py =P.y \n #P = Point(px,py,cv)\n eP = e*P #cv.mul_point(e,P) also works fine. \n addends = cv.add_point(R, eP)\n rightSide = (sha256(str(addends).encode())).hexdigest() # In hex format.\n print(\"Right side value is: \", rightSide)\n return leftSide, rightSide\n\ndef verificationCheck(rightSide, leftSide):\n if(rightSide==leftSide):\n print(\"Successful proof.\")\n else:\n print(\"Failed proof\")\n return\n\n\n# Main method for ZKP.\ndef main():\n print('')\n\n print(\"***********************Zero-Knowledge Proof using Schnorr***********\")\n\n print('')\n\n print (\"++++++++++ Prover's computations begins.+++++++++++++++\")\n\n print('')\n # Call Prover to perform computations.\n P,R,e,s = ProverComputations()\n print('')\n print (\"++++++++++ Prover's computations ends.+++++++++++++++\")\n\n print('')\n print (\"++++++++++ Verifier's computations begins.+++++++++++++++\")\n print('')\n rightSide, leftSide = VerifierComputations(P,R,e,s)\n print (\"++++++++++ Verifier's computations ends.+++++++++++++++\")\n\n print('')\n print (\"***************** Fetching Verifier's result.*************\")\n verificationCheck(rightSide, leftSide)\n print('')\n print (\"*************Verifier's result ends.***********************\")\n print('')\n print (\"++++++++++++++++++++++ End of program.++++++++++++++++++++++++++++++\")\n # Main method ends here. \n\n# Program execution time. \nmain()\n\n\n \n\n","sub_path":"NIZKP_DApp/ZkpOverSec256.py","file_name":"ZkpOverSec256.py","file_ext":"py","file_size_in_byte":4545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"428048066","text":"# Эта программа расконсервирует объекты CellPhone.\nimport pickle\nimport cellphone\n\n# Константа для имени файла.\nFILENAME = 'cellphone.dat'\n\ndef main():\n end_of_file = False # Для обозначения конца файла.\n\n # Открыть файл.\n with open(FILENAME, 'rb') as input_file:\n\n # Прочитать до конца файл.\n while not end_of_file:\n try:\n # Расконсервировать следующий объект.\n phone = pickle.load(input_file)\n\n # Показать данные о телефоне.\n display_data(phone)\n except EOFError:\n # Установить флаг, чтобы обозначить, что\n # был достигнут конец файла.\n end_of_file = True\n\n # Закрыть файл.\n input_file.close()\n\n# Функция display_data показывает данные\n# из объекта CellPhone, переданного в качестве аргумента.\ndef display_data(phone):\n print('Производитель:', phone.get_manifact())\n print('Номер модели:', phone.get_model())\n print('Розничная цена: ₽',\n format(phone.get_retail_price(), ',.2f'),\n sep='')\n print()\n\n# Вызвать главную функцию.\nmain()","sub_path":"10/unpickle_cellphone.py","file_name":"unpickle_cellphone.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"85702640","text":"#!venv/bin/python\n#\n# Banco de dados comandos necessários\n#\n# Ativa o ambiente virtual do projeto\n# source venv/bin/activate - linux\n# venv\\Scripts\\activate.bat - Windows\n#\n# inicia e cria a pasta migrate\n# python manager.py db init\n#\n# cria a primeira migração (-m indica uma mensagem sobre a migração)\n# python manager.py db migrate -m \"migração inicial\"\n# ou\n# python manager.py db migrate\n#\n# Ativa a primeira migração assim criando as tabelas\n# python manager.py db upgrade\n#\n# Regressa para a última migração\n# python manager.py db downgrade\n\nfrom app import criar_app, db, models, utils\nfrom flask_script import Manager, Shell, Server\nfrom flask_migrate import Migrate, MigrateCommand\n\napp = criar_app('default')\n\nmanager = Manager(app)\nmigrate = Migrate(app, db)\n\n\ndef make_shell_context():\n\treturn dict(app=app, db=db, md=models, utils=utils)\n\nmanager.add_command('runserver', Server(threaded=True))\nmanager.add_command('shell', Shell(make_context=make_shell_context, use_ipython=True))\nmanager.add_command('db', MigrateCommand)\n\nif __name__ == '__main__':\n\tmanager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"314449360","text":"##coding:utf8\nfrom flask import Flask, jsonify, Response, redirect, make_response\nfrom flask import request, session, url_for, Blueprint\nfrom flask import render_template, jsonify\nimport model\nfrom jsons import *\nac = Blueprint('star', __name__)\n\n@ac.route('/star', methods=['GET', 'POST'])\ndef star():\n\tif request.method == 'GET':\n\t\treturn render_template('star.html')\n\telse:\n\t\tif 'username' not in session:\n\t\t\treturn redirect(url_for('index'))\n\t\telse:\n\t\t\tuserid = session['id']\n\t\t\tpublishid = request.form['publishid']\n\t\t\tdb_star = model.star(userid=userid, publishid=publishid)\n\t\t\tresult = db_star.execute()\n\t\t\tif result == True:\n\t\t\t\tresp = make_response(render_template('star.html'), 200)\n\t\t\t\tresp.headers['X-Something'] = 'A value'\n\t\t\t\treturn resp\n\t\t\telse:\n\t\t\t\treturn 0\n\n@ac.route('/unstar', methods=['GET', 'POST'])\ndef unstar():\n\tif request.method == 'POST':\n\t\tif 'username' not in session:\n\t\t\treturn redirect(url_for('account.login'))\n\t\telse:\n\t\t\tuserid = session['id']\n\t\t\tpublishid = request.form['publishid']\n\t\t\tdb_star = model.star(userid=userid, publishid=publishid)\n\t\t\tresult = db_star.unstar()\n\t\t\tif result == True:\n\t\t\t\tresp = make_response(render_template('star.html'), 200)\n\t\t\t\tresp.headers['X-Something'] = 'A value'\n\t\t\t\treturn resp\n\t\t\telse:\n\t\t\t\treturn 0\n\n@ac.route('/stars/')\ndef stars(username):\n\tuserid = model.user(username=username).getUsername()\n\tdate = model.star(userid=userid).get()\n\tperson = model.person(userid=userid).get()\n\tuser = model.user(userid=userid).get()\n\treturn render_template('stars.html', date=date, person=person, user=user, title = 'My page')","sub_path":"ershoujiaoyi/controllers/star.py","file_name":"star.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"356437754","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom flask import Flask, request, g, jsonify, has_request_context, abort, \\\n send_from_directory, send_file, url_for, current_app\n\ntry:\n from flask import _app_ctx_stack as ctx_stack\nexcept ImportError: # pragma: no cover\n from flask import _request_ctx_stack as ctx_stack\n\n# Default App name\nDEFAULT_APP_NAME = 'myapp'\n\n\n__all__ = (\n 'create_app'\n)\n\n\ndef create_app(config_name=None):\n \"\"\" app工厂函数\n :param config_name:\n :return:\n \"\"\"\n\n app = Flask(DEFAULT_APP_NAME)\n configure_blueprints(app)\n return app\n\ndef configure_blueprints(app):\n from .auth.views import auth_blueprint\n app.register_blueprint(auth_blueprint, url_prefix='/admin')\n \n @app.route('/ping', methods=['GET'])\n def test_ping():\n return '

www.lockey.io

'\n","sub_path":"backend/myapp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"532145648","text":"#!/usr/bin/env python\n\n\"\"\"\n\nAs all of us who have read \"Harry Potter and the Chamber of Secrets\" knows, the reason He-Who-Must-Not-Be-Named chose his creepy moniker is that \"I Am Lord Voldemort\" is an anagram for his birthname, \"Tom Marvolo Riddle\".\n\nI've never been good at these kinds of word-games (like anagrams), I always find it hard to figure out that stuff manually.\nI find it much more enjoyable to write computer programs to solve these problems for me. In the spirit of that, today's problem is to find simple one-word anagrams for other words.\n\nWrite a program that given a word will find all one-word anagrams for that word. So, for instance, if you put in \"LEPROUS\", it should return \"PELORUS\" and \"SPORULE\".\nAs a dictionary, use this file, which is a 1.8 mb text-file with one word listed on each line, each word listed in upper-case.\nIn this problem description, I've used upper-case for all words and their anagrams, but that is entirely optional, it's perfectly all right to use upper-case if you want to.\n\nUsing your program, find all the one-word anagrams for \"TRIANGLE\".\n\n(by the way, in case anyone is curious: a \"PELORUS\" is \"a sighting device on a ship for taking the relative bearings of a distant object\", which I imagine basically is a telescope bolted onto a compass, and a \"SPORULE\" is \"a small spore\")\n\nBonus: if you looked up the anagrams for \"PAGERS\", you'd find that there was actually quite a few of them: \"GAPERS\", \"GASPER\", \"GRAPES\", \"PARGES\" and \"SPARGE\". Those five words plus \"PAGERS\" make a six-word \"anagram family\".\n\nHere's another example of an anagram family, this time with five words: \"AMBLERS\", \"BLAMERS\", \"LAMBERS\", \"MARBLES\" and \"RAMBLES\".\n\nWhat is the largest anagram family in the dictionary I supplied? What is the second largest?\n\n\"\"\"\n\ndef wordkey(w):\n return ''.join(sorted(w))\n\ndef makedict(name):\n m = {}\n f = open(name)\n for w in f:\n w = w.strip('\\n')\n w = w.upper()\n k = wordkey(w)\n if k not in m:\n m[k] = [w]\n else:\n m[k].append(w)\n \n for k in m:\n sorted(m[k])\n\n f.close()\n return m\n\ndef anagrams(m, w):\n w = w.upper()\n print(\"{} -> {}\".format(w, m.get(wordkey(w))))\n\ndef longest2(m):\n l1, l2 = 0, 0\n k1, k2 = \"\", \"\"\n for k in m:\n l = len(m[k])\n if l1 < l:\n l2, k2 = l1, k1\n l1, k1 = l, k\n elif l2 < l:\n l2, k2 = l, k\n\n return ((l1, m.get(k1)), (l2, m.get(k2)))\n\ndef main():\n m = makedict(\"enable1.txt\")\n\n anagrams(m, \"TRIANGLE\")\n anagrams(m, \"LEPROUS\")\n anagrams(m, \"PAGERS\")\n anagrams(m, \"AMBLERS\")\n\n print(longest2(m))\n\nmain()\n","sub_path":"dailyprogrammer/80-easy-anagrams.py","file_name":"80-easy-anagrams.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"193760042","text":"\"\"\"More test cases for ambianic.interpreter module.\"\"\"\nfrom ambianic import pipeline\nfrom ambianic.config_mgm import Config, ConfigChangedEvent\nfrom ambianic import config_manager\nfrom ambianic.pipeline import interpreter\nfrom ambianic.pipeline.avsource.av_element import AVSourceElement\nfrom ambianic.pipeline.interpreter import \\\n PipelineServer, Pipeline, HealingThread, PipelineServerJob\nimport logging\nimport time\nimport threading\nimport os\n\n\nlog = logging.getLogger()\nlog.setLevel(logging.DEBUG)\n\ndef test_pipeline_server_start_stop():\n\n\n _dir = os.path.dirname(os.path.abspath(__file__))\n\n config_manager.set(Config({\n \"sources\": {\n \"test\": {\n \"uri\": os.path.join(\n _dir,\n \"./avsource/test2-cam-person1.mkv\"\n )\n }\n },\n \"pipelines\": {\n \"test\": [\n { \"source\": \"test\" }\n ]\n }\n }))\n\n srv = PipelineServer(config_manager.get_pipelines())\n srv.start()\n srv.stop()\n\n\nclass PipelineServerEv(PipelineServer):\n\n def __init__(self, config):\n super().__init__(config)\n self.triggered = False\n\n def trigger_event(self, event: ConfigChangedEvent):\n log.debug(\"trigger restart\")\n super().trigger_event(event)\n self.triggered = True\n\n\ndef test_pipeline_server_config_change():\n\n\n _dir = os.path.dirname(os.path.abspath(__file__))\n\n source_cfg = {\n \"uri\": os.path.join(\n _dir,\n \"./avsource/test2-cam-person1.mkv\"\n )\n }\n\n config_manager.set(Config({\n \"pipelines\": {\n \"test\": [\n { \"source\": \"test\" }\n ]\n }\n }))\n\n srv = PipelineServerEv(config_manager.get_pipelines())\n srv.start()\n\n config_manager.get().add_callback(srv.trigger_event)\n config_manager.get_sources().set(\"test\", source_cfg)\n # the callback will restart the process \n assert srv.triggered\n","sub_path":"tests/pipeline/test_pipeline_server.py","file_name":"test_pipeline_server.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"24998147","text":"input_str = input(\"Введіть стрічку: \")\nvowel = \"уеіаоєяиюї\"\ncount = 0\nres_vowel = \"\"\nfor letter in input_str:\n if letter in vowel:\n count += 1\n res_vowel += letter\nif res_vowel:\n print(\"Голосні букви у стрічці \\\"{}\\\"\".format(res_vowel))\n print(\"Кількість голосних у стрічці {} шт.\".format(count))\nelse:\n print(\"На жаль голосних букв у вашій стрічці не знайдено.\")\n","sub_path":"Lesson3_Tasks/Lesson3_Task1.py","file_name":"Lesson3_Task1.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"446819653","text":"class Solution(object):\n def convertToBase7(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n # time limited exceeded\n # for i in xrange(-1e7, 1e7):\n # if int(str(i), 7)==num:\n # return i\n \n if num is 0:\n return '0'\n \n # record the sigh of num\n if num>=0:\n flag=True\n else:\n flag=False\n \n ans_str=''\n num=abs(num)\n \n # record the remanders in ans_str\n # dividable by 7 with num until num<=0\n while num!=0:\n ans_str=ans_str+str(num%7)\n num//=7\n \n # () is important here\n # first () determines the positive and negative sign\n # second () join the reverse string\n # because the un-reverse string is from one-digit to higher-digit\n return ('' if flag else '-')+ans_str[::-1]","sub_path":"base_7.py","file_name":"base_7.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"539808456","text":"from PyQt5 import QtWidgets\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtCore import Qt\nimport sys\nimport os\nimport numpy as np\n\nclass window(QtWidgets.QWidget):\n \n def __init__(self):\n super().__init__()\n self.set_ui()\n\n def done(self):\n self.close()\n\n def keyPressEvent(self, event):\n\n if (event.key() == \"enter\") or (event.key() == \"space\"):\n self.done()\n\n #def mousePressEvent(self, event):\n # print(\"press\",event.GrabMouse,event.DragMove, event.MouseButtonPress, event.MouseButtonRelease)\n # self.hold = True\n \n #def mouseReleaseEvent(self, event):\n # self.hold = False\n # print(\"release\")\n\n def set_ui(self):\n #self.hold = False\n #self.new = True\n #self.mag = 1\n icon = QIcon('icon.png')\n self.setWindowIcon(icon)\n self.setWindowTitle('Instructions')\n self.setGeometry(50,50,300,200)\n self.setMouseTracking(True)\n\n lab = \"Mouse Controls:

L. Click: Select atoms for next spin assignment
R. Click: Undo previous spin assignments

Keyboard Controls:

Enter: Assign Spins after selecting
t : Toggle non-magnetic atoms
b : Toggle bounding box
g : Toggle plot grid
n : Toggle ploted numbers on axes ticks
i : Instructions popup
f: Enter fullscreen mode
Escape: Exit Program
CTRL + / CTRL - : Zoom in or out
U / D Arrows: Change atom size
R / L Arrows: Change vector length\"\n\n self.l1 = QtWidgets.QLabel()\n self.l1.setText(lab)\n self.l1.move(50,0)\n\n self.b1 = QtWidgets.QPushButton()\n self.b1.setText(\"Done\")\n self.b1.move(50,25)\n self.b1.setAutoDefault(True)\n self.b1.clicked.connect(self.done)\n \n layout = QtWidgets.QVBoxLayout()\n layout.addWidget(self.l1)\n layout.addWidget(self.b1)\n self.setLayout(layout)\n\n\napp = QtWidgets.QApplication(sys.argv)\nwin = window()\nwin.show()\n\"\"\"\nqwindow = win.windowHandle()\n\nif qwindow is not None:\n \n def handle_activeChanged():\n if win.new:\n win.new = False\n #elif (not qwindow.isActive()) or (win.hold) :\n # win.close()\n \n qwindow.activeChanged.connect(handle_activeChanged)\n\"\"\"\nsys.exit(app.exec_())\n\n","sub_path":"textgui/instructions.py","file_name":"instructions.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"412757497","text":"from conf import bot\nfrom utils.logger import loggyballs as log\n\nimport os\nimport contextlib\nwith contextlib.redirect_stdout(None):\n from pygame import mixer\n\nmixer.init(frequency=44100)\n\nsfx_ch = 0\n\nlog.info(f\"{__name__} imported!\")\n\n\ndef play(full_file_path):\n mixer.Channel(sfx_ch).play(mixer.Sound(full_file_path))\n\n\nclass SoundEffect:\n 'Generates teh functions for all the sfx comands'\n\n \n def __init__(self, cmd_name, cmd_path):\n 'make an async func that registers/controls cmd'\n\n @bot.command(name=cmd_name)\n async def test_command(ctx):\n play(cmd_path)\n\n log.info(f\"[SFX] !{cmd_name} registered!\")\n\n\ndef generate_functions():\n path = 'sfx/hooks/'\n for file in os.listdir(path):\n if file.endswith('.ogg'):\n cmd_name = file[:-4]\n cmd_path = path + file\n SoundEffect(cmd_name, cmd_path)\n\n\ngenerate_functions()","sub_path":"sfx/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"472291179","text":"\nimport math\nfrom Vector import Vector\nclass Circle:\n def __init__(self, center, r, theta):\n self.center = center\n self.r = r\n self.theta = theta\n self.n = len(self.center.list)\n def param(self): # vector-like object\n v = Vector([0, 0])\n x = self.r*math.cos(self.theta)\n y = self.r*math.sin(self.theta)\n v1 = v.add(self.center.add(Vector([x, y])))\n return Vector(v1.list) # mporeis na kaneis return v1.list wste na alaxei to getpoints se lista\n def getPoints(self, n): # list of vectors\n points = []\n for i in range(n+1):\n self = Circle(self.center, self.r, 2*i*math.pi/n)\n points.append(self.param())\n return points","sub_path":"vectorBased/Circle.py","file_name":"Circle.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"404829693","text":"import pygame\nimport random\n\nclass Cube:\n def __init__(self):\n self.w = 600\n self.h = 20\n self.color = (255, 255, 255)\n\n def draw(self, surface, x, y):\n pygame.draw.rect(surface, self.color, (x, y, self.w, self.h))\n\nif __name__ == \"__main__\":\n clock = pygame.time.Clock()\n \n surface = pygame.display.set_mode((1600, 900), 0, 32)\n pygame.display.set_caption(\"Lines flickering\")\n\n cube = Cube()\n\n while True:\n clock.tick(20)\n surface.fill((0,0,0))\n\n # Draw blocks randomly\n block_coords = []\n\n block_coords.append((random.randint(-100, 1300),random.randint(0, 900)))\n block_coords.append((random.randint(-100, 1300),random.randint(0, 900)))\n block_coords.append((random.randint(-100, 1300),random.randint(0, 900)))\n\n for block in block_coords:\n cube.draw(surface, block[0], block[1])\n\n pygame.display.update()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit()","sub_path":"graphics/lines_flickering/lines_flickering.py","file_name":"lines_flickering.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"267740568","text":"#!/usr/bin/ipython3\nimport numpy as np\nimport matplotlib.pyplot as plt\n#import seaborn as sns\nimport emcee\nimport corner\nimport sys\n\n#sns.set_style('whitegrid')\nplt.ion()\n\n\nmism_m = np.load('mass_stacked_m.npy')\nerr_mism_m = np.load('mass_err_stacked_m.npy')\nz_avg = np.load('z_avg.npy')\nmstar = np.load('mass_stellar_avg.npy')\n\nf_gas_m = mism_m/(mism_m+(mstar))\nf_err_m = np.absolute(f_gas_m)*((np.absolute((mstar)/mism_m)*(err_mism_m/mism_m))/np.absolute(1+((mstar)/mism_m)))\n\n\ndef lnprior(params):\n p1, p2, p3 = params\n if -5.0 < p1 < 5.0 and -5.0 < p2 < 5.0 and -2.0 < p3 < 2.0:\n return 0.0\n else:\n return -np.inf\n\ndef lnlike(params, x1, x2, y, yerr):\n p1, p2, p3 = params\n model = (1+p1*(1+x1)**(p2)*(x2/1e10)**(p3))**(-1)\n sigma = yerr\n return -0.5*(np.nansum(((y-model)**2)/(sigma**2) + np.log(2*np.pi*sigma**2)))\n\ndef lnprob(params, x1, x2, y, yerr):\n lp = lnprior(params)\n if not np.isfinite(lp):\n return -np.inf\n else:\n return lp + lnlike(params, x1, x2, y, yerr)\n\n\nnp.random.seed(12654201)\n\nndim = 3\nnwalkers = 100\n\npos = []\nfor i in range(nwalkers):\n a = np.random.uniform(-5.0, 5.0)\n b = np.random.uniform(-5.0, 5.0)\n c = np.random.uniform(-2.0, 2.0)\n pos.append(np.asarray([a, b, c]))\n\nsampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(z_avg, mstar, \n f_gas_m, f_err_m), threads=4)\n\n\nnsteps = 1000\nwidth = 100\nfor i, result in enumerate(sampler.sample(pos, iterations=nsteps)):\n n = int((width+1)*float(i)/nsteps)\n sys.stdout.write(\"\\r[{0}{1}]\".format('#' * n, ' ' * (width - n)))\n\nsys.stdout.write(\"\\n\")\n\nsamples = sampler.chain.reshape((-1, ndim))\n\na1, a2, a3 = map(lambda x: (x[1], x[2]-x[1], x[1]-x[0]), zip(*np.percentile(samples, [16, 50, 84], axis=0)))\nprint(a1,a2,a3)\n\npos2 = []\nfor i in range(nwalkers):\n a = np.random.uniform(a1[0]-5*a1[1], a1[0]+5*a1[2])\n b = np.random.uniform(a2[0]-5*a2[1], a2[0]+5*a2[2])\n c = np.random.uniform(a3[0]-5*a3[1], a3[0]+5*a3[2])\n pos2.append(np.asarray([a, b, c]))\n\nsampler2 = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(z_avg, mstar, \n f_gas_m, f_err_m), threads=4)\n\nnsteps = 10000\nwidth = 100\n\nfor i, result in enumerate(sampler2.sample(pos2, iterations=nsteps)):\n n = int((width+1)*float(i)/nsteps)\n sys.stdout.write(\"\\r[{0}{1}]\".format('#'*n,' '*(width-n)))\n\nsys.stdout.write('\\n')\n\nsamples2 = sampler2.chain[:,1000:,:].reshape((-1, ndim))\n#np.save('samples_mcmc_fgas.npy', samples2)\n\nfig2 = corner.corner(samples2, labels=['$\\\\alpha_1$', '$\\\\alpha_2$', '$\\\\alpha_3$'], quantiles=[0.16, 0.50, 0.84], show_titles=True)\n#plt.savefig('corner_plot_fgas.png')\n\naa1, aa2, aa3 = map(lambda x: (x[1], x[2]-x[1], x[1]-x[0]), zip(*np.percentile(samples2, [16, 50, 84], axis=0)))\n#np.save('fit_mcmc_fgas.npy', np.array([aa1,aa2,aa3]))\n\nprint(aa1, '\\n', aa2, '\\n', aa3, '\\n')\n\n","sub_path":"codes/mcmc_fit_fgas.py","file_name":"mcmc_fit_fgas.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"388048041","text":"#4- Construa um algotítmo que leia 10 valoes inteiros e positivos e:\r\n\r\n#A) Encontre o maior valor\r\n#B) Encontre o menor valor\r\n#C) Calcule a média dos números lidos\r\n\r\nmaior = -999\r\nmenor = 999\r\nsoma = 0\r\n\r\nfor n in range (1,11):\r\n valor = int(input('Informe um valor: '))\r\n if valor > 0:\r\n if valor > maior:\r\n maior = valor\r\n if valor < menor:\r\n menor = valor\r\n soma = soma + valor\r\n else:\r\n valor = int(input('Informe um valor: '))\r\nmedia = soma / 10\r\n\r\nprint('0 maior número é {0}'.format(maior))\r\nprint('O menor valor é {0}'.format(menor))\r\nprint('A média dos números é {0}'.format(media))\r\n","sub_path":"Seção 7 - Comandos de repetição/Exercício 4.py","file_name":"Exercício 4.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"639112964","text":"#!C:/Python37/python3.exe\n\n# lmp3thw - ex7. quik and dirty implementation of find command\n# implements to options: -type f/d and wildcards with */? (but with an error, works wrong when * is the last character in the string)\n# implements only one option: -print\n\nimport os, sys\nimport argparse\nimport fnmatch\n\n### __defs__ ###\n\ndef check_wildcard(filename, pattern):\n \"\"\" checks a filename if it matches the pattern in args.name \"\"\"\n\n if filename.find('\\\\'):\n path_elements = filename.split('\\\\')\n else:\n path_elements = [filename]\n \n if any (fnmatch.fnmatch(path_element, pattern) for path_element in path_elements):\n return True\n\n return False\n\n### __main__() ###\n\nparser = argparse.ArgumentParser(description='lmp3thw ex6: basic find')\nparser.add_argument('start_dir', help='folder to start search, default is .', action='store', default='.')\nparser.add_argument('-type', help='file type (d, f)', default='f')\nparser.add_argument('-name', help='filename or wildcard expression to search', default='*')\nparser.add_argument('-print', help='print matching filenames', action='store_true')\nargs = parser.parse_args()\nprint('debug:'+args.start_dir)\nprint('debug:'+args.type)\nprint('debug:'+args.name) # pattern\nprint('debug:'+str(args.print))\n\ntree = os.walk(args.start_dir)\n\nif args.type == 'd' and args.print:\n for i in tree:\n if check_wildcard(i[0], args.name):\n print(i[0])\nelif args.type == 'f' and args.print:\n for i in tree:\n for file in i[2]:\n if check_wildcard(file, args.name):\n print(i[0]+'\\\\'+file)\n","sub_path":"lmp3thw/pyfind.py","file_name":"pyfind.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"348062684","text":"import tornado.ioloop\nimport tornado.web\n\nimport http.client\nimport time \nimport traceback\n\nimport lightgames\nimport manager\n\n\n# An example response.\nresponse = {\n \"state\": \"success\",\n \"bridges\": {\n \"001788182e78\": {\n \"ip\": \"130.237.228.58:80\",\n \"username\": \"a0e48e11876b8971eb694151aba16ab\",\n \"valid_username\": True,\n \"lights\": 3\n },\n \"001788182c73\": {\n \"ip\": \"130.237.228.213:80\",\n \"username\": \"1c9cdb15142f458731745fe11189ab3\",\n \"valid_username\": True,\n \"lights\": 3\n },\n \"00178811f9c2\": {\n \"ip\": \"130.237.228.161:80\",\n \"username\": \"24f99ac4b92c8af22ea52ec3d6c3e37\",\n \"valid_username\": True,\n \"lights\": 'aoeu'\n }\n }\n}\n\n\ndef update_config(cur_cfg, new_cfg, key):\n if key in new_cfg and cur_cfg[key] != new_cfg[key]:\n cur_cfg[key] = new_cfg[key]\n return True\n return False\n\n\nclass RequestHandler(tornado.web.RequestHandler):\n def get_current_user(self):\n if 'disable_login' in manager.config and manager.config['disable_login']:\n return \"disabled\"\n\n user_json = self.get_secure_cookie(\"user\")\n if user_json:\n return tornado.escape.json_decode(user_json)\n else:\n return None\n\n\nclass ConfigHandler(tornado.web.RequestHandler):\n def get(self):\n self.redirect(\"config/setup\")\n\n\nclass ConfigLoginHandler(tornado.web.RequestHandler):\n def get(self):\n self.render('config_login.html', next=self.get_argument(\"next\", \"/config\"))\n\n def post(self):\n self.set_current_user(\"test\")\n self.redirect(self.get_argument(\"next\"))\n\n def set_current_user(self, user):\n if user:\n print(\"User %s logged in\" % user)\n self.set_secure_cookie(\"user\", tornado.escape.json_encode(user), expires_days=None)\n else:\n self.clear_cookie(\"user\")\n\n\nclass SetupConfigHandler(RequestHandler): \n @tornado.web.authenticated \n def get(self): \n def config(key):\n if key in manager.config:\n return manager.config[key]\n return None\n\n template_vars = {\n 'config': config,\n 'status': self.get_argument(\"status\", \"\"),\n 'message': self.get_argument(\"msg\", \"\")\n }\n self.render(\"config_setup.html\", **template_vars)\n\n @tornado.web.authenticated\n def post(self):\n print('POST', self.request.body)\n\n cfg = {}\n for key,val in self.request.arguments.items():\n cfg[key] = self.get_argument(key)\n\n cfg['lampport'] = int(cfg['lampport'])\n cfg['serverport'] = int(cfg['serverport'])\n\n status = \"message\"\n msg = \"Setup saved\"\n if update_config(manager.config, cfg, 'lampdest') or \\\n update_config(manager.config, cfg, 'lampport'):\n manager.connect_lampserver()\n msg = \"Reconnected to lampserver\"\n\n update_config(manager.config, cfg, 'serverport')\n update_config(manager.config, cfg, 'stream_embedcode')\n\n self.redirect(\"setup?status=%s&msg=%s\" % (status, msg))\n\n\n\nclass BridgeConfigHandler(RequestHandler):\n bridges = None \n @tornado.web.authenticated\n def get(self):\n if BridgeConfigHandler.bridges == None: \n client = http.client.HTTPConnection(\n manager.config['lampdest'], manager.config['lampport']\n )\n print(\"BridgeConfig GET /bridges\")\n client.request(\"GET\", \"/bridges\");\n\n json = client.getresponse().read().decode()\n try:\n response = tornado.escape.json_decode(json)\n except ValueError:\n print(\"ValueError: Did not get json from server when requesting /bridges\")\n print(json) \n self.write(\"

Did not get json from server. Is the IP and port correct? Check the output in console

\")\n else:\n if response['state'] == 'success':\n data = response['bridges']\n print(\"BridgeConfig response:\", data)\n BridgeConfigHandler.bridges = data \n self.render('config_bridges.html', bridges=data)\n else:\n self.write(\"

Unexpected answer from lamp-server.

\")\n self.write(\"

\" + str(response) + \"

\")\n self.write(\"

Expected 'state':'success'

\")\n else: \n self.render('config_bridges.html', bridges=BridgeConfigHandler.bridges) \n\n @tornado.web.authenticated\n def post(self):\n print('POST', self.request.arguments)\n client = http.client.HTTPConnection(\n manager.config['lampdest'], manager.config['lampport']\n )\n headers = {'Content-Type': 'application/json'}\n\n data = self.request.arguments \n if 'identify' in data and 'select' in data:\n request = {'alert': 'select'}\n request = tornado.escape.json_encode(request) \n for mac in data['select']: \n print(\"Identify POST:\", \"/bridges/\"+mac.decode('utf-8')+\"/lights/all\", request) \n client.request(\"POST\", \"/bridges/\"+mac.decode('utf-8')+\"/lights/all\", request, headers)\n time.sleep(1.5) \n\n response = client.getresponse().read().decode() \n print('Identify response:', response) \n\n response = tornado.escape.json_decode(response) \n if response['state'] != 'success': \n print('Error when blinking', mac, response) \n\n elif 'add' in data: \n data['ip'] = data['ip'][0].strip().decode() \n data['username'] = data['username'][0].strip().decode() \n if data['ip'] != '': \n request = {'ip': data['ip']}\n if data['username'] != '': \n request['username'] = data['username'] \n\n print('Add bridge:', request)\n json = tornado.escape.json_encode(request) \n client.request(\"POST\", \"/bridges/add\", json, headers) \n\n response = client.getresponse().read().decode() \n response = tornado.escape.json_decode(response)\n if response['state'] == 'success': \n BridgeConfigHandler.bridges.update(response['bridges']) \n print('Added bridge:', response['bridges']) \n else: \n print(\"ERROR!\", response) \n else: \n print('No IP specified') \n\n elif 'remove' in data and 'select' in data: \n for mac in data['select']: \n print('Remove bridge', mac.decode()) \n client.request(\"DELETE\", \"/bridges/\"+mac.decode(), {}, headers)\n time.sleep(1.5) \n\n response = client.getresponse().read().decode() \n print('Remove response:', response) \n\n response = tornado.escape.json_decode(response) \n if response['state'] == 'success': \n del BridgeConfigHandler.bridges[mac.decode()]\n else: \n print('Could not remove bridge.')\n print(response['errorcode'], response['errormessage']) \n\n # Set bridges to None, to force it to get them in get() \n elif 'refresh' in data: \n BridgeConfigHandler.bridges = None \n\n elif 'search' in data: \n print('Search') \n client.request('GET', '/bridges/search', {}, headers) \n\n response = client.getresponse().read().decode() \n print(response) \n response = tornado.escape.json_decode(response) \n if response['state'] == 'success': \n time.sleep(20) \n client.request('GET', '/bridges/search/result', {}, headers) \n\n response = client.getresponse().read().decode() \n response = tornado.escape.json_decode(response) \n print('BridgeConfig search response', response) \n if response['state'] == 'success': \n BridgeConfigHandler.bridges.update(response['bridges']) \n else: \n print(response['errorcode'], response['errormessage']) \n else: \n print(response['errorcode'], response['errormessage']) \n else: \n print('Unknown request. What did you do?') \n \n self.redirect(\"bridges\")\n\n\nclass GameConfigHandler(RequestHandler):\n @tornado.web.authenticated\n def get(self):\n template_vars = {\n 'config_file': manager.game.config_file,\n 'game_name': manager.config['game_name'],\n 'game_path': tornado.escape.json_encode(manager.config['game_path']),\n 'game_list': lightgames.get_games(manager.config['game_path']),\n 'status': self.get_argument(\"status\", \"\"),\n 'message': self.get_argument(\"msg\", \"\")\n }\n\n template_vars.update(lightgames.Game.template_vars) # Game defaults\n template_vars.update(manager.game.template_vars)\n if 'title' not in template_vars:\n template_vars['title'] = template_vars.get('module_name', \"Untitled game\")\n\n template_vars['vars'] = template_vars;\n self.render('config_game.html', **template_vars)\n\n @tornado.web.authenticated\n def post(self):\n backup = manager.config.copy()\n\n cfg = {}\n for key,val in self.request.arguments.items():\n cfg[key] = self.get_argument(key)\n\n if 'game_path' in cfg:\n cfg['game_path'] = tornado.escape.json_decode(cfg['game_path'])\n\n print(\"Config: %s\" % cfg)\n\n cfg['files'] = self.request.files\n\n load_game = False\n\n if update_config(manager.config, cfg, 'game_name') or \\\n update_config(manager.config, cfg, 'game_path'):\n load_game = True\n\n status = \"message\"\n if load_game:\n print(\"Changing or restarting game\")\n try:\n manager.load_game()\n msg = \"Game changed\"\n except Exception as e:\n manager.config = backup\n msg = \"Loading failed: %s\" % e\n status = \"error\"\n traceback.print_exc()\n else:\n ret = manager.game.set_options(cfg)\n if ret == None:\n msg = \"Settings saved\"\n else:\n status = \"error\"\n msg = ret\n\n self.redirect(\"game?status=%s&msg=%s\" % (status, msg))\n","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":10688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"269651991","text":"import os\nimport sys\n\nsys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))\n\nfrom library.mongo.lib import MongoLib\n\n\nclass DetailModel:\n collection = 'smartcity_temp_school'\n\n def __init__(self, database, logger):\n self.mongo = MongoLib(\n db=database.get('db'),\n host=database.get('host'),\n port=database.get('port')\n )\n self.logger = logger\n\n def get_data(self, bs4=True):\n if bs4:\n return self.mongo.get(self.collection, where={'info_sekolah': None})\n else:\n return self.mongo.get(self.collection, where={'detail_sekolah': None})\n\n def search_data(self, pk, item):\n find = self.mongo.get(self.collection, where={'sekolah_id_enkrip': pk})\n if find.get('count') > 0:\n self.update_data(item, {'sekolah_id_enkrip': pk})\n\n def update_data(self, item, key):\n query = self.mongo.update(self.collection, item, key)\n if query.get('code') == 200:\n self.logger.write_log(self.get_message('success', 'update', key.get('sekolah_id_enkrip')), method='INFO')\n else:\n self.update_data(item, key)\n\n @staticmethod\n def get_message(mode, method, pk):\n result = {\n 'error': lambda x: 'Error {} data : {}'.format(x.get('method'), x.get('pk')),\n 'success': lambda x: 'Success {} data : {}'.format(x.get('method'), x.get('pk'))\n }\n\n return result.get(mode, lambda x: str('Oops key is not found'))({'method': method, 'pk': pk})\n\n","sub_path":"model/detail/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"339515818","text":"import cv2\nimport numpy as np\nimport math\nimport imutils\n\n\nclass HOGDescriptor:\n\n def __init__(self, canny=False):\n self.canny = canny\n pass\n\n def describe(self, image):\n image = cv2.resize(image, (256, 256))\n if self.canny:\n image = cv2.Canny(image, 100, 200)\n winSize = (256, 256)\n blockSize = (64, 64)\n blockStride = (32, 32)\n cellSize = (32, 32)\n nbins = 8\n derivAperture = 1\n winSigma = 4.\n histogramNormType = 0\n L2HysThreshold = 2.0000000000000001e-01\n gammaCorrection = 0\n nlevels = 64\n hog = cv2.HOGDescriptor(winSize, blockSize, blockStride, cellSize, nbins, derivAperture, winSigma,\n histogramNormType, L2HysThreshold, gammaCorrection, nlevels)\n\n # hog = cv2.HOGDescriptor()\n winStride = (16, 16)\n padding = (0, 0)\n locations = ((0, 0), (0, 16), (0, 32))\n # winStride, padding, locations\n hist = hog.compute(image)\n\n return_list = []\n for item in hist:\n return_list.append(abs(float(item[0])))\n return return_list\n\n def name(self):\n return \"HistogramOfOrientedGradients\"\n\n def distance(self, histSketch, histImage):\n d = 0\n skip = 0\n for i in range(len(histSketch)):\n # if skip >0:\n # skip -=1\n # continue\n # if i%9==0:\n # if histSketch[i]==0.0 and histSketch[i+1]==0.0 and histSketch[i+2]==0.0 and histSketch[i+3]==0.0 and histSketch[i+4]==0.0 and histSketch[i+5]==0.0 and histSketch[i+6]==0.0 and histSketch[i+7]==0.0:\n # skip = 7\n # continue\n if (histSketch[i] == 0.0):\n continue\n d += math.pow(histImage[i] - histSketch[i], 2)\n return math.sqrt(d)\n\n def pyramid(self, image, scale=2, minSize=(30, 30)):\n # yield the original image\n yield image\n\n # keep looping over the pyramid\n while True:\n # compute the new dimensions of the image and resize it\n w = int(image.shape[1] / scale)\n image = imutils.resize(image, width=w)\n\n # if the resized image does not meet the supplied minimum\n # size, then stop constructing the pyramid\n if image.shape[0] < minSize[1] or image.shape[1] < minSize[0]:\n break\n\n # yield the next image in the pyramid\n yield image\n\n def sliding_window(self, image, stepSize, windowSize):\n # slide a window across the image\n for y in range(0, image.shape[0], stepSize):\n for x in range(0, image.shape[1], stepSize):\n # yield the current window\n yield (x, y, image[y:y + windowSize[1], x:x + windowSize[0]])","sub_path":"application/artifacts/image_search/hog_descriptor.py","file_name":"hog_descriptor.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"459509814","text":"# %%\n# VScodeで入力をテキストから読み込んで標準入力に渡す\nimport sys\nimport os\nf=open(r'.\\Chapter-1\\C_input.txt', 'r', encoding=\"utf-8\")\n# inputをフルパスで指定\n# win10でファイルを作るとs-jisで保存されるため、読み込みをutf-8へエンコードする必要あり\n# VScodeでinput file開くとutf8になってるんだけど中身は結局s-jisになっているらしい\nsys.stdin=f\n\n#\n# 入力スニペット\n# num = int(input())\n# num_list = [int(item) for item in input().split()]\n# num_list = [input() for _ in range(3)]\n##################################\n# %%\n# 以下ペースト可\nN = int(input())\nnum_list = [int(input()) for _ in range(N)]\nimport math\n\ndef prime_chk(n):\n if 0 < n <= 3:\n return True\n else:\n for i in range(2, int(math.sqrt(n)+1)):\n if n % i == 0:\n return False\n return True\n\nres_list = [i for i in num_list if prime_chk(i)]\nprint(len(res_list))","sub_path":"chapter_1/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"551109449","text":"import os\nimport logging\nimport csv\nfrom datetime import datetime\nfrom common.get_config import get_aws_regions\n\nfrom boto3.dynamodb.conditions import Key\nimport boto3\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\ndef convert_to_csv(items):\n \"\"\"\n Args:\n items: all arns in a region from the DynamoDB query as a list\n returns:\n csv_body: body of the csv file to write out\n \"\"\"\n\n fieldnames = [\"Package\", \"Package Version\", \"Status\", \"Expiry Date\", \"Arn\"]\n\n # sort by package, and then created date (oldest to newest)\n sorted_items = sorted(items, key=lambda i: (i[\"pckg\"].lower(), i[\"crtdDt\"]))\n\n with open(\"/tmp/packages.csv\", \"w\", newline=\"\") as csvfile:\n\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for item in sorted_items:\n\n # convert datetime to human readable\n try:\n if item[\"exDt\"]:\n item[\"exDt\"] = datetime.utcfromtimestamp(item[\"exDt\"]).isoformat()\n except KeyError:\n item[\"exDt\"] = \"\"\n\n csv_item = {\n \"Package\": item[\"pckg\"],\n \"Package Version\": item[\"pckgVrsn\"],\n \"Arn\": item[\"arn\"],\n \"Status\": item[\"dplySts\"],\n \"Expiry Date\": item[\"exDt\"],\n }\n writer.writerow(csv_item)\n\n with open(\"/tmp/packages.csv\", \"r\") as csvfile:\n csv_text = csvfile.read()\n\n return csv_text\n\n\ndef query_table(region, table):\n \"\"\"\n Args:\n table: DynamoDB table object to query\n region: region to query on\n returns:\n items: items returned from the query\n \"\"\"\n\n kwargs = {\n \"IndexName\": \"deployed_in_region\",\n \"KeyConditionExpression\": Key(\"rgn\").eq(region),\n }\n items = []\n\n while True:\n response = table.query(**kwargs)\n items.extend(response[\"Items\"])\n\n try:\n kwargs[\"ExclusiveStartKey\"] = response[\"ExclusiveStartKey\"]\n except KeyError:\n logger.info(\n f\"Reached end of query for {region}, Returning {len(items)} items\"\n )\n break\n\n return items\n\n\ndef main(event, context):\n\n \"\"\"\n Gets layer arns for each region and publish to S3\n \"\"\"\n\n regions = get_aws_regions()\n\n dynamodb = boto3.resource(\"dynamodb\")\n table = dynamodb.Table(os.environ[\"DB_NAME\"])\n bucket = os.environ[\"BUCKET_NAME\"]\n region_deploy = dict()\n\n for region in regions:\n\n items = query_table(table=table, region=region)\n arns = convert_to_csv(items)\n region_deploy[region] = len(items)\n\n logger.info(f\"Uploading to S3 Bucket\")\n client = boto3.client(\"s3\")\n client.put_object(\n Body=arns.encode(\"utf-8\"), Bucket=bucket, Key=f\"arns/{region}.csv\"\n )\n\n return {\"arn_count\": region_deploy}\n","sub_path":"pipeline/Serverless/03_publish/publish_arns.py","file_name":"publish_arns.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"270020484","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.template import loader\nfrom django.http import Http404\nfrom django.urls import reverse\nfrom django.contrib.auth import logout\nfrom django.contrib.sessions.models import Session\nfrom django.utils import timezone\n\nfrom login.models import NewUser, Course, Lesson, Progress, Challenge, ChallengeProgress, CourseLocation\n\nfrom random import shuffle\ndef get_all_logged_in_users():\n # Query all non-expired sessions\n # use timezone.now() instead of datetime.now() in latest versions of Django\n sessions = Session.objects.filter(expire_date__gte=timezone.now())\n uid_list = []\n\n # Build a list of user ids from that query\n for session in sessions:\n data = session.get_decoded()\n uid_list.append(data.get('_auth_user_id', None))\n\n # Query all logged in users based on id list\n return NewUser.objects.filter(id__in=uid_list)\n\n\n\ndef profile(request, username):\n if request.user.is_authenticated:\n context = {\n \"UserName\":request.user.username,\n \"Progress\":Progress.objects.filter(newuser__username=username),\n \"CProgress\":ChallengeProgress.objects.filter(newuser__username=username),\n \"score\": NewUser.objects.get(username=username).score,\n \"picture\": NewUser.objects.get(username=username).picture\n }\n return render(request, 'homepage/profile.html',context)\n else:\n #return HttpResponseRedirect(reverse('login:index'))\n return render(request, 'homepage/logout.html')\n\ndef otherprofile(request, fromWho, toWho):\n context = {\n \"ToWhoName\":toWho,\n \"Progress\":Progress.objects.filter(newuser__username=toWho),\n \"CProgress\":ChallengeProgress.objects.filter(newuser__username=toWho),\n \"FromWhoName\":fromWho\n }\n return render(request, 'homepage/otherprofile.html', context)\n \n\ndef logoutuser(request):\n a = NewUser.objects.get(username = request.user.username)\n a.isOnline = False\n a.save()\n logout(request)\n return HttpResponseRedirect(reverse('login:index'))\n\ndef courseList(request, username):\n whosOnline = get_all_logged_in_users()\n lessonP10 = Progress.objects.filter(is_complete=True)\n challengeP10 = ChallengeProgress.objects.filter(is_complete=True)\n news = []\n for i in lessonP10:\n news.append(i)\n for i in challengeP10:\n news.append(i)\n shuffle(news)\n easy = Course.objects.filter(level=\"easy\")\n medium = Course.objects.filter(level=\"medium\")\n hard = Course.objects.filter(level=\"hard\")\n context = {\n \"User\":request.user,\n \"CourseClass\":Course.objects.all(),\n \"easy\":easy,\n \"medium\":medium,\n \"hard\":hard,\n \"whosOnline\":whosOnline,\n \"picture\": NewUser.objects.get(username=username).picture,\n \"score\": NewUser.objects.get(username=username).score,\n \"news\":news\n }\n return render(request, 'homepage/courselist.html', context )\n \ndef course(request, username, coursename, lessonname):\n CL = CourseLocation.objects.filter(newuser__username=username, course__course_name=coursename)\n l = Lesson.objects.filter(lesson_name=lessonname)\n if len(CL) == 0:\n lesson = Lesson.objects.filter(course__course_name=coursename)[0]\n cl = CourseLocation(newuser=NewUser.objects.get(username=username), course=Course.objects.get(course_name=coursename), islessonornot=True, whichone=lesson.lesson_name)\n cl.save()\n elif CL[0].islessonornot == False and len(l) == 0:\n return HttpResponseRedirect(reverse('homepage:challenge',args=(username,coursename,lessonname,CL[0].whichone)))\n else:\n# cl = CourseLocation.objects.get(newuser__username=username, course__course_name=coursename)\n cl = CL[0]\n if coursename == lessonname:\n lesson = Lesson.objects.get(lesson_name=cl.whichone)\n else:\n lesson = Lesson.objects.get(lesson_name=lessonname)\n cl.whichone = lesson.lesson_name\n cl.islessonornot = True\n cl.save()\n '''\n if coursename == lessonname:\n lesson = Lesson.objects.filter(course__course_name=coursename)[0]\n else:\n lesson = Lesson.objects.get(lesson_name=lessonname)\n '''\n #whosOnline = NewUser.objects.filter(isOnline = True)\n '''\n whosOnline = []\n alluser = NewUser.objects.all()\n for i in alluser:\n if i.username in request.session:\n whosOnline.append(NewUser.objects.get(username = i.username))\n '''\n whosOnline = get_all_logged_in_users()\n\n\n p = Progress.objects.filter(newuser__username=username, lesson__lesson_name=lessonname)\n if len(p) == 0:\n Text = \"\"\n TextNotes = \"\"\n else:\n Text = p[0].progress_until_now\n TextNotes = p[0].notes\n completeprogresses = Progress.objects.filter(newuser__username=username, is_complete=True)\n completeLesson = [i.lesson for i in completeprogresses]\n completeCprogresses = ChallengeProgress.objects.filter(newuser__username=username, is_complete=True)\n completeChallenges = [i.challenge for i in completeCprogresses]\n context = {\"CourseName\": coursename,\n \"User\":request.user,\n \"lessonDetail\":Lesson.objects.filter(course__course_name=coursename),\n \"loadlesson\":lesson,\n \"name\":lesson.lesson_name,\n \"whosOnline\":whosOnline,\n \"isLesson\": \"true\",\n \"Text\":Text,\n \"TextNotes\":TextNotes,\n \"progress\": completeLesson,\n \"cprog\": completeChallenges,\n \"picture\": NewUser.objects.get(username=username).picture,\n \"score\": NewUser.objects.get(username=username).score,\n \"Error\": lesson.error_message\n }\n return render(request, 'homepage/course.html', context)\n\ndef challenge(request, username, coursename, lessonname, challengename):\n challenge = Challenge.objects.get(challenge_name=challengename)\n cl = CourseLocation.objects.get(newuser__username=username, course__course_name=coursename)\n cl.whichone = challenge.challenge_name\n cl.islessonornot = False\n cl.save()\n #whosOnline = NewUser.objects.filter(isOnline = True)\n '''\n whosOnline = []\n alluser = NewUser.objects.all()\n for i in alluser:\n if i.username in request.session:\n whosOnline.append(NewUser.objects.get(username = i.username))\n '''\n whosOnline = get_all_logged_in_users()\n\n \n p = ChallengeProgress.objects.filter(newuser__username=username, challenge__challenge_name=challengename)\n if len(p) == 0:\n Text = \"\"\n TextNotes = \"\"\n else:\n Text = p[0].progress_until_now\n TextNotes = p[0].notes\n \n completeprogresses = Progress.objects.filter(newuser__username=username, is_complete=True)\n completeLesson = [i.lesson for i in completeprogresses]\n completeCprogresses = ChallengeProgress.objects.filter(newuser__username=username, is_complete=True)\n completeChallenges = [i.challenge for i in completeCprogresses]\n context = {\"CourseName\": coursename,\n \"User\":request.user,\n \"lessonDetail\":Lesson.objects.filter(course__course_name=coursename),\n \"loadlesson\":challenge,\n \"name\":challenge.challenge_name,\n \"whosOnline\":whosOnline,\n \"isLesson\": \"false\",\n \"Text\":Text,\n \"TextNotes\":TextNotes,\n \"progress\": completeLesson,\n \"cprog\": completeChallenges,\n \"picture\": NewUser.objects.get(username=username).picture,\n \"score\": NewUser.objects.get(username=username).score,\n \"Error\": challenge.error_message\n }\n return render(request, 'homepage/course.html', context)\n\ndef keepprogress(request, username, lessonname):\n #NewUser.objects.create_user(username=\"OPP\", password=\"123\")\n #isLesson = \"true\"\n if request.POST[\"haha\"] == \"true\":\n a = Progress.objects.filter(newuser__username = username, lesson__lesson_name = lessonname)\n if len(a) == 0:\n p = Progress(newuser=NewUser.objects.get(username=username), lesson=Lesson.objects.get(lesson_name=lessonname), progress_until_now=request.POST[\"inputcode\"])\n p.save()\n else:\n p = Progress.objects.get(newuser__username = username, lesson__lesson_name = lessonname)\n p.progress_until_now = request.POST[\"inputcode\"]\n p.save()\n if request.POST[\"isC\"] == \"true\":\n if p.is_complete == False:\n u = NewUser.objects.get(username=username)\n u.score += p.lesson.point_value\n u.save()\n p.is_complete = True\n p.save()\n return HttpResponse(\"\")\n else:\n #return HttpResponse(\"jlskdjf\")\n a = ChallengeProgress.objects.filter(newuser__username = username, challenge__challenge_name = lessonname)\n #return HttpResponse(\"jlskdjf\")\n if len(a) == 0:\n #return HttpResponse(\"jlskdjf\")\n p = ChallengeProgress(newuser=NewUser.objects.get(username=username), challenge=Challenge.objects.get(challenge_name=lessonname), progress_until_now=request.POST[\"inputcode\"])\n p.save()\n #return HttpResponse(\"jlskdjf\")\n else:\n p = ChallengeProgress.objects.get(newuser__username = username, challenge__challenge_name = lessonname)\n p.progress_until_now = request.POST[\"inputcode\"]\n p.save()\n if request.POST[\"isC\"] == \"true\":\n if p.is_complete == False:\n u = NewUser.objects.get(username=username)\n u.score += p.challenge.point_value\n u.save()\n p.is_complete = True\n p.save()\n return HttpResponse(\"\")\n \n \ndef keepnotes(request, username, lessonname):\n if request.POST[\"haha\"] == \"true\":\n a = Progress.objects.filter(newuser__username = username, lesson__lesson_name = lessonname)\n if len(a) == 0:\n p = Progress(newuser=NewUser.objects.get(username=username), lesson=Lesson.objects.get(lesson_name=lessonname), notes=request.POST[\"notes\"])\n p.save()\n else:\n p = Progress.objects.get(newuser__username = username, lesson__lesson_name = lessonname)\n p.notes=request.POST[\"notes\"]\n p.save()\n return HttpResponse(\"\")\n else:\n a = ChallengeProgress.objects.filter(newuser__username = username, challenge__challenge_name = lessonname)\n if len(a) == 0:\n p = ChallengeProgress(newuser=NewUser.objects.get(username=username), challenge=Challenge.objects.get(challenge_name=lessonname), notes=request.POST[\"notes\"])\n p.save()\n else:\n p = ChallengeProgress.objects.get(newuser__username = username, challenge__challenge_name = lessonname)\n p.notes=request.POST[\"notes\"]\n p.save()\n return HttpResponse(\"\")\n\n\ndef chat(request, fromID, fromName, toID, toName):\n context = {\n \"fromID\": fromID,\n \"fromName\": str(fromName),\n \"toID\": toID,\n \"toName\": toName\n }\n return render(request, 'homepage/chat/fullview.html', context)\n","sub_path":"homepage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"432644002","text":"from app.entities.product import Product\nfrom app.entities import session\nfrom app.exceptions import EntityNotFound, EntityAlreadyExists\nfrom datetime import datetime\n\nclass ProductRepository():\n ''' ProductRepository '''\n\n def __init__(self, session):\n self.session = session\n \n def get_by_id(self, product_id: str) -> Product:\n ''' Return a product or fail '''\n product: Product = self.session.query(Product)\\\n .filter_by(id = product_id)\\\n .first()\n if not product:\n raise EntityNotFound(f'Product {product_id} was not found')\n return product\n \n def get_by_company(self, company_id: str) -> list:\n ''' Return a list of all company products '''\n products: Product = self.session.query(Product)\\\n .filter_by(company_id = company_id)\n return list(products)\n \n def get_all(self) -> list:\n ''' Return a list of all products '''\n products = self.session.query(Product)\n return list(products)\n\n def add(self, company_id, product_id: str, value: float) -> Product:\n ''' Validate if is an existent product. If not, create. '''\n try:\n if self.get_by_id(product_id):\n raise EntityAlreadyExists(f'Product {product_id} already exists')\n except Exception as e:\n if not isinstance(e, EntityNotFound):\n raise e\n\n product = Product(product_id, company_id, value)\n self.session.add(product)\n self.session.commit()\n return product\n \n def delete(self, product: Product):\n ''' Delete product '''\n self.session.delete(product)\n self.session.commit()\n ","sub_path":"app/repositories/product_repository.py","file_name":"product_repository.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"571703841","text":"class Node:\n def __init__(self, x):\n self.left = None\n self.right = None\n self.value = x\n\n\ndef inOrder(root):\n if root:\n return inOrder(root.left), root.value, inOrder(root.right)\n else:\n return []\n\n\ndef preOrder(root):\n if root:\n return root.value, preOrder(root.left), preOrder(root.right)\n else:\n return []\n\n\ndef postOrder(root):\n if root:\n return postOrder(root.left), postOrder(root.right), root.value\n else:\n return []\n\n\n# Given binary tree [3,9,20,null,null,15,7]\n# 3\n# / \\\n# 9 20\n# / \\\n# 15 7\n#\n# [\n# [3],\n# [9,20],\n# [15,7]\n# ]\ndef levelOrder(self, root):\n \"\"\"\n :type root: Node\n :rtype: List[List[int]]\n \"\"\"\n result = []\n\n if not root:\n return result\n\n curr_level = [root]\n while curr_level:\n level_result = []\n next_level = []\n\n for curr in curr_level:\n level_result.append(curr.value)\n if curr.left:\n next_level.append(curr.left)\n if curr.right:\n next_level.append(curr.right)\n\n result.append(level_result)\n curr_level = next_level\n\n return result\n\n\ndef maxDepth(self, root: TreeNode) -> int:\n if root is None:\n return 0\n else:\n return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1\n\n\ndef isSymmetric(self, root: TreeNode) -> bool:\n def isMirror(left, right):\n if left is None or right is None:\n return left == None and right == None\n\n return (\n left.value == right.value\n and isMirror(left.left, right.right)\n and isMirror(left.right, right.left)\n )\n\n return isMirror(root, root)\n\n\ndef hasPathSum(self, root: TreeNode, sum: int) -> bool:\n if root == None:\n return False\n else:\n current = root\n result = []\n result.append(current)\n result.append(current.value)\n\n while result != []:\n pathsum = result.pop()\n current = result.pop()\n\n if not current.left and not current.right:\n if pathsum == sum:\n return True\n\n if current.right:\n r_pathsum = pathsum + current.right.value\n result.append(current.right)\n result.append(r_pathsum)\n\n if current.left:\n l_pathsum = pathsum + current.left.value\n result.append(current.left)\n result.append(l_pathsum)\n\n return False\n","sub_path":"leetcode/traverse_a_tree.py","file_name":"traverse_a_tree.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"143396369","text":"with open(\"百度百科字嵌入\", encoding=\"utf8\") as fr, open(\"char.vocab\", \"w\", encoding=\"utf8\") as fw:\n set0 = set()\n for i, line in enumerate(fr):\n line = line.rstrip().split(\" \")\n if line[0] != \"\":\n fw.write(str(line[0])+\"\\n\")\n if str(line[0]) in set0:\n print(line[0])\n else:\n set0.add(line[0])\n print(len(set0))\nprint(\"finished\")\n","sub_path":"process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"323886271","text":"import math\n#This file contains functions needed for formatting\n\n#this function add the break line\ndef line(size = 81):\n print(''.ljust(size, '='))\n return\n\n#this function will enclose the text in a box\ndef text_box(mytext, size = 81):\n start = 0\n end = size - 4\n no_of_lines = math.ceil(len(mytext)/end)\n line(size)\n for i in range(no_of_lines):\n print('| ' + mytext[start:end].ljust(size - 4, ' ') + ' |')\n start = start + end\n end = end + end\n line(size)\n return\n\n#this function will add the heading\ndef head(mytext, size = 86):\n line(size)\n print('|' + mytext.center(size - 4, ' ') + '|')\n line(size)\n return\n\n#this function will add the heading of a table\ndef table_head(itemNo, left_text, right_text, left_size = 20, right_size = 50):\n size = 5 + left_size + right_size + 7\n line(size)\n print('| ' + itemNo.center(3, ' ') + '| ' + left_text.center(left_size, ' ') + ' | ' + right_text.center(right_size, ' ') + ' |')\n line(size)\n return\n\n#this function will add the contents of the table\ndef table_content(itemNo, left_text, right_text, left_size = 20, right_size = 50):\n size = 5 + left_size + right_size + 7\n print('| ' + itemNo.ljust(3, ' ') + '| ' + left_text.ljust(left_size, ' ') + ' | ' + right_text.ljust(right_size, ' ') + ' |')\n line(size)\n return\n\n\n#this function will print out the welcome window\ndef show_list():\n table_head('No', 'Command', 'Description')\n table_content('1', 'Send Email', 'Can send mails to several receivers')\n table_content('2', 'Weather Update', 'Will display the current weather Report')\n table_content('3', 'List Files', 'Will List files of current Directory')\n table_content('4', 'Date', \"Today's date will be displayed\")\n table_content('5', 'Shutdown', 'The computer will be powered off')\n table_content('6', 'Reboot', 'The computer will restart')\n table_content('7', 'Create File', 'New file will be created in the current folder')\n table_content('8', 'Create Folder', 'New folder will be created in the current folder')\n table_content('9', 'File type', 'The file information will be displayed')\n table_content('10', 'Create User', 'The new user will be created.')\n table_content('11', 'Delete User', 'Deletes the user.')\n table_content('12', 'Current Directory', 'Current working Directory will be displayed')\n table_content('13', 'Create Directory', 'New Directory will be created')\n table_content('14', 'Go Back', 'Move to the previous directory')\n table_content('15', 'Change Directory', 'Move to the specified directory')\n table_content('16', 'Delete file', 'Deletes the specified file')\n table_content('17', 'Delete Directory', 'Deletes the specified directory')\n return\n","sub_path":"formatting.py","file_name":"formatting.py","file_ext":"py","file_size_in_byte":2767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"278236216","text":"from module.protocol.network.messages.NetworkMessage import NetworkMessage\n\n\nclass ExchangeBidHouseBuyMessage(NetworkMessage):\n def __init__(self, buffer_reader, len_type, length, count=None):\n NetworkMessage.__init__(self, buffer_reader, len_type, length, count)\n self.id = 8882\n self.uid = {\"type\": \"uint\", \"value\": \"\"}\n self.qty = {\"type\": \"uint\", \"value\": \"\"}\n self.price = {\"type\": \"Number\", \"value\": \"\"}\n","sub_path":"module/protocol/network/messages/ExchangeBidHouseBuyMessage.py","file_name":"ExchangeBidHouseBuyMessage.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"347319679","text":"\"\"\"\n Module to extract, process and store pipeline settings\n\"\"\"\n\nimport pathlib\n\nimport toml\n\nfrom .datatypes import DataTypes\nfrom .params import ParamsSet\n\n\nCONFIG_FOLDER = pathlib.Path(__file__).parent / \"configs\"\n\n\nclass Config:\n \"\"\"\n Class to extract, process and store pipeline settings\n\n Parameters\n ----------\n config_folder : pathlib.Path\n The path to the folder containing the configuration files\n\n Attributes\n ----------\n datatypes : DataTypes\n The set of supported datatypes\n params_set : ParamsSet\n The dictionary containing process configurations\n \"\"\"\n\n def __init__(self, config_folder: pathlib.Path = CONFIG_FOLDER) -> None:\n datatypes_file = config_folder / \"datatypes.toml\"\n with open(datatypes_file, \"r\") as fid:\n datatypes = DataTypes(toml.load(fid))\n self.datatypes = datatypes\n process_types = [\n \"otu_assignment\",\n \"tax_assignment\",\n \"otu_processing\",\n \"network_inference\",\n ]\n combined_params: dict = {}\n for process_type in process_types:\n fname = config_folder / f\"{process_type}.toml\"\n with open(fname, \"r\") as fid:\n params = toml.load(fid)\n for key, value in params.items():\n combined_params[key] = value\n params_set = ParamsSet(combined_params)\n self._check_io_integrity(params_set)\n self.params_set = params_set\n\n def _check_io_integrity(self, params_set: ParamsSet) -> None:\n \"\"\"\n Verify whether all the datatypes in the params_set are valid\n\n Parameters\n ----------\n params_set : ParamsSet\n The params to be verified\n \"\"\"\n for param in params_set:\n for curr_input in param.input:\n if curr_input.datatype not in self.datatypes:\n raise ValueError(\n f\"Invalid datatype {curr_input.datatype} in input definition\"\n )\n formats = self.datatypes[curr_input.datatype].format\n for curr_format in curr_input.format:\n if curr_format not in formats:\n raise ValueError(\n f\"Unsupported format {curr_format} in input definition\"\n )\n for curr_output in param.output:\n if curr_output.datatype not in self.datatypes:\n raise ValueError(\n f\"Invalid datatype {curr_output.datatype} in output definition\"\n )\n formats = self.datatypes[curr_output.datatype].format\n for curr_format in curr_output.format:\n if curr_format not in formats:\n raise ValueError(\n f\"Unsupported format {curr_format} in output definition\"\n )\n if not curr_output.location:\n raise ValueError(\n f\"Relative location for output {curr_output} must be defined\"\n )\n","sub_path":"micone/config/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"274591236","text":"import os\nimport socket\nimport netifaces\nimport requests\ninterfaces = netifaces.interfaces()\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\ns.connect((\"8.8.8.8\", 80))\n\n\nLOCAL_IP_ADDRESS = None\nMAC_ADDRESS = None\nIP_ADDRESS = s.getsockname()[0]\nprint(s.getsockname()[0])\ns.close()\nPROTOCOL = 'http'\nPORT = \"8080\"\nWEBHOOK_URL = 'http://lk.statpad.ru/webhook/camcorder/'\nWEBHOOK_STORAGE_URL = 'https://storage.statpad.ru/api/download/'\nWEBHOOK_CALLBACK_URL = 'http://' + str(IP_ADDRESS) + ':' + str(PORT) + '/transfer/webhook/'\nTRANSFER_URL = 'http://' + str(IP_ADDRESS) + '/'\nTOKEN = \"393B845FB26A76822CD42F8BEC1DA\"\n\nPUBLIC_PATH = '/home/pi/raspberry-recorder/src/public/'\nCAPTURE_PATH = PUBLIC_PATH + 'capture/'\nVIDEO_EXTENSION = '.mp4'\nTRANSFER = {}\n\nfor index, name in enumerate(interfaces):\n if netifaces.ifaddresses(name):\n data = netifaces.ifaddresses(name)\n\n if netifaces.AF_INET in data:\n inet = data[netifaces.AF_INET]\n\n if name == 'tun0':\n IP_ADDRESS = inet[0]['addr']\n else:\n if netifaces.AF_LINK in data:\n link = data[netifaces.AF_LINK]\n\n if name != 'wlan' and name != 'lo':\n LOCAL_IP_ADDRESS = inet[0]['addr']\n MAC_ADDRESS = link[0]['addr']","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"572784976","text":"import numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import Model\n\nclass MyNN(Model): #神经网络搭建\n def __init__(self, s_dim, a_dim, hidden_nodes1, hidden_nodes2):\n super().__init__()\n self.d1 = tf.keras.layers.Dense(hidden_nodes1, 'relu') # w: [s_dim, hidden_nodes1], b: [hidden_nodes1, ]\n self.d2 = tf.keras.layers.Dense(hidden_nodes2, 'relu')\n self.d3 = tf.keras.layers.Dense(a_dim, None) # Q值不需要激活函数, [-inf, inf]\n self(tf.keras.Input(shape = s_dim)) # 初始化参数 [B, s_dim]\n\n def call(self, s):\n x = self.d1(s)\n x = self.d2(x)\n q = self.d3(x)\n return q # [B, A]\n\nclass DeepQNetwork:\n def __init__(\n self,\n action_dim, #动作纬度\n state_dim, #状态纬度\n epsilon = 0.2, #epislon-greedy\n reward_decay = 0.99, #折扣因子\n memory_size = 100000, #经验池大小\n replace_target_iter = 1000, #目标网络参数更新间隔\n batch_size = 256, #经验池采样批大小\n learning_rate = 0.01 #学习率\n ):\n self.a_dim = action_dim\n self.s_dim = state_dim\n self.epsilon = epsilon\n self.gamma = reward_decay\n self.memory_size = memory_size \n self.memory_counter = 0\n self.memory_now_size = 0\n self.memory = np.zeros((self.memory_size, self.s_dim*2+3)) # s:S, s':S, a:1, r:1, done:1]\n\n #neural network\n self.num_hidden1 = 32\n self.num_hidden2 = 32\n self.q_net = MyNN(self.s_dim, self.a_dim, self.num_hidden1, self.num_hidden2) #online network\n self.q_targt_net = MyNN(self.s_dim, self.a_dim, self.num_hidden1, self.num_hidden2) #target network\n tf.group([t.assign(s) for t, s in zip(self.q_targt_net.weights,self.q_net.weights)]) #使得两个网络参数在一开始保持一致\n self.replace_target_iter = replace_target_iter\n self.train_step_counter = 0\n self.batch_size = batch_size\n self.lr = learning_rate # 不算小\n self.optimizer = tf.keras.optimizers.Adam(self.lr) \n\n #模型保存\n self.ck_point = tf.train.Checkpoint(policy = self.q_net)\n self.saver = tf.train.CheckpointManager(self.ck_point, directory='./models', max_to_keep=5, checkpoint_name='zym_model')\n\n def save_model(self, episode): #用于保存模型\n self.saver.save(checkpoint_number=episode)\n\n def restore_model(self, directory):#用于验证模型\n self.ck_point.restore(tf.train.latest_checkpoint(directory))\n tf.group([t.assign(s) for t, s in zip(self.q_targt_net.weights,self.q_net.weights)]) \n\n def choose_action(self, state):\n s = np.array(state).reshape((1,len(state))) # [B=1, S]\n action_value = self.q_net(s) #得到神经网络的所有输出,即所有动作的价值 # Q=[B=1, A]\n action = np.argmax(action_value) # 1,\n if np.random.uniform() < self.epsilon: #探索\n action = np.random.randint(0, self.a_dim)\n return action\n\n def store_transition(self, s, a, r, done, s_):\n transition = np.hstack((s, a, r, done, s_)) # S, 1, 1, 1\n index = self.memory_counter % self.memory_size\n self.memory[index, :] = transition\n self.memory_now_size = min(self.memory_size, self.memory_now_size+1)\n self.memory_counter += 1\n \n def learn(self):\n if self.train_step_counter % self.replace_target_iter == 0: #target网络参数替换\n tf.group([t.assign(s) for t, s in zip(self.q_targt_net.weights,self.q_net.weights)])\n if self.memory_now_size <= self.batch_size: #如果batch_size大于现有经验\n sample_index = np.arange(self.memory_now_size) #全取\n else:\n sample_index = np.random.choice(self.memory_size, size = self.batch_size) #随机采样经验\n batch_memory = self.memory[sample_index, :]#将采样到的经验放到batch_memory中\n\n mem_s = batch_memory[:, :self.s_dim] #当前状���\n mem_s_= batch_memory[:, -self.s_dim:] #下一个状态\n mem_action = batch_memory[:, self.s_dim].astype(int) #获取到所有动作\n mem_reward = batch_memory[:, self.s_dim + 1] #获取到所有奖励\n mem_done = batch_memory[:, self.s_dim + 2] #获取到所有奖励\n q_loss = self.train(mem_s, mem_s_, mem_action, mem_reward, mem_done)\n\n def train(self, s, s_, a, r, done):\n '''\n s: [B, S]\n s_: [B, S]\n a: [B, ]\n r: [B, ]\n done: [B, ]\n '''\n with tf.GradientTape() as tape:\n q_eval_current = self.q_net(s) #获得当前状态下所有动作的估计值 [B, A]\n mem_action_onehot = tf.one_hot(a, self.a_dim) #对经验池动作处理成one hot [B, ] => [B, A]\n q_eval = tf.reduce_sum(tf.multiply(q_eval_current, mem_action_onehot), axis=1)#计算出估计值q(s,a) [B, A] => [B, ]\n\n q_target_next = self.q_targt_net(s_) #获得下一个状态的所有动作目标值 # [B, A] \n q_target = r + (1 - done) * self.gamma * np.max(q_target_next, axis=1) #计算出target值q(s_,a)=r+gamma*q(s_,a_) [B, ]\n \n td_error = q_eval - q_target #q(s, a) - r + gamma * q(s_, a_)\n q_loss = tf.reduce_mean(tf.square(td_error)) # [B, ] => 1,\n grads = tape.gradient(q_loss, self.q_net.trainable_variables)\n self.optimizer.apply_gradients(zip(grads, self.q_net.trainable_variables))\n self.train_step_counter += 1\n return q_loss","sub_path":"1-DQN/DQN_agent.py","file_name":"DQN_agent.py","file_ext":"py","file_size_in_byte":5622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"479732574","text":"import math\n\nfrom scipy import special\nfrom scipy.optimize import fsolve\nc=3*math.pow(10,8)\nll=[18.26,16.5,17.78,18.54,14.76]\nh=[8.57,7.67,7.55,8.63,6.57]\nf=[2.502,2.635,2.546,2.661,2.925]\nQu=[3941,1955,1978,3707,1997]\nli=[1,4,5,7,'#']\n\nll2=[14.76,15.24,14.58,14.92,14.8]\nh2=[6.57,7.19,5.93,6.39,7.05]\nf2=[2.925,2.833,2.961,2.893,2.917]\ndef get_anotherv(d,L,f0):\n v1=math.pow(0.5*math.pi*d/L,2)\n v2=math.pow(d*math.pi*f0/c,2)\n return math.sqrt(v1-v2)\n\ndef get_v(d,L,f0):\n v1=math.pow(math.pi*d*f0/c,2)\n v2=math.pow(c/(2*f0*L),2)-1\n return math.sqrt(v1*v2)\n\ndef get_u(v):\n def fun_u(i,v):\n u=i[0]\n return u*special.j0(u)*special.k1(v)+v*special.k0(v)*special.j1(u)\n u=fsolve(fun_u,[3],v)[0]\n #print(u,v)\n return u\n\ndef get_Xi(d,L,f0):\n v=get_v(d,L,f0)\n u=get_u(v)\n xi1=math.pow(c,2)/math.pow(math.pi*d*f0,2)\n xi2=v*v+u*u\n return xi1*xi2+1\n\ndef get_Rs(f0):\n return math.sqrt(math.pi*f0*4*math.pi*10**(-14)/5.8)\n\ndef get_W(u,v):\n w1=special.j1(u)/special.k1(v)\n w2=special.k0(v)*special.kn(2,v)-special.k1(v)*special.k1(v)\n w3=special.j1(u)*special.j1(u)-special.j0(u)*special.jv(2,u)\n \n return math.pow(w1,2)*w2/w3\n\n\ndef get_B(L,f0,xi,W,rs):\n b1=math.pow(c/(f0*2*L),3)\n b2=rs*(1+W)/(30*math.pow(math.pi,2)*xi)\n return b1*b2\n\ndef get_A(xi,W):\n return 1+W/xi\n\ndef get_sigma(f0,rs):\n return 0.00825*f0/rs\n\ndef get_delta(d,L,f0,xi,Q):\n v=get_v(d,L,f0)\n u=get_u(v)\n W=get_W(u,v)\n rs=get_Rs(f0)\n delta1=get_A(xi,W)/Q\n delta2=get_B(L,f0,xi,W,rs)/math.sqrt(get_sigma(f0,rs))\n return delta1-delta2\n'''\nfor i in range(len(ll)):\n xi=get_Xi(ll[i]*10**(-3),h[i]*10**(-3),f[i]*10**9)\n delta=get_delta(ll[i]*10**(-3),h[i]*10**(-3),f[i]*10**9,xi,Qu[i])\n print('%s %f %.3e' % (li[i],xi,delta))\n'''\nfor i in range(len(ll2)):\n xi=get_Xi(ll2[i]*10**(-3),h2[i]*10**(-3),f2[i]*10**9)\n delta=get_delta(ll[i]*10**(-3),h[i]*10**(-3),f[i]*10**9,xi,Qu[i])\n print(xi)\n","sub_path":"bishe/Courtney.py","file_name":"Courtney.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"123467753","text":"from flask import Flask, render_template, request, redirect\nfrom replit import db\nimport random\n\n\n\napp = Flask(\n __name__,\n template_folder='templates',\n static_folder='static'\n)\n\n# Index page and Rendering Basic Templates\n@app.route('/', methods = ['GET', 'POST'])\ndef index():\n if request.method == \"POST\":\n id = random.randint(0, 1000)\n title = request.form.get('title')\n db[str(id)] = title\n print(db[str(id)])\n return redirect('https://meet.jit.si/'+db[str(id)])\n return render_template('index.html', obj = db)\n\n\n\nif __name__ == '__main__':\n # Run the Flask app\n app.run(\n\thost='0.0.0.0',\n\tdebug=True,\n\tport=8080\n )\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"304805284","text":"from urllib.error import HTTPError\nimport datetime\nimport html\nimport json\nimport pandas as pd\nimport re\nimport numpy as np\nfrom esios_hook import EsiosHook\nfrom postgres_hook import PostgresEsiosHook\nimport os\n\n\nclass Operator:\n \"\"\"\n Load variables json\n input\n :param vars_folder: folder path of variables file\n :type vars_folder: str\n output:\n :param tables: postgres tables name\n :type tables: list\n :param esios_hk: data about esios hook\n :type esios_hk: dict \n :param ptgs_hook: data about postgres hook\n :type ptgs_hook: dict \n :param script_vars: data about execute script\n :type script_vars: dict\n \"\"\"\n\n def __init__(self,\n vars_folder,\n *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.vars_folder = vars_folder\n\n print(os.getcwd())\n\n def load_variables(self):\n try:\n with open(\"{}/variables.json\".format(self.vars_folder)) as f:\n data = json.load(f)\n tables = data[\"tables\"]\n esios_hk = data[\"esios_hk\"]\n ptgs_hook = data[\"ptgs_hook\"]\n script_vars = data[\"script_vars\"]\n except FileNotFoundError:\n print(\"File Not Found, Check path of variables folder\")\n raise\n except Exception:\n print(\"UnControlled Error\")\n raise\n return tables, esios_hk, ptgs_hook, script_vars\n\n\nclass EsiosOperator:\n \"\"\"\n Get and transformation Esios Api Data\n :param table: table name of postgres database\n :type table: str\n :param token: personal authentication to use esios api\n :type token: str\n :param base_url: url to connect to esios api\n :type: str\n :table: table to load data in postgres database\n \"\"\"\n\n def __init__(self,\n table,\n token,\n base_url,\n *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.table = table\n self.token = token\n self.base_url = base_url\n\n def get_table_description(self, folder):\n \"\"\"\n Get table information to transform name from differents tables\n input\n :param folder: table description path folder\n output\n table_info: information of selected table in json format\n \"\"\"\n\n with open(\"{folder}/{table}.json\".format(folder=folder,\n table=self.table)) as file:\n table_info = json.loads(file.read().encode(\"utf8\"))\n return table_info\n\n def create_description_df(self):\n \"\"\"\n Create description dataframe with description of diferents Dataframes\n output\n df: description indicators dataframe (df)\n \"\"\"\n esios = EsiosHook(self.token, self.base_url)\n result = esios.check_and_run()\n df = pd.DataFrame(data=result[\"indicators\"], columns=[\n \"id\", \"name\", \"description\"])\n df[\"description\"] = df[\"description\"].apply(\n lambda x: re.sub(\"<[(/p)(/b)pb]>\", \"\", html.unescape(x)).replace(\"

\", \"\").replace(\"\", \"\"))\n print(\"Indicators Description Data has been created correctly\")\n return df\n\n def create_indicators_df(self,\n ind_description,\n start_date_esios,\n end_date_esios):\n \"\"\"\n Create dataframe from differents indicators data depending of the table\n input\n :param ind_description: description info from _get_table_description (json)\n :param start_date_esios: start date from wich data is downloaded (format %Y-%m-%dT%H:%M:%S)\n :param end_date_esios: end date until wich data is downloaded (format %Y-%m-%dT%H:%M:%S)\n output\n df: indicators df\n \"\"\"\n esios = EsiosHook(self.token, self.base_url)\n counter = 0\n info_col = []\n for c in ind_description[\"indicadores\"]:\n if counter == 0:\n json1 = esios.check_and_run(\n c[\"esios_id\"], start_date_esios, end_date_esios)\n if not len(json1[\"indicator\"][\"values\"]) == 0:\n df = pd.DataFrame.from_dict(json1[\"indicator\"][\"values\"],\n orient=\"columns\")[\n [\"datetime\", \"geo_id\", \"geo_name\", \"value\"]]\n df[\"datetime\"] = df[\"datetime\"].apply(\n lambda x: datetime.datetime.strptime(x[:19],\n \"%Y-%m-%dT%H:%M:%S\"))\n df = df.rename(columns={\"value\": c[\"postgres_name\"]})\n else:\n counter -= 1\n else:\n json2 = esios.check_and_run(\n c[\"esios_id\"], start_date_esios, end_date_esios)\n if not len(json2[\"indicator\"][\"values\"]) == 0:\n df2 = pd.DataFrame.from_dict(json2[\"indicator\"][\"values\"],\n orient=\"columns\")[\n [\"datetime\", \"geo_id\", \"geo_name\", \"value\"]]\n df2 = df2.rename(columns={\"value\": c[\"postgres_name\"]})\n df2[\"datetime\"] = df2[\"datetime\"].apply(\n lambda x: datetime.datetime.strptime(x[:19],\n \"%Y-%m-%dT%H:%M:%S\"))\n df = pd.merge(\n df, df2,\n on=[\"datetime\", \"geo_id\", \"geo_name\"],\n how=\"outer\")\n else:\n pass\n info_col.append(c[\"postgres_name\"])\n counter += 1\n try:\n return df, info_col\n except UnboundLocalError:\n return None\n\n @staticmethod\n def missing_control_df(df, info_col):\n \"\"\"\n Check if existing missing values and replace by 0\n input\n :param df: indicators df\n :type df: Pandas Dataframe\n :param info_col: list of indicators to ingest\n :type info_col: list\n output\n :param df: indicators df\n :type df: df\n \"\"\"\n df.replace(to_replace=[None], value=0, inplace=True)\n df_columns = list(df.columns)\n for c in info_col:\n if c not in df_columns:\n print(\"There is not data if field {}, se completa con ceros\"\n .format(c))\n df[c] = 0\n else:\n pass\n return df\n print(\"There aren't more columns without data\")\n\n @staticmethod\n def date_range(start, end):\n \"\"\"\n Create list of time intervals\n input\n :start: start date from wich data is downloaded (format %Y-%m-%dT%H:%M:%S)\n :end: end date until wich data is downloaded format %Y-%m-%dT%H:%M:%S\n output\n ranges: list of time intervals\n \"\"\"\n ranges = []\n start_dt = datetime.datetime.strptime(start, \"%Y-%m-%dT%H:%M:%S\")\n end_dt = datetime.datetime.strptime(end, \"%Y-%m-%dT%H:%M:%S\")\n load_period = (end_dt - start_dt).days\n if load_period > 60:\n intv = int(np.ceil(load_period / 60))\n diff = (end_dt - start_dt) / intv\n for i in range(intv):\n ranges.append((start_dt + diff * i).strftime(\"%Y-%m-%dT%H:%M:%S\"))\n ranges.append(end_dt.strftime(\"%Y-%m-%dT%H:%M:%S\"))\n ranges_intv = []\n for tm in ranges:\n tm = datetime.datetime.strptime(tm, \"%Y-%m-%dT%H:%M:%S\")\n tm = tm - datetime.timedelta(minutes=tm.minute % 10,\n seconds=tm.second)\n ranges_intv.append(tm.strftime(\"%Y-%m-%dT%H:%M:%S\"))\n return ranges_intv\n else:\n ranges = [start, end]\n return ranges\n\n @staticmethod\n def calculate_columns_df(df, sum_cols, new_col):\n \"\"\"\n Create calculate columns, is the sum of other field\n input\n :param df: indicators df\n :param sum_cols: list of indicators to sum\n :param new_col: name of new column\n output\n df: indicators df\n \"\"\"\n try:\n df[new_col] = df[sum_cols].sum(axis=1)\n except KeyError:\n print(\"Column or columns in the list to sum is not in the df\")\n raise\n except Exception:\n print(\"UnControlled Error\")\n raise\n return df\n\n @staticmethod\n def drop_columns_df(df, drop_cols):\n \"\"\"\n Drop specifics columns\n input\n :param df: indicators df\n :type df: Pandas Dataframe\n :param drop_cols: list of indicators to drop\n :type drop_cols: list\n output\n :param df: indicators df\n :type df: df\n \"\"\"\n try:\n df = df.drop(columns=[drop_cols])\n except KeyError:\n print(\"Some columns in the list to remove is not in df\")\n pass\n except Exception:\n print(\"UnControlled Error\")\n raise\n return df\n\n @staticmethod\n def groupby_time_esios_df(df, time_field, pk_fields, freq=\"60Min\"):\n \"\"\"\n Group data by hours by time and geolocalization\n input\n :param df: indicators df\n :param time_field: name of time field\n :param pk_fields: list of primary key fields\n :param freq\n output\n df: indicators df\n \"\"\"\n group = [pd.Grouper(freq=freq)] + pk_fields\n df = df.set_index(time_field).groupby(group).mean()\n df = df.reset_index()\n return df\n\n\nclass PostgresEsiosOperator:\n \"\"\"\n Interact with Postgres Hook to connect with postgres Database.\n :param login: user of postgres database\n :type login: str\n :param password: password of postgres database\n :type password: str\n :param conn_type: database type\n :type conn_type: str\n :param host: host database server\n :type host: str\n :param schema: database name\n :type schema: str\n :param port: port database server\n :type port: str\n :param table: table name to execute query\n :type table: str\n \"\"\"\n\n def __init__(self,\n table,\n login,\n password,\n conn_type,\n host=\"localhost\",\n schema=\"public\",\n port=None,\n *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.table = table\n self.login = login\n self.password = password\n self.conn_type = conn_type\n self.host = host\n self.schema = schema\n self.port = port\n\n def get_max_timestamp(self, publication):\n \"\"\"\n Get latest timestamp load, and return specif date if table not exist\n input\n :param publication: period of publication\n \"\"\"\n postgres = PostgresEsiosHook(\n self.login,\n self.password,\n self.conn_type,\n self.host,\n self.schema,\n self.port)\n query = ('select * from \"{}\" order by datetime desc limit 1'\n .format(self.table))\n result = postgres.fetchone(query)\n if not result:\n result = \"2015-01-01T00:00:00\"\n else:\n result = postgres.fetchone(query)[0]\n result = datetime.timedelta(minutes=publication) + result\n result = result.strftime(\"%Y-%m-%dT%H:%M:%S\")\n return result\n","sub_path":"module/operators.py","file_name":"operators.py","file_ext":"py","file_size_in_byte":11750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"299540767","text":"\nn = 4\nm = 6\n\nd = [19, 15, 10, 17]\n\n# print(d)\n\n\nd = sorted(d)\n\nprint(d)\n\n\ndef dd_search(d, target, start, end):\n\n if start > end:\n return None\n\n if len(d) == 0:\n return None\n\n mid = (start + end) // 2\n\n dd = []\n for i in range(len(d)):\n if d[i] > d[mid]:\n dd.append(d[i] - d[mid])\n\n print(\"start : {}, end : {}, mid : {}, dd : {}, sum(dd) :{} \".format(start, end, mid, dd, sum))\n\n if sum(dd) >= target:\n print(\"okay\")\n return d[mid]\n\n else:\n return dd_search(d, target, mid+1, end)\n \n \n\nprint(dd_search(d, 6, 0, len(d)-1 ))\n","sub_path":"example_002_sol.py","file_name":"example_002_sol.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"369564795","text":"# Day 1: Fuel Calculator\n# My Solution\n\ndef main():\n file = open(\"day01-input.txt\", \"r\")\n if file.mode == 'r':\n sum = 0\n for line in file:\n sum += calculate(int(line))\n file.close()\n print(sum)\n\ndef calculate(module):\n sum = 0\n fuel = module\n while fuel > 0:\n new_fuel = fuel//3-2\n if new_fuel >= 0:\n sum += new_fuel\n fuel = new_fuel\n return sum\n\nif __name__ == \"__main__\" :\n main()\n","sub_path":"day01-mySolution.py","file_name":"day01-mySolution.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"393042319","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 12 10:19:46 2021\n\n@author: spunlag\n\"\"\"\n\nimport networkx as nx\nimport time\nimport matplotlib.pyplot as plt\nfrom shortestpath_networkx import create_asymmetric_uncertainty_shortest_path_interdiction_nx\nimport random\nimport numpy as np\nfrom pyomo.environ import *\nimport pickle\n\n\ndef get_IR(M,G,R,s,t,vdim,B):\n #Solve the nominal model\n R0={}\n vdim0=0\n M_nom=create_asymmetric_uncertainty_shortest_path_interdiction_nx(G,R0, s,t,vdim0,B)\n opt.solve(M_nom)\n #(paths,length)=return_paths(M_nom,G,R0,s,t)\n #print('Nominal SPI: Path')\n #print(paths)\n #print(length)\n #Solve a model that has the fixed interdictions from the nominal model but adds in robustness\n M_nom_rob=create_asymmetric_uncertainty_shortest_path_interdiction_nx(G,R, s,t,vdim,B)\n M_nom_rob.mods=ConstraintList()\n #print('Nominal SPI: Interdicted Arcs')\n for (i,j) in G.edges:\n if value(M_nom.x[(i,j)]) >= 0.9:\n M_nom_rob.mods.add(M_nom_rob.x[(i,j)]==1)\n #print(f'({i},{j})')\n else:\n M_nom_rob.mods.add(M_nom_rob.x[(i,j)]==0)\n opt.solve(M_nom_rob)\n #M_nom_rob.x.pprint()\n #(paths,length)=return_paths(M_nom_rob,G,R,s,t)\n #print('Robust Path Given Nominal Interdictions')\n #print(paths)\n #print(length)\n #Make comparisons\n #print(value(M.Obj))\n #print(value(M_nom.Obj))\n #print(value(M_nom_rob.Obj))\n Regret=100*(exp(-value(M.Obj))-exp(-value(M_nom.Obj)))/exp(-value(M.Obj))\n Improvement=100*(exp(-value(M_nom_rob.Obj))-exp(-value(M.Obj)))/exp(-value(M_nom_rob.Obj))\n\n return (Improvement,Regret)\n#%%\nmatrix = np.loadtxt('siouxfalls.txt', usecols=(0,1,3))\n\nProb = {(int(a),int(b)) : c for a,b,c in matrix}\nfor (i,j) in Prob.keys():\n if Prob[(i,j)] ==10:\n Prob[(i,j)] = (0.1,0.05) #p_ij, q_ij \n elif Prob[(i,j)] ==9 :\n Prob[(i,j)] = (0.2, 0.1)\n elif Prob[(i,j)] ==8 : \n Prob[(i,j)] = (0.3,0.15)\n elif Prob[(i,j)] ==7 : \n Prob[(i,j)] = (0.4,0.2)\n elif Prob[(i,j)] ==6 : \n Prob[(i,j)] = (0.5, 0.25)\n elif Prob[(i,j)] ==5 : \n Prob[(i,j)] = (0.6, 0.3)\n elif Prob[(i,j)] ==4 : \n Prob[(i,j)] = (0.7, 0.35)\n elif Prob[(i,j)] ==3 : \n Prob[(i,j)] = (0.8, 0.4)\n elif Prob[(i,j)] ==2 : \n Prob[(i,j)] = (0.9, 0.45) \n else:\n raise Exception('Original Sioux Falls value out of range 2-10')\n\nrandom.seed(a=631996)\n\nG=nx.DiGraph()\n\nfor (i,j) in Prob.keys():\n (p,_)=Prob[(i,j)]\n q=random.uniform(0.25*p, 0.75*p)\n G.add_edge(i,j)\n G[i][j]['length']=-np.log(p)\n G[i][j]['interdicted_length']=-np.log(q)+np.log(p)\n \nvdim=len(G.edges)\n\nBudgets={2,4,6,8}\nr_fracs=list(np.linspace(0.25,1,4))\ns=24\nt=10\n\nfor r_frac in r_fracs:\n R={}\n for (i,j) in set(G.edges):\n r=G[i][j]['interdicted_length']\n k=0\n for (u,v) in set(G.edges):\n if i==u and j==v:\n R[(i,j,k)]=r_frac*r\n else:\n R[(i,j,k)]=0\n k=k+1\n \n for B in Budgets: \n M=create_asymmetric_uncertainty_shortest_path_interdiction_nx(G,R,s,t,vdim,B)\n opt=SolverFactory('gurobi_direct')\n opt.solve(M)\n (Regret_Avoided, Regret)=get_IR(M,G,R,s,t,vdim,B)\n print(f'r_frac={r_frac} and B={B}')\n print(f'Regret Avoided={Regret_Avoided}')\n ","sub_path":"Shortest Path/ParameterRTest.py","file_name":"ParameterRTest.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"577186810","text":"def seperate(numbers, threshhold):\n subThreshold = []\n aboveThreshold = []\n for n in numbers:\n if n < threshhold:\n subThreshold.append(n)\n else:\n aboveThreshold.append(n)\n return subThreshold, aboveThreshold\n\ntest = [3, 4, 6, 7, 8, 4, 2, 1, 5, 7,]\nprint(seperate(test, 5))\n\ndef multiplication_table(n):\n matrise = [[((x+1)*(y+1)) for x in range(0,n)] for y in range(0,n)]\n return matrise \n \nprint(multiplication_table(7))","sub_path":"ITGK/Øving 6/gangetabell og lister.py","file_name":"gangetabell og lister.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"575653770","text":"#!/usr/bin/python\n\"\"\"Simplistic wrappers for locally loaded GEO objects.\n\"\"\"\nimport re\ntry:\n # Python 2.7+\n from collections import OrderedDict\nexcept ImportError:\n # Python <=2.6\n from ordereddict import OrderedDict\n \nRX_PLATFORM = re.compile(\"^\\^PLATFORM = (\\w+)\")\nRX_HEADER = re.compile(\"^#([^=]+?) = ?(.*)\")\nRX_ATTR = re.compile(\"^!Platform_([^=]+?) = ?(.*)\")\nHEAD_END_LINE = \"!platform_table_begin\"\nTABLE_END_LINE = \"!platform_table_end\"\n\nclass GPL_Lite(object):\n\n def __init__(self, fp):\n self.cols = OrderedDict()\n self.rows = OrderedDict()\n \n # GPL ID\n self.id = RX_PLATFORM.match(fp.next()).group(1)\n # Column Attribute Descriptions\n for line in fp:\n m = RX_HEADER.match(line)\n if not m: break\n key, value = m.groups()\n self.cols[key] = value\n s = line.strip('\\r\\n')\n assert s == HEAD_END_LINE, \"[%s] != [%s]\" % (s, HEAD_END_LINE)\n # Column titles\n titles = fp.next().strip('\\r\\n').split('\\t')\n assert self.cols.keys() == titles, \"%s != %s\" % (self.cols.keys(), titles)\n # Data rows\n for i, line in enumerate(fp):\n line = line.strip('\\r\\n')\n if line == \"\": continue\n if line == TABLE_END_LINE: break\n row = line.split('\\t')\n self.rows[row[0]] = dict(zip(self.cols.keys(), row))\n self.rows[row[0]]['n'] = i+1\n\n def get_col_list(self, coltitle):\n \"\"\"Return an ordered list of a particular column.\"\"\"\n return [d[coltitle] for d in self.rows.values()]\n \n \n","sub_path":"lite.py","file_name":"lite.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"118278588","text":"# Get the user's email address\r\nemail = input(\"what is your email address?:\").strip()\r\n\r\n# Slice out the user name\r\nusername = email[:email.index(\"@\")]\r\n\r\n# Slice out the domain name\r\ndomain_name = email[email.index(\"@\")+1]\r\n\r\n# Format message\r\nresult = \"Your username is '{}' and your domain name of the email is '{}'\".format(username, domain_name)\r\n\r\n# Display the result message\r\nprint(result)","sub_path":"Email Slicer/email_slicer.py","file_name":"email_slicer.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"496514057","text":"from util import *\n\n\n@apply(simplify=False)\ndef apply(given, wrt=None):\n if wrt is None:\n wrt = given.wrt\n\n assert not wrt.is_given\n domain = given.domain_defined(wrt)\n\n return All[wrt:domain](given)\n\n\n@prove\ndef prove(Eq):\n x = Symbol(real=True)\n Eq << apply(log(x) >= 1 - 1 / x)\n\n Eq << Eq[-1].simplify()\n\n\nif __name__ == '__main__':\n run()\n# created on 2020-05-29\n","sub_path":"axiom/algebra/cond/imply/all/domain_defined.py","file_name":"domain_defined.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"628467735","text":"import asyncio\nimport logging\nfrom typing import Dict, List, Tuple\n\nimport requests\nfrom aiohttp import ClientSession\n\nfrom .parser import Parser\n\nLOG = logging.getLogger('scrapper.macrotrends')\n\n\nclass BaseError(Exception):\n def __init__(self, message: str):\n LOG.exception(message)\n self.message = message\n\n def __str__(self):\n return f'MacrotrendsScrapperError: {self.message}'\n\n\nclass FetchError(BaseError):\n def __init__(self, url: str, error):\n super().__init__(f'failed to fetch {url}: {error}')\n\n\nclass Scrapper:\n def __init__(\n self,\n main_page_url: str = 'https://www.macrotrends.net',\n research_page_postfix: str = '/stocks/research',\n financial_aspect_endpoints: Tuple[str] = ('income-statement', 'balance-sheet', 'cash-flow-statement'),\n price_endpoint: str = 'stock-price-history'\n ):\n self.main_page_url = main_page_url\n self.research_page_postfix = research_page_postfix\n self.financial_aspect_endpoints = financial_aspect_endpoints\n self.price_endpoint = price_endpoint\n self.all_endpoints = financial_aspect_endpoints + (price_endpoint,)\n self.parser = Parser(main_page_url)\n self.beautified_financial_aspects = [self.parser.beautify_field(field) for field in financial_aspect_endpoints]\n\n @staticmethod\n def fetch(url):\n \"\"\"Raise error if cannot fetch data\"\"\"\n try:\n res = requests.get(url)\n except Exception as e:\n raise FetchError(url, e)\n return res.content\n\n @staticmethod\n async def async_fetch(client_session: ClientSession, url: str, raise_for_status: bool = True) -> str:\n \"\"\"Asynchronously perform a get request\n\n :param client_session: aiohttp Client Session\n :param url: fetching url\n :param raise_for_status: raise Error if resposne status is 400 or highger\n :return: response for content\n \"\"\"\n LOG.debug(f'fetching {url}')\n async with client_session.get(url, raise_for_status=raise_for_status) as resp:\n return await resp.text()\n\n def scrap_industry_listing_urls(self) -> Dict:\n \"\"\"Find listing of stocks by industry urls urls by scrapping the research page\n :return: Dictionary of industries and their corresponding urls\n \"\"\"\n research_page_content = self.fetch(self.main_page_url + self.research_page_postfix)\n return self.parser.parse_industry_listing_urls(research_page_content)\n\n def scrap_stocks_data_from_industry_listing(self, industry_listing_page_url: str) -> Dict:\n \"\"\"Find stocks url and profile information by scrapping listing of stock by industry page\n\n :return: Dictionary of stocks ticker and its data\n \"\"\"\n industry_listing_page_content = self.fetch(industry_listing_page_url)\n return self.parser.parse_stocks_data_from_industry_listing_page(industry_listing_page_content)\n\n def create_stock_data_from_parsed_pages(self, parsed_pages: List[Dict]):\n \"\"\"create stock data from parsed financial aspect pages and price page\n\n :param parsed_pages: scrapped page in order of fin aspects + price\n :return:\n \"\"\"\n stock_data = {field: parsed_pages[idx] for idx, field in enumerate(self.beautified_financial_aspects)}\n scrapped_price_data = parsed_pages[-1]\n for field in ['sector', 'industry', 'description']:\n stock_data[field] = scrapped_price_data.pop(field)\n stock_data['price'] = scrapped_price_data['price']\n return stock_data\n\n async def async_scrap_stock_pages(self, client_session: ClientSession, stock_main_page_url: str):\n \"\"\"async fetch and parse stock financial aspect pages and price pages\n\n :param client_session: aiohttp client session\n :param stock_main_page_url: the main page of a stock\n :return: scrapped page\n \"\"\"\n async def scrap_fin_asp_page(aspect: str) -> Dict:\n content = await self.async_fetch(client_session, f'{stock_main_page_url}/{aspect}')\n if isinstance(content, Exception):\n raise FetchError(f'{stock_main_page_url}/{aspect}', content)\n return self.parser.parse_stock_financial_aspect_page(content)\n\n async def scrap_price_page() -> Dict:\n content = await self.async_fetch(client_session, f'{stock_main_page_url}/{self.price_endpoint}')\n if isinstance(content, Exception):\n raise FetchError(f'{stock_main_page_url}/{self.price_endpoint}', content)\n return self.parser.parse_stock_price_data_and_profile_page(content)\n tasks = [scrap_fin_asp_page(asp) for asp in self.financial_aspect_endpoints] + [scrap_price_page()]\n return await asyncio.gather(*tasks, return_exceptions=True)\n\n async def async_scrap_stock_data(self, client_session: ClientSession, stock_main_page_url: str) -> Dict:\n LOG.debug(f'scrapping {stock_main_page_url}')\n scrapped_pages = await self.async_scrap_stock_pages(client_session, stock_main_page_url)\n for page in scrapped_pages:\n if isinstance(page, Exception):\n raise BaseError(f'fail to scrap {stock_main_page_url}: {page}')\n stock_data = self.create_stock_data_from_parsed_pages(scrapped_pages)\n LOG.debug(f'scrapped {stock_main_page_url}')\n return stock_data\n\n async def bound_async_scrap_stock_data(self, semaphore: asyncio.Semaphore, *args):\n \"\"\"bound async fetch with semaphore\n\n :param semaphore:\n :return:\n \"\"\"\n async with semaphore:\n return await self.async_scrap_stock_data(*args)\n\n def scrap_multiple_stocks(self, stock_main_page_urls: List[str], limit: int = 50) -> List[Dict]:\n \"\"\"scrap multiple stocks data\n\n :param stock_main_page_urls: list of stocks main page url\n :param limit: limit concurrency with semaphore\n :return:\n \"\"\"\n async def run():\n async with ClientSession() as session:\n tasks = [self.bound_async_scrap_stock_data(semaphore, session, url) for url in stock_main_page_urls]\n return await asyncio.gather(*tasks, return_exceptions=True)\n\n semaphore = asyncio.Semaphore(limit)\n loop = asyncio.get_event_loop()\n try:\n scrapped_data = loop.run_until_complete(run())\n finally:\n loop.run_until_complete(loop.shutdown_asyncgens())\n loop.close()\n LOG.info(f'scrapped {len(stock_main_page_urls)} stock data')\n return scrapped_data\n\n def scrap_stock_data(self, stock_main_page_url: str):\n \"\"\"Scrap stock data from its url\n\n :param stock_main_page_url: macrotrends stock url\n :return:\n \"\"\"\n\n async def run():\n async with ClientSession(raise_for_status=True) as session:\n return await self.async_scrap_stock_data(session, stock_main_page_url)\n\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n scrapped_data = loop.run_until_complete(run())\n LOG.info(f'scrapped {stock_main_page_url} stock data')\n return scrapped_data\n","sub_path":"stock_picker/scrapper/macrotrends/scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":7220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"502429035","text":"def permute(nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n ret = []\n def helper(saved, remain ):\n #add the finished to ret\n if len(remain) == 0:\n ret.append(saved)\n else:\n for i in range(len(remain)):\n rtemp = remain.copy()\n stemp = saved.copy()\n stemp.append(rtemp.pop(i))\n helper(stemp, rtemp)\n helper([],nums)\n return ret\n\nprint(len(permute([1,2,3,4])))\n","sub_path":"algo_practice/permute.py","file_name":"permute.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"5506541","text":"'''\nXor Dataset Generator : Python 3\nAuthor: Abhishek Munagekar\n'''\nimport random\nimport time\n#Parameters\n\nxor_num = 5\nnos_entry = 10000\n_seed = int(time.time())\n\ndumpfilename='dump.txt'\n\nstring = ['0','1']\nrandom.seed(_seed)\ndump = open(dumpfilename,'w')\ndump.write(str(nos_entry)+\"\\n\")\nfor i in range (nos_entry):\n\t_input = [None]* xor_num\n\t_output = 0\n\tfor j in range(xor_num):\n\t\t_input[j]=random.randint(0,1)\n\t\tdump.write(string[_input[j]]+\"\\t\")\n\t\t_output ^=_input[j]\n\tdump.write(string[_output]+\"\\n\")\ndump.close()\n","sub_path":"xorgen.py","file_name":"xorgen.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"515228390","text":"import tushare as ts\nimport time\n\ncodes = ['002415', '000001', '601988', '600050']\n\nfor count in range(0, 100):\n df_ticks = ts.get_realtime_quotes(codes)\n\n for index in df_ticks.index:\n print(dict(df_ticks.loc[index]), flush=True)\n\n time.sleep(3)\n","sub_path":"xiaoxiang/07.第七课:执行子系统的实现--模拟撮合、实盘接口/第7课代码/simulation/get_ticks.py","file_name":"get_ticks.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"224049625","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/coils/foundation/dbfs1/dbfs1manager.py\n# Compiled at: 2012-10-12 07:02:39\n\n\nclass DBFS1Manager(object):\n \"\"\" The DBFS1Manager supports versions documents and document editing; this is compatible\n with the DB Project in Legacy OpenGroupware\"\"\"\n\n def __init__(self, project_id):\n self._project_id = project_id\n\n def get_path(self, document, version=None):\n path = None\n if version is not None:\n for revision in document.versions:\n if revision.version == version:\n path = ('documents/{0}/{1}/{2}.{3}').format(self._project_id, revision.object_id / 1000 * 1000, revision.object_id, revision.extension)\n\n else:\n path = ('documents/{0}/{1}/{2}.{3}').format(self._project_id, document.object_id / 1000 * 1000, document.object_id, document.extension)\n return path\n\n def create_path(self, document, version):\n folder_path = ('documents/{0}/{1}').format(self._project_id, version.object_id / 1000 * 1000)\n file_name = ('{1}.{2}').format(folder_path, version.object_id, document.extension)\n return (folder_path, file_name)","sub_path":"pycfiles/OpenGroupware-0.1.48-py2.6/dbfs1manager.py","file_name":"dbfs1manager.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"119992066","text":"from PySide2.QtCore import QObject, QRegExp, QSortFilterProxyModel, Qt, SIGNAL, Slot\nfrom PySide2.QtGui import QFont\nfrom datetime import datetime, date\nfrom main_window import MainWindow\nfrom expenseform_window import ExpenseForm\nfrom models.view_models import Models\nfrom database.db import MyDatabase\n\nclass MainController(QObject):\n def __init__(self):\n super().__init__()\n self._view = MainWindow()\n self._expenseForm = None\n self.db = MyDatabase('expenses.db')\n self._models = Models(self.db)\n \n self._view.initializeView(self._models)\n self.connectSignals()\n # self.initializeMainWindow()\n \n @Slot()\n def connectSignals(self):\n #Checks when the Month-Year Combobox Changes \n self._view.dateFilter.currentTextChanged.connect(self.updateTableView)\n self._view.userFilter.currentTextChanged.connect(self.updateTableView)\n self._view.categoryFilter.currentTextChanged.connect(self.updateTableView)\n #Checks when a row in he table is clicked\n self._view.expenseTable.clicked.connect(self.getSelectedRowData)\n #Checks when the ADD EXPENSE button is clicked\n self._view.addExpenseBtn.clicked.connect(self.addNewExpense)\n #Checks when the EDIT and DELETE buttons are pressed\n self._view.editDelegate.clicked.connect(self.openUpdateWindow)\n self._view.deleteDelegate.clicked.connect(self.openDeleteWindow)\n #Checks when the ADD USER button is clicked\n self._view.addUserButton.clicked.connect(self.addNewUser)\n self._view.addCategoryButton.clicked.connect(self.addNewCategory)\n\n\n self._view.valueInput.textChanged[str].connect(self.check_disable)\n self._view.usersDataInput.textChanged[str].connect(self.check_username_isempty)\n self._view.categoryDataInput.textChanged[str].connect(self.check_category_isempty)\n self._view.categoryTypoeDataInput.textChanged[str].connect(self.check_category_isempty)\n self._view.userInput.activated.connect(self.check_disable)\n self._view.categoryInput.activated.connect(self.check_disable)\n\n \n def updateTableView(self):\n self._view.updateTableView(self._models)\n \n def updateDateView(self):\n self._view.updateDateView(self._models)\n \n \n \n @Slot()\n def getSelectedRowData(self, index):\n \n row = index.row()\n expenseList = [self._view.expenseTable.model().index(row, col).data()\n for col in range(self._view.expenseTable.model().columnCount(0))]\n self._view.getSelectedRowData(expenseList)\n self.check_disable()\n \n @Slot()\n def addNewExpense(self): \n \n date = self._view.dateInput.date().toPython() \n value = self._view.valueInput.text()\n categoryIdx = self._view.categoryInput.currentIndex()\n userIdx = self._view.userInput.currentIndex()\n print(\"categoryIdx: \", categoryIdx, \"userIdx: \", userIdx)\n self.db.insertExpenses(value, date, categoryIdx, userIdx)\n self.updateTableView()\n self.updateDateView()\n \n @Slot()\n def openUpdateWindow(self, index):\n row = index.row()\n expenseList = [self._view.expenseTable.model().index(row, col).data()\n for col in range(self._view.expenseTable.model().columnCount(0))]\n if self._expenseForm is None:\n self._expenseForm = ExpenseForm()\n self._expenseForm.openUpdateWindow(expenseList, self._models)\n self._expenseForm.updateExpenseBtn.clicked.connect(self.updateExpense)\n self._expenseForm.c.close.connect(self.deleteForm)\n \n\n def updateExpense(self):\n idx= self._expenseForm.updIndex.text()\n date = self._expenseForm.updDate.date().toPython() \n value = self._expenseForm.updValue.text()\n categoryIdx = self._expenseForm.updCategory.currentIndex()\n userIdx = self._expenseForm.updUser.currentIndex()\n self.db.updateExpense(idx, date, value, categoryIdx, userIdx)\n self.updateTableView()\n self.updateDateView() \n self._expenseForm.close()\n self._expenseForm = None\n\n\n @Slot()\n def openDeleteWindow(self, index):\n row = index.row()\n expenseList = [self._view.expenseTable.model().index(row, col).data()\n for col in range(self._view.expenseTable.model().columnCount(0))]\n if self._expenseForm is None:\n self._expenseForm = ExpenseForm()\n self._expenseForm.openDeleteWindow(expenseList, self._models)\n self._expenseForm.deleteExpenseBtn.clicked.connect(self.deleteExpense)\n self._expenseForm.c.close.connect(self.deleteForm)\n \n @Slot()\n def deleteExpense(self):\n idx= self._expenseForm.updIndex.text()\n # print(index.data(),\"row:\",index.row()) \n self.db.deleteExpense(idx)\n self.updateTableView()\n self.updateDateView()\n self._expenseForm.close() \n self._expenseForm = None\n \n\n def addNewUser(self): \n df = self.db.getAllUsers()\n user = self._view.usersDataInput.text()\n \n exists = user in df['username'].values.tolist()\n if exists:\n self._view.messageLabel.setText('username exists')\n print(f\"username exists?: {exists}\")\n else:\n self.db.insertUsers(user)\n self._view.usersDataTable.setModel(self._models.getUsersModel())\n self._view.messageLabel.setText('')\n\n def addNewCategory(self): \n df = self.db.getAllCategories()\n category = self._view.categoryDataInput.text()\n cattype = self._view.categoryTypoeDataInput.text()\n \n exists = category in df['category_name'].values.tolist()\n if exists:\n self._view.messageLabel.setText('Category already exists')\n else:\n self.db.insertCategories(category, cattype)\n self._view.categoryDataTable.setModel(self._models.getCategoriesTableModel())\n self._view.categoryDataTable.setColumnHidden(0, True)\n self._view.messageLabel.setText('')\n\n \n def deleteForm(self):\n self._expenseForm = None\n \n @Slot()\n def check_disable(self):\n #pass\n if not self._view.valueInput.text() or not self._view.userInput.currentText() or not self._view.categoryInput.currentText():\n self._view.addExpenseBtn.setEnabled(False)\n else:\n self._view.addExpenseBtn.setEnabled(True)\n\n def check_username_isempty(self):\n if not self._view.usersDataInput.text():\n self._view.addUserButton.setEnabled(False)\n else:\n self._view.addUserButton.setEnabled(True)\n \n def check_category_isempty(self):\n if not self._view.categoryDataInput.text() or not self._view.categoryTypoeDataInput.text():\n self._view.addCategoryButton.setEnabled(False)\n else:\n self._view.addCategoryButton.setEnabled(True)\n\n\n ","sub_path":"controllers/main_controller.py","file_name":"main_controller.py","file_ext":"py","file_size_in_byte":7016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"292702226","text":"# Given a string containing just the characters '(', ')', '{', '}', '[' and ']',\n# determine if the input string is valid.\n\n# The brackets must close in the correct order, \"()\" and \"()[]{}\" are all valid\n# but \"(]\" and \"([)]\" are not.\n\nOPEN_PARENS = {'(', '{', '['}\nMATCHING_PARENS = {'(' : ')', '{' : '}', '[' : ']'}\n\nclass Solution(object):\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n st = []\n for p in s:\n if p in OPEN_PARENS:\n st.append(MATCHING_PARENS[p])\n else:\n if len(st) == 0 or p != st.pop():\n return False\n return len(st) == 0\n","sub_path":"valid-parentheses.py","file_name":"valid-parentheses.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"515256043","text":"from django.contrib.auth import get_user_model\nfrom django.urls import reverse\nfrom django.test import TestCase\n\nfrom rest_framework import status\nfrom rest_framework.test import APIClient\n\nfrom core.models import Ingredient\nfrom recipe.serializers import IngredientSerializer\n\nINGREDIENTS_URL = reverse('recipe:ingredient-list')\n\n\nclass PublicIngredientAPITests(TestCase):\n \"\"\"Test the publicly available ingredient API\"\"\"\n\n def setUp(self):\n self.client = APIClient()\n\n def test_login_required(self):\n \"\"\"Test that login is required to access API\"\"\"\n res = self.client.get(INGREDIENTS_URL)\n\n self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)\n\n\nclass PrivateIngredientAPITests(TestCase):\n \"\"\"Test the private ingredient API\"\"\"\n\n def setUp(self):\n self.client = APIClient()\n self.user = get_user_model().objects.create_user(\n email='test@mkznd.com',\n password='password'\n )\n self.client.force_authenticate(user=self.user)\n\n def test_get_ingredient_list(self):\n \"\"\"Test retrieving a list of ingredients\"\"\"\n Ingredient.objects.create(user=self.user, name='Kale')\n Ingredient.objects.create(user=self.user, name='Salt')\n res = self.client.get(INGREDIENTS_URL)\n\n ingredients_db = Ingredient.objects.all().order_by('-name')\n serializer = IngredientSerializer(ingredients_db, many=True)\n\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.data, serializer.data)\n\n def test_ingredients_limited_to_user(self):\n \"\"\"Test that only ingredients for authenticated user are returned\"\"\"\n user2 = get_user_model().objects.create_user(\n email='new@mkznd.com',\n password='password'\n )\n ingredient = Ingredient.objects.create(user=self.user, name='Kale')\n Ingredient.objects.create(user=user2, name='Apple')\n\n res = self.client.get(INGREDIENTS_URL)\n\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(len(res.data), 1)\n self.assertEqual(res.data[0]['name'], ingredient.name)\n\n def test_create_ingredient(self):\n \"\"\"Test that ingredient with normal name can be created\"\"\"\n payload = {'name': 'Celery'}\n res = self.client.post(INGREDIENTS_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n exists = Ingredient.objects.filter(\n user=self.user,\n name=payload['name']\n ).exists()\n self.assertTrue(exists)\n\n def test_create_without_name(self):\n \"\"\"Test if creating ingredient without name fails\"\"\"\n payload = {'name': ''}\n res = self.client.post(INGREDIENTS_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)\n exists = Ingredient.objects.filter(\n user=self.user,\n name=payload['name']\n ).exists()\n self.assertFalse(exists)\n\n def test_create_existing_name(self):\n \"\"\"Test if creating existing ingredients fails\"\"\"\n payload = {'name': 'Cabbage'}\n Ingredient.objects.create(user=self.user, name='Cabbage')\n res = self.client.post(INGREDIENTS_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)\n num = len(Ingredient.objects.filter(\n user=self.user,\n name=payload['name']\n ))\n self.assertEqual(num, 1)\n","sub_path":"app/recipe/tests/test_ingredients_api.py","file_name":"test_ingredients_api.py","file_ext":"py","file_size_in_byte":3484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"5599780","text":"#49. Given an array of numbers, find the maximum sum of any contiguous subarray of the array.\n\ndef maxSum(arr):\n curr_max = 0\n i = 0\n while i < len(arr):\n sub_arr = arr[i:len(arr)]\n j = 0\n while j < len(sub_arr):\n if sum(sub_arr[i:(j+1)]) > curr_max:\n curr_max = sum(sub_arr[i:(j+1)])\n j += 1\n i += 1\n return curr_max\n\nprint(maxSum([34, -50, 42, 14, -5, 86]))\nprint(maxSum([-5, -1, -8, -9]))\n","sub_path":"daily_coding_problem/problem49.py","file_name":"problem49.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"473829216","text":"import fileinput\r\nfrom collections import deque\r\n\r\n \r\ndef in_ana(h, digit_str):\r\n \r\n for c in digit_str:\r\n if c not in h:\r\n return False\r\n \r\n if h[c] < digits_h[digit_str][c]:\r\n return False\r\n \r\n return True\r\n \r\ndef extract_ana(h, digit_str):\r\n res = dict(h)\r\n for c in digit_str:\r\n res[c] -= 1\r\n if res[c] == 0:\r\n del res[c]\r\n \r\n return res\r\n \r\ndef find_sub_d(h, digit_str, res = ''):\r\n \r\n if not h:\r\n return res\r\n \r\n for digit_str in digits_l:\r\n while in_ana(h, digit_str):\r\n extract_ana(h, digit_str)\r\n res += d_to_n[digit_str]\r\n return find_sub_d(h, digit_str, res)\r\n\r\n \r\ndef get_h(line):\r\n h = {}\r\n for c in line:\r\n if c not in h:\r\n h[c] = 1\r\n else:\r\n h[c] += 1\r\n\r\n return h\r\n\r\n \r\ndef find_digits(h, s='', d_i = 0):\r\n global digits_l\r\n res = ''\r\n \r\n if not h:\r\n return s\r\n \r\n \r\n for i, digit_str in enumerate(digits_l[d_i:]):\r\n if in_ana(h, digit_str):\r\n h_n = extract_ana(h, digit_str)\r\n #print \"s = \" + str(s)\r\n res += find_digits(h_n, s+d_to_n[digit_str], i+d_i)\r\n \r\n # if h:\r\n # print \"h = \" + str(h)\r\n # print \"res = \" + str(res)\r\n #This case we did not find the right sequence. Need to backtrack. \r\n # i = int(res.pop(0))\r\n # digits_l = digits_l[i+1:]\r\n # print \"digits = \" + str(digits_l)\r\n # h = get_h(line)\r\n # res = []\r\n \r\n #return ''.join(res)\r\n #print \"res = \" + str(res)\r\n return res\r\n \r\ndigits_l = [\"ZERO\", \"ONE\", \"TWO\", \"THREE\", \"FOUR\", \"FIVE\", \"SIX\", \"SEVEN\", \"EIGHT\", \"NINE\"]\r\ndigits_h = {}\r\nfor digit in digits_l:\r\n digits_h[digit] = {}\r\n for c in digit:\r\n if c not in digits_h[digit]:\r\n digits_h[digit][c] = 1\r\n else:\r\n digits_h[digit][c] += 1\r\n \r\nd_to_n = {}\r\nfor i, digit in enumerate(digits_l):\r\n d_to_n[digit] = str(i)\r\n \r\nf = open('workfile', 'w')\r\n\r\nif __name__ == \"__main__\":\r\n \r\n i = 1\r\n f_i = fileinput.input()\r\n tests = f_i.next()\r\n for line in f_i:\r\n #s = map(int, line.split(' '))\r\n res = find_digits(get_h(line.rstrip()))\r\n f.write(\"Case #\" + str(i) + \": \" + str(res) + \"\\n\")\r\n i += 1\r\n \r\n f.close()\r\n f_i.close()","sub_path":"codes/CodeJamCrawler/CJ_16_2/16_2_1_joshg111_a.py","file_name":"16_2_1_joshg111_a.py","file_ext":"py","file_size_in_byte":2483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"632208758","text":"from flask import Flask\nfrom flask import redirect, url_for\n\napp = Flask(__name__)\ndebug = True #TURN THIS OFF WHEN DEBUG OFF\n\n@app.route(\"/\")\ndef main_page():\n user_logged_in = True\n if user_logged_in == True:\n return redirect(url_for(\"dashboard_page\"))\n return render_template('../app/templates/main_page.html')\n\n@app.route(\"/dashboard\")\ndef dashboard_page():\n return \"Hello Dashboard :P\"\n\nif __name__ == \"__main__\":\n if debug:\n app.config.update(\n PROPAGATE_EXCEPTIONS = True\n )\n app.run()\n","sub_path":"backend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"407893802","text":"symbols = ['{', '}', '(', ')', '[', ']', '.', ', ', ';', '|',\n '+', '-', '*', '/', '&', ',', '<', '>', '=', '~']\nkeywords = ['class', 'constructor', 'function',\n 'method', 'field', 'static', 'var', 'int',\n 'char', 'boolean', 'void', 'true', 'false',\n 'null', 'this', 'let', 'do', 'if', 'else',\n 'while', 'return']\n\ndef tokenize(in_jack):\n stripped_jack = strip(in_jack)\n tokens = '\\n'\n token = \"\"\n token_type = \"\"\n\n for item in stripped_jack:\n if token_type == \"Identifier\" and not item.isalnum() and item != \"_\" and token in keywords:\n tokens = tokens + f\" {token} \\n\"\n token_type, token = \"\",\"\"\n if item == '\"' and token_type != \"String\":\n token_type = \"String\"\n elif item == '\"' and token_type == \"String\":\n tokens = tokens + f\" {token} \\n\"\n token_type, token = \"\",\"\"\n elif token_type == \"String\":\n token = token + item \n elif item.isnumeric() and token_type != \"Identifier\":\n token = token + item\n token_type = \"Integer\"\n elif token_type == \"Integer\":\n tokens = tokens + f\" {token} \\n\"\n token_type, token = \"\",\"\"\n elif item.isalnum() or item == \"_\": \n token = token + item\n token_type = \"Identifier\"\n elif token_type == \"Identifier\":\n tokens = tokens + f\" {token} \\n\"\n token_type, token = \"\",\"\"\n sym=\"\" \n if item in symbols:\n if item == '<':\n sym = '<'\n elif item == '>':\n sym = '>'\n elif item == '&':\n sym = '&'\n else: \n sym = item\n tokens = tokens + f\" {sym} \\n\" \n token_type, token= \"\",\"\" \n\n tokens = tokens + ''\n return tokens\n\ndef strip(jack):\n \"\"\"remove white space and comments\"\"\"\n code = \"\"\n comment_block = False\n for i in jack.read().splitlines():\n line = i.strip() # clean whitespace\n if len(line) == 0:\n continue\n elif len(line) > 0 and line[0] == '*' and comment_block:\n continue\n elif len(line) > 0 and not comment_block:\n comment_block = False\n if len(line) > 1 and line[0] == '/' and line[1] == '/':\n continue\n elif len(line) > 1 and line[0] == '/' and line[1] == '*':\n comment_block = True\n else:\n v = filter_comment(line)\n code = code + v + '\\n'\n return code\n\n\ndef filter_comment(line):\n \"\"\"filter comments\"\"\"\n i = line.split('//')\n return i[0].strip()\n","sub_path":"10/Tokenizer.py","file_name":"Tokenizer.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"416257873","text":"from matplotlib import pyplot as plt\nfrom matplotlib.patches import Rectangle\nimport math\nimport numpy as np\n\ndef plot_crossings(found_crossings, real_sources, room_dimensions, mics_locations, calculated_angles):\n\n x_val, y_val = zip(*found_crossings)\n\n fig = plt.figure(\"Crossings visualization\")\n ax = fig.add_subplot(1, 1, 1)\n ax.scatter(x_val, y_val)\n ax.add_patch(Rectangle((0., 0.), room_dimensions[0], room_dimensions[1], fill=None, alpha=1))\n\n for source in real_sources:\n ax.scatter(source[0], source[1], marker=\"P\")\n\n for mic in mics_locations:\n ax.scatter(*zip(mic), marker=\"x\")\n\n # x = np.linspace(0, 1, 10)\n # ax.plot(x, math.tan(295 * math.pi / 180) * (x - mics_locations[0][0]), linestyle=\"--\")\n\n plt.show()","sub_path":"utils/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"464035611","text":"#coding:utf-8\nimport logging\nimport md5\ntry:\n from collections import OrderedDict\nexcept ImportError:\n from ordereddict import OrderedDict\n\nfrom time import time\nfrom django.core.cache import get_cache\n\nlogger = logging.getLogger(__name__)\n\ntry:\n cache = get_cache('memcache')\nexcept ImportError as e:\n logger.warn(u'加载memcache时出错:[%s], 改为内存缓存', e)\n cache = get_cache('default')\n\n\ndef cache_decorator(expiration=3*60):\n def wrapper(func):\n def news(*args, **kwargs):\n unique_str = repr((func, args, kwargs))\n m = md5.new(unique_str)\n key = m.hexdigest()\n value = cache.get(key)\n if value:\n return value\n else:\n value = func(*args, **kwargs)\n cache.set(key, value, expiration)\n return value\n return news\n return wrapper\n\n","sub_path":"blog_garyrong/utils/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"307039290","text":"from apiclient import discovery\nfrom oauth2client import client\nfrom oauth2client import tools\nfrom oauth2client.file import Storage\nimport httplib2\nimport os\nimport json\n\n\n# If modifying these scopes, delete your previously saved credentials\n# at ~/.credentials/appsactivity-python-quickstart.json\nSCOPES = 'https://www.googleapis.com/auth/spreadsheets'\nAPPLICATION_NAME = 'showtime3'\n\n\ncwd = os.getcwd()\ndirlist = os.listdir(cwd)\nfoundpath = False\nfoundfile = False\nfor i in dirlist:\n if 'client_secret_' in i:\n with open(i, 'r') as f:\n client_secret_pathname = f.readline().rstrip()\n foundpath = True\nif foundpath:\n dirlist2 = os.listdir(client_secret_pathname)\n for i in dirlist2:\n if 'client_secret_' in i:\n CLIENT_SECRET_FILE = client_secret_pathname + i\n foundfile = True\nif not foundfile:\n CLIENT_SECRET_FILE = 'client_secret_12345'\n\nfound_sheets = False\nfor i in dirlist2:\n if 'sheet' in i:\n sheetid = i\n found_sheets = True\n\nabssheetid = client_secret_pathname + sheetid\nwith open(abssheetid) as s:\n sheetnames = json.load(s)\n\nmaster_list_sheet = sheetnames['master_list_sheet']\ntester_list_sheet = sheetnames['tester_list_sheet']\n\n\ndef get_credentials():\n \"\"\"Gets valid user credentials from storage.\n\n If nothing has been stored, or if the stored credentials are invalid,\n the OAuth2 flow is completed to obtain the new credentials.\n\n Returns:\n Credentials, the obtained credential.\n \"\"\"\n\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'appsactivity-python-showtime.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n print('Storing credentials to ' + credential_path)\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials\n\n\ndef sheetpull():\n credentials = get_credentials()\n print ('Credential get: ', credentials)\n http = credentials.authorize(httplib2.Http())\n discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'\n 'version=v4')\n service = discovery.build('sheets', 'v4', http=http,\n discoveryServiceUrl=discoveryUrl)\n spreadsheet_id = master_list_sheet\n rangeName = 'A2:C'\n result = service.spreadsheets().values().get \\\n (spreadsheetId=spreadsheet_id, range=rangeName).execute()\n values = result.get('values', [])\n return (values)\n\n\ndef sheetpush(tracks, path):\n credentials = get_credentials()\n http = credentials.authorize(httplib2.Http())\n discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'\n 'version=v4')\n service = discovery.build('sheets', 'v4', http=http,\n discoveryServiceUrl=discoveryUrl)\n if path == 'live':\n spreadsheet_id = master_list_sheet\n sheetname = 'Master List'\n else:\n spreadsheet_id = tester_list_sheet\n sheetname = 'Tester'\n\n range_name = 'Sheet1'\n values = tracks\n body = {\n 'values': values\n }\n value_input_option = 'RAW'\n\n result = list(service.spreadsheets().values()).append(\n spreadsheetId=spreadsheet_id, range=range_name,\n valueInputOption=value_input_option, body=body).execute()\n print(('Pushed songs to {0}'.format(sheetname)))\n\n return (values)\n\ndef sheetquery(month_name, path):\n credentials = get_credentials()\n http = credentials.authorize(httplib2.Http())\n discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'\n 'version=v4')\n service = discovery.build('sheets', 'v4', http=http,\n discoveryServiceUrl=discoveryUrl)\n if path == 'live':\n spreadsheet_id = master_list_sheet\n else:\n spreadsheet_id = tester_list_sheet\n\n rangeName = 'C2:C'\n result = list(service.spreadsheets().values()).get \\\n (spreadsheetId=spreadsheet_id, range=rangeName).execute()\n values = result.get('values', [])\n for i in values:\n if month_name in i:\n return True\n return False\n\nif __name__ == \"__main__\":\n print ('\\n\\n\\n')\n get_credentials()\n a = sheetpull()\n print (len(a))\n","sub_path":"gsheetpull.py","file_name":"gsheetpull.py","file_ext":"py","file_size_in_byte":4734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"44973578","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 9 09:54:04 2020\n@author: sebastian\n\"\"\"\n\ndef product(x):\n total = 1\n for i in x:\n total *= i\n return total\n\nprint(product([4, 5, 5]))\n \n \n\n\n\n","sub_path":"pythonBasics/practiceMakePerfect/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"6822673","text":"# Apurva Badithela\r\n# 5/25/2020\r\n# This file is very similar to online_preliminaries.py except that in the construction of the graph and the winning set, it takes into account the bridge states in which the environment must wait until the system is in a position that it can satisfy the goal.\r\nimport numpy as np\r\nfrom random import randrange\r\nimport importlib\r\nimport pickle\r\nimport os\r\nfrom grid_construct import grid\r\nimport networkx as nx\r\n\r\n# Unsafe set:\r\ndef unsafe(collision_indices):\r\n U = []\r\n for ii in collision_indices:\r\n s = state(ii,ii)\r\n U.extend([\"v1_\"+str(s)])\r\n U.extend([\"v2_\"+str(s)])\r\n return U\r\n# Generate transition system:\r\n# U is the set of sink vertices. These vertices have no outgoing edges\r\n# Bridge states are states of the environment from which the environment must wait until the system has a clear path to its goal. See 10-by-10 grid example. The normal graph construction would limit the winning set of this example to be after the static obstacle wall.\r\n# Now, it'll include both the static wall and the moving obstacle.\r\n# The guard for leaving a bridge state is that the system has a feasible path to reach its own goal.\r\ndef trans_sys(V1, V2, T1, T2, bridge, sink):\r\n GVp = []\r\n GEdges=[]\r\n # First all environment action transitions:\r\n for env_state in range(1,Ne+1):\r\n #If the environment is blocking a path crucial for the agent in order to get across:\r\n if env_state in bridge:\r\n for sys_state in range(1,Ns):\r\n start_state = state(sys_state, env_state)\r\n start_vtx = \"v1_\"+str(start_state)\r\n if start_vtx in sink:\r\n continue\r\n rem_bridge = [b for b in bridge if b != env_state]\r\n dist_sys_bridge = shortest_distance(M, N, static_obs, rem_bridge, sys_state)\r\n dist_env_bridge = shortest_distance(M, N, static_obs, rem_bridge, env_state)\r\n env_closer_to_some_bridge = [1 for ii in range(len(dist_sys_bridge)) if dist_sys_bridge[ii] >= dist_env_bridge[ii]]\r\n if env_closer_to_some_bridge:\r\n end_state = state(sys_state, env_state)\r\n end_vtx = \"v2_\"+str(end_state)\r\n edge = [start_vtx, end_vtx, \"ae\"]\r\n GEdges.append(edge)\r\n else:\r\n for end_env_state in T1[env_state-1]:\r\n end_state = state(sys_state, end_env_state)\r\n end_vtx = \"v2_\"+str(end_state)\r\n edge = [start_vtx, end_vtx, \"ae\"]\r\n GEdges.append(edge)\r\n else:\r\n for end_env_state in T1[env_state-1]:\r\n for sys_state in range(1,Ns):\r\n start_state = state(sys_state, env_state)\r\n start_vtx = \"v1_\"+str(start_state)\r\n if start_vtx in sink:\r\n continue\r\n end_state = state(sys_state, end_env_state)\r\n end_vtx = \"v2_\"+str(end_state)\r\n edge = [start_vtx, end_vtx, \"ae\"]\r\n GEdges.append(edge)\r\n # Now, all system action transitions:\r\n for sys_state in range(1,Ns+1):\r\n for end_sys_state in T2[sys_state-1]:\r\n for env_state in range(1,Ne):\r\n start_state = state(sys_state, env_state)\r\n start_vtx = \"v2_\"+str(start_state)\r\n if start_vtx in sink:\r\n continue\r\n end_state = state(end_sys_state, env_state)\r\n end_vtx = \"v1_\"+str(end_state)\r\n edge = [start_vtx, end_vtx, \"as\"]\r\n GEdges.append(edge)\r\n return GVp, GEdges\r\n\r\n# Function to find the shortest distance in a 10-by-10 grid graph with obstacles in some locations.\r\n# Finding the shortest distance between the starting point start and the bridge locations in bridge...\r\ndef shortest_distance(M, N, static_obs, bridge, start):\r\n G = nx.Graph()\r\n Ns = M*N\r\n Ne = M*N\r\n mov_obs_col = 8\r\n Ns, Ne, env_states, mov_obs_states, T1, T2 = grid(M, N, static_obs, mov_obs_col)\r\n for xs in range(1,Ns+1):\r\n for xs_end in T2[xs-1]:\r\n G.add_edge(xs, xs_end)\r\n dist_to_bridge = []\r\n for b in bridge:\r\n path_b = nx.dijkstra_path(G, start, b)\r\n dist_to_bridge.append(len(path_b))\r\n return dist_to_bridge\r\n\r\n# Generate winning sets for 2 player games:\r\ndef state(sys_loc, env_loc):\r\n return Ne*(sys_loc-1) + env_loc # Zero-index the sys_loc\r\n\r\n# Given number of system and environment transitions:\r\ndef vertices(Ns, Ne):\r\n Vp =[]\r\n V1 = []\r\n V2 = []\r\n for xs in range(1,Ns+1):\r\n for xe in range(1,Ne+1):\r\n s = state(xs, xe)\r\n V1.extend([\"v1_\"+str(s)]) # Environment action vertices\r\n V2.extend([\"v2_\"+str(s)]) # System action vertices\r\n return V1, V2, Vp\r\n \r\n# Main function to synthesize winning sets:\r\n# Returns winning set for n steps\r\n# N: Maximum number of iterations for fixed-point iterations\r\n# Win_ii_n: The entire winning set upto the nth fixed point iteration\r\n# Pre_ii_n: Consists only of the Pre set of states computed at the nth iteration\r\n\r\ndef synt_winning_set(GVp, GEdges, U, W0):\r\n W = [W0] # Winning set with 0 iterations\r\n Pre_cur = W0.copy()\r\n Win_cur = W0.copy()\r\n fixpoint = False\r\n while not fixpoint:\r\n Pre_ii = pre(GVp, GEdges, Pre_cur, U, 1, 0, 1)\r\n Pre_ii_1 = Pre_ii[0].copy()\r\n Pre_ii_2 = Pre_ii[1].copy()\r\n Win_cur_1 = Win_cur[0].copy()\r\n Win_cur_2 = Win_cur[1].copy()\r\n if Pre_ii_1: # If it is not empty\r\n Win_cur_1.extend(Pre_ii_1)\r\n Win_cur_1 = list(dict.fromkeys(Win_cur_1)) # Removes duplicates\r\n if Pre_ii_2: # If it is not empty\r\n Win_cur_2.extend(Pre_ii_2)\r\n Win_cur_2 = list(dict.fromkeys(Win_cur_2)) # Removes duplicates\r\n Win_ii_1 = Win_cur_1.copy()\r\n Win_ii_2 = Win_cur_2.copy()\r\n Win_ii = [Win_ii_1, Win_ii_2]\r\n W.append(Win_ii)\r\n if(Win_cur == Win_ii):\r\n fixpoint = True\r\n Pre_cur = Pre_ii.copy()\r\n Win_cur = Win_ii.copy()\r\n\r\n return W\r\n\r\n# Synthesizing test cases:\r\n# Environment states are the first place of states\r\n# System state is the second place of states\r\ndef synt_winning_set2(GVp, GEdges, U, W0):\r\n W = [W0] # Winning set with 0 iterations\r\n W_env = [W0[0]] # Winning set with environment states\r\n W_sys = [W0[1]] # Winning set with system states\r\n Pre_cur = W0.copy()\r\n Win_cur = W0.copy()\r\n N = 0\r\n fixpoint = False\r\n while not fixpoint:\r\n Pre_ii = pre(GVp, GEdges, Pre_cur, U, 1, 0, 1)\r\n Pre_ii_1 = Pre_ii[0].copy()\r\n Pre_ii_2 = Pre_ii[1].copy()\r\n Win_cur_1 = Win_cur[0].copy()\r\n Win_cur_2 = Win_cur[1].copy()\r\n if Pre_ii_1: # If it is not empty\r\n Win_cur_1.extend(Pre_ii_1)\r\n Win_cur_1 = list(dict.fromkeys(Win_cur_1)) # Removes duplicates\r\n if Pre_ii_2: # If it is not empty\r\n Win_cur_2.extend(Pre_ii_2)\r\n Win_cur_2 = list(dict.fromkeys(Win_cur_2)) # Removes duplicates\r\n\r\n Win_ii_1 = Win_cur_1.copy()\r\n Win_ii_2 = Win_cur_2.copy()\r\n Win_ii = [Win_ii_1, Win_ii_2]\r\n Win_prev = Win_cur.copy()\r\n if(Win_ii_1 != Win_prev[0]):\r\n W_env.append(Win_ii_1)\r\n if(Win_ii_2 != Win_prev[1]):\r\n W_sys.append(Win_ii_2)\r\n if(Win_cur == Win_ii):\r\n fixpoint = True\r\n W.append(Win_ii)\r\n N += 1\r\n Pre_cur = Pre_ii.copy()\r\n Win_cur = Win_ii.copy()\r\n\r\n return W, W_env, W_sys\r\n\r\n# ToDo: Fix the notation of W0 here...\r\n# Defining Predecessor operator for synthesizing winning sets: \r\n# Assume: Player 1 is the environment and Player 2 is the System\r\n# Winning sets would only contain environment action states\r\n# Pre(S):= {x \\in V2| \\forall }\r\n# U: Unsafe set of states\r\n# Qualifier notations: there_exists: 0 and forall: 1\r\ndef pre(GVp, GEdges, W0, U, qual1, qual2, qual3):\r\n if not GVp: # 2-player game winning set\r\n # Simple backward reachability:\r\n env_W0 = W0[0].copy() # First row of W0 has env action nodes in winning set\r\n sys_W0 = W0[1].copy() # Second row of W0 has sys action nodes in winning set\r\n Win1 = [] # Winning set containing environment action states\r\n Win2 = [] # Winning set containing system action states\r\n Win = [] # Winning set containing env winning actions in the first row and sys winning actions in the second row\r\n\r\n # Backward reachability for winning set with environment action state\r\n for env_win in env_W0:\r\n end_node = [row[1] for row in GEdges]\r\n env_win_idx = [ii for ii, x in enumerate(end_node) if x==env_win]\r\n start_node = [row[0] for row in GEdges] # Extracting the first column in G.Edges\r\n env_nbr = [start_node[ii] for ii in env_win_idx]\r\n if env_nbr: # If list is not empty\r\n for env_nbr_elem in env_nbr:\r\n if env_nbr_elem not in U: # Not in unsafe set\r\n Win2.append(env_nbr_elem)\r\n\r\n # Backward reachability for winning set with system action state. All environment actions must lead to a winning state\r\n for sys_win in sys_W0:\r\n end_node = [row[1] for row in GEdges]\r\n potential_sys_win_idx = [ii for ii, x in enumerate(end_node) if x==sys_win]\r\n start_node = [row[0] for row in GEdges] # Extracting the first column in G.Edges \r\n potential_sys_nbr = [start_node[ii] for ii in potential_sys_win_idx]\r\n sys_nbr = []\r\n for potential_nbr in potential_sys_nbr:\r\n if potential_nbr not in U:\r\n potential_nbr_idx = [ii for ii, x in enumerate(start_node) if x==potential_nbr]\r\n potential_nbr_end_node = [end_node[ii] for ii in potential_nbr_idx]\r\n if set(potential_nbr_end_node) <= set(sys_W0):\r\n sys_nbr.extend([potential_nbr])\r\n \r\n Win1.extend(sys_nbr) \r\n Win1 = list(dict.fromkeys(Win1)) # Removes duplicates\r\n Win2 = list(dict.fromkeys(Win2)) # Removes duplicates\r\n Win.append(Win1)\r\n Win.append(Win2)\r\n\r\n else: # Find sure, almost-sure and positive winning sets\r\n Win=[]\r\n return Win\r\n\r\ndef get_state(state):\r\n if state%Ne == 0:\r\n env_state = Ne\r\n sys_state = state/Ne - 1\r\n else:\r\n env_state = state%Ne\r\n sys_state = state//Ne\r\n return env_state, sys_state\r\n\r\n# Retrieve states:\r\ndef retrieve_win_states(W, W_V1, W_V2):\r\n sys_win = []\r\n env_win = []\r\n # Counters to check that the number of environment and system winning vertices are correctly recorded in W_V1 and W_V2\r\n n_sys_win = 0\r\n n_env_win = 0\r\n for ii in range(0,N):\r\n W_ii = W[ii].copy()\r\n env_action_states = W_ii[0].copy()\r\n sys_action_states = W_ii[1].copy()\r\n sys_win_ii = []\r\n env_win_ii = []\r\n for ee in env_action_states:\r\n ee_idx = V1.index(ee)\r\n env_temp_ptr = W_V1[ee_idx] # Temporary pointer to point to the env winning list\r\n if env_temp_ptr[2]==-1: # If there is not a winning set assignment yet, make an assignment\r\n env_temp_ptr[2] = ii\r\n n_env_win += 1\r\n s = int(ee[3:])\r\n [env_st, sys_st] = get_state(s)\r\n env_win_ii.append([env_st, sys_st])\r\n for ss in sys_action_states:\r\n ss_idx = V2.index(ss)\r\n sys_temp_ptr = W_V2[ss_idx] # Temporary pointer to the sys winning list\r\n if sys_temp_ptr[2]==-1:\r\n sys_temp_ptr[2] = ii\r\n n_sys_win += 1\r\n s = int(ss[3:])\r\n [env_st, sys_st] = get_state(s)\r\n sys_win_ii.append([env_st, sys_st])\r\n\r\n # Assertion to check that all winning states have been correctly stored in W_V1 and W_V2:\r\n assert(n_env_win == len(env_action_states))\r\n assert(n_sys_win == len(sys_action_states))\r\n\r\n sys_win.append(sys_win_ii)\r\n env_win.append(env_win_ii)\r\n\r\n assert(len(env_win[N-1]) == n_env_win)\r\n assert(len(sys_win[N-1]) == n_sys_win)\r\n return env_win, sys_win\r\n\r\n# Retrieve states2:\r\n# Same function as above but based on winning sets containing purely environment states and purely system states\r\ndef retrieve_win_states2(W_sys, W_env, W_V1, W_V2):\r\n sys_win = []\r\n env_win = []\r\n # Counters to check that the number of environment and system winning vertices are correctly recorded in W_V1 and W_V2\r\n n_sys_win = 0\r\n n_env_win = 0\r\n # N is the length of the winning set:\r\n for ii in range(0,len(W_env)):\r\n env_action_states = W_env[ii].copy()\r\n env_win_ii = []\r\n for ee in env_action_states:\r\n ee_idx = V1.index(ee)\r\n env_temp_ptr = W_V1[ee_idx] # Temporary pointer to point to the env winning list\r\n if env_temp_ptr[2]==-1: # If there is not a winning set assignment yet, make an assignment\r\n env_temp_ptr[2] = ii\r\n n_env_win += 1\r\n s = int(ee[3:])\r\n [env_st, sys_st] = get_state(s)\r\n env_win_ii.append([env_st, sys_st])\r\n env_win.append(env_win_ii)\r\n\r\n for ii in range(0, len(W_sys)):\r\n sys_action_states = W_sys[ii].copy()\r\n sys_win_ii = []\r\n for ss in sys_action_states:\r\n ss_idx = V2.index(ss)\r\n sys_temp_ptr = W_V2[ss_idx] # Temporary pointer to the sys winning list\r\n if sys_temp_ptr[2]==-1:\r\n sys_temp_ptr[2] = ii\r\n n_sys_win += 1\r\n s = int(ss[3:])\r\n [env_st, sys_st] = get_state(s)\r\n sys_win_ii.append([env_st, sys_st])\r\n sys_win.append(sys_win_ii)\r\n\r\n assert(n_env_win == len(env_action_states))\r\n assert(n_sys_win == len(sys_action_states))\r\n return env_win, sys_win\r\n\r\n# Winning sets : [W0_sys]\r\n# ADDITION on 3/17/20:\r\n# Edge information for test agent\r\n# GEdges are the edges on the game graph\r\n# N: No. of winning sets\r\n# env_win: Env action states in winning sets\r\n# sys_win: Sys action states in winning sets\r\n# Returns edge information for all edges from an environment action state\r\n# Edge weight of 0 for transition leaving winning set, one for staying in the same winning set, and 2 for moving into the next winning set\r\n# ToDo: Make the data sructures more like dictionaries so that they can be easily read. Learn using pandas\r\n\r\ndef edge_info(GEdges, N, sys_win, env_win, W_V1, W_V2):\r\n env_edge_info = [GEdges[ii] for ii in range(len(GEdges)) if GEdges[ii][2]=='ae'] # Env. action states\r\n sys_edge_info = [GEdges[ii] for ii in range(len(GEdges)) if GEdges[ii][2]=='as'] # Sys. action states\r\n # env_edge_info_len = [0 for ii in range(len(env_edge_info))] # Size of each env_edge_info row\r\n # sys_edge_info_len = [0 for ii in range(len(sys_end_info))] # Size of each sys_edge_info row\r\n V1 = [row[0] for row in W_V1] # Winning env action vertices\r\n V2 = [row[0] for row in W_V2] # Winning system action vertices\r\n # Edges with environment as the first state and system as the successor\r\n for env_edge in env_edge_info:\r\n # Finding start and end nodes of the edge:\r\n # Add if successor vertex is in winning sets\r\n assert(len(env_edge)==3)\r\n start = env_edge[0]\r\n succ = env_edge[1]\r\n # Add number of transitions.\r\n # Initially the number of transitions is 0\r\n env_edge.append(0)\r\n start_idx = V1.index(start)\r\n succ_idx = V2.index(succ)\r\n env_win_set = W_V1[start_idx][2]\r\n sys_win_set = W_V2[succ_idx][2]\r\n # If the successor remains in the same winning set, the env edge information records this as 1\r\n if ((sys_win_set>-1) and (env_win_set>-1)):\r\n if(env_win_set > sys_win_set): # Better because you're in the smaller attractor\r\n env_edge.append(2)\r\n elif(env_win_set == sys_win_set):\r\n env_edge.append(1)\r\n else: # Bad because you're in a bigger attractor, need to have a different number than the previous case\r\n env_edge.append(1) # To Do: This needs to change\r\n elif ((sys_win_set>-1) and not (env_win_set>-1)):\r\n env_edge.append(2)\r\n else:\r\n env_edge.append(0) # Action leading outside winning set\r\n # Testing code:\r\n if(len(env_edge)!=5):\r\n #print(env_edge)\r\n assert(len(env_edge)==5)\r\n for sys_edge in sys_edge_info:\r\n assert(len(sys_edge)==3)\r\n # Finding start and end nodes of the edge:\r\n # Add if successor vertex is in winning sets\r\n start = sys_edge[0]\r\n succ = sys_edge[1]\r\n # Add number of transitions.\r\n # Initially the number of transitions is 0\r\n sys_edge.append(0)\r\n start_idx = V2.index(start)\r\n succ_idx = V1.index(succ)\r\n env_win_set = W_V1[succ_idx][2]\r\n sys_win_set = W_V2[start_idx][2]\r\n # If the successor remains in the same winning set, the env edge information records this as 1\r\n if ((sys_win_set>-1) and (env_win_set>-1)):\r\n if(sys_win_set > env_win_set): # Better because you're in the smaller attractor\r\n sys_edge.append(2)\r\n elif(env_win_set == sys_win_set): # Ok because you're in the same attractor\r\n sys_edge.append(1)\r\n else: # Bad because you're in a bigger attractor\r\n sys_edge.append(1) # To Do: This needs to change\r\n elif ((env_win_set>-1) and not (sys_win_set>-1)):\r\n sys_edge.append(2)\r\n else:\r\n sys_edge.append(0) # Action leading outside winning set\r\n # Testing code:\r\n if(len(sys_edge)!=5):\r\n #print(sys_edge)\r\n assert(len(sys_edge) == 5)\r\n return env_edge_info, sys_edge_info\r\n\r\n\r\n# Return edges where v is the starting vertex. The vertex input is in the form of [e,s]\r\n# Player is either the system or the environment\r\n# Returns the edges starting from v and their indices in sys_edge_info\r\ndef edge(v, edge_info, player):\r\n v_edges = []\r\n st = set_state(v, player)\r\n v_edges = [edges for edges in edge_info if edges[0]==st]\r\n v_edges_idx = [ii for ii in range(len(edge_info)) if edge_info[ii][0]==st]\r\n return v_edges, v_edges_idx\r\n\r\n# Input v: vertex containing system and environment information\r\n# player: 'e' or 's' for environment or system\r\n# Output: Returns vertex\r\n\r\ndef set_state(v, player):\r\n x = state(v[1], v[0]) # Feed in the system location and environment location\r\n if(player == 'e'):\r\n st = \"v1_\"+str(x)\r\n elif(player == 's'):\r\n st = \"v2_\"+str(x)\r\n else:\r\n print(\"Error in set_state: Input either 's' (system) or 'e' (environment) for the player variable.\")\r\n st = []\r\n return st\r\n\r\n\r\n# Initialize the main graph game:\r\n### Main components of the file:\r\n# Runner blocker example\r\n\r\n\r\n# Transition system\r\n# Need to manually write transitions\r\n# T1: Transitions of environment\r\n# T2: Transitions of system\r\n# Example 1: 4-by-4 gridworld\r\nex = 4\r\nif ex == 1:\r\n Ns = 16\r\n Ne = 16\r\n V1, V2, Vp = vertices(Ns,Ne)\r\n T1 = [[1], [3,6], [2,7], [4], [5], [2,10], [3,11], [8], [9], [6,14], [7,15], [12], [13], [10,15], [11, 14], [16]] #Environment transitions\r\n T2 = [[1,2,5], [1,2,3,6], [2,3,4,7], [3,4,8], [1,5,6,9], [2,5,6,7,10], [3,6,7,8,11], [4,7,8,12], [5,9,10,13], [6,9,10,11,14], [7,10,11,12,15], [8,11,12,16], [9,13,14], [10,13,14,15], [11,14,15,16], [12,15,16]] # System transitions\r\n Tp = []\r\n # Unsafe set\r\n e_states = [2,3,6,7,10,11,14,15]\r\n collision_indices = e_states # Collision can occur in one of environment states\r\n U = unsafe(collision_indices)\r\n \r\n # Filenames:\r\n fn_GVp = \"GVp_ex1.dat\"\r\n fn_GEdges = \"GEdges_ex1.dat\"\r\n fn_sys_edge_info = \"sys_edge_info_ex1.dat\"\r\n fn_env_edge_info = \"env_edge_info_ex1.dat\"\r\n fn_env_win_set = \"env_win_set_ex1.dat\"\r\n fn_sys_win_set = \"sys_win_set_ex1.dat\"\r\n fn_W_V1 = \"W_V1_ex1.dat\"\r\n fn_W_V2 = \"W_V2_ex1.dat\"\r\n fn_W = \"W_ex1.dat\"\r\n fn_W0 = \"W0_ex1.dat\"\r\n fn_online_test_runs = \"online_test_runs_ex1.dat\"\r\n fn_e_states = \"e_states_ex1.dat\"\r\n\r\n# Example 2: Runner blocker:\r\nelif ex == 2:\r\n Ns = 5\r\n Ne = 5\r\n V1, V2, Vp = vertices(Ns,Ne)\r\n T1 = [[1], [3], [2,4], [3], [5]]\r\n T2 = [[1,2,3,4],[1,2,3,5], [1,2,3,4,5], [1,3,4,5], [2,3,4,5]]\r\n Tp = []\r\n e_states = [2,3,4]\r\n collision_indices = e_states # Collision can occur in one of environment states\r\n U = unsafe(collision_indices)\r\n\r\n # Filenames:\r\n fn_GVp = \"GVp_ex2.dat\"\r\n fn_GEdges = \"GEdges_ex2.dat\"\r\n fn_sys_edge_info = \"sys_edge_info_ex2.dat\"\r\n fn_env_edge_info = \"env_edge_info_ex2.dat\"\r\n fn_env_win_set = \"env_win_set_ex2.dat\"\r\n fn_sys_win_set = \"sys_win_set_ex2.dat\"\r\n fn_W_V1 = \"W_V1_ex2.dat\"\r\n fn_W_V2 = \"W_V2_ex2.dat\"\r\n fn_W = \"W_ex2.dat\"\r\n fn_W0 = \"W0_ex2.dat\"\r\n fn_online_test_runs = \"online_test_runs_ex2.dat\"\r\n fn_e_states = \"e_states_ex2.dat\"\r\n\r\n# 10-by-10 grid without pausing feature and the blocker only \r\nelif ex == 3:\r\n # 10-by-10 grid example. Winning set is confined to after the static boundary \r\n M = 10\r\n N = 10\r\n mov_obs_col = N-2 # 1-indexed\r\n static_obs = []\r\n for ii in range(2, M):\r\n static_obs.append([ii, mov_obs_col-1])\r\n if(ii == 2 or ii == M-1):\r\n static_obs.append([ii, mov_obs_col-2])\r\n\r\n bridge = [] # Not specified. In this example, it would mean that the winning set is only confined to the region region after the obstacle is clear.\r\n Ns, Ne, mov_static_states, e_states, T1, T2 = grid(M, N, static_obs, mov_obs_col) # e_states is the states consisting of the moving obstacle\r\n V1, V2, Vp = vertices(Ns, Ne)\r\n Tp = []\r\n collision_indices = mov_static_states # Collision can occur in one of environment states (both static and moving)\r\n U = unsafe(collision_indices)\r\n\r\n # Filenames:\r\n fn_GVp = \"GVp_ex3.dat\"\r\n fn_GEdges = \"GEdges_ex3.dat\"\r\n fn_sys_edge_info = \"sys_edge_info_ex3.dat\"\r\n fn_env_edge_info = \"env_edge_info_ex3.dat\"\r\n fn_env_win_set = \"env_win_set_ex3.dat\"\r\n fn_sys_win_set = \"sys_win_set_ex3.dat\"\r\n fn_W_V1 = \"W_V1_ex3.dat\"\r\n fn_W_V2 = \"W_V2_ex3.dat\"\r\n fn_W = \"W_ex3.dat\"\r\n fn_W0 = \"W0_ex3.dat\"\r\n fn_online_test_runs = \"online_test_runs_ex3.dat\"\r\n fn_e_states = \"e_states_ex3.dat\"\r\n\r\n# Same as example 3 but the environment pauses at bridge locations.\r\nelif ex == 4:\r\n # 10-by-10 grid example. Winning set is confined to after the static boundary \r\n M = 7\r\n N = 7\r\n mov_obs_col = N-2 # 1-indexed\r\n static_obs = []\r\n for ii in range(2, M):\r\n static_obs.append([ii, mov_obs_col-1])\r\n if ((ii == 2) or (ii == M-1)):\r\n static_obs.append([ii, mov_obs_col-2])\r\n bridge_loc1 = mov_obs_col\r\n bridge_loc2 = (M-1)*N + mov_obs_col\r\n bridge = [bridge_loc1, bridge_loc2]\r\n Ns, Ne, mov_static_states, e_states, T1, T2 = grid(M, N, static_obs, mov_obs_col) # e_states is the states consisting of the moving obstacle\r\n V1, V2, Vp = vertices(Ns, Ne)\r\n Tp = []\r\n collision_indices = mov_static_states # Collision can occur in one of environment states (both static and moving)\r\n U = unsafe(collision_indices)\r\n\r\n # Filenames:\r\n fn_GVp = \"GVp_ex4.dat\"\r\n fn_GEdges = \"GEdges_ex4.dat\"\r\n fn_sys_edge_info = \"sys_edge_info_ex4.dat\"\r\n fn_env_edge_info = \"env_edge_info_ex4.dat\"\r\n fn_env_win_set = \"env_win_set_ex4.dat\"\r\n fn_sys_win_set = \"sys_win_set_ex4.dat\"\r\n fn_W_V1 = \"W_V1_ex4.dat\"\r\n fn_W_V2 = \"W_V2_ex4.dat\"\r\n fn_W = \"W_ex4.dat\"\r\n fn_W0 = \"W0_ex4.dat\"\r\n fn_online_test_runs = \"online_test_runs_ex4.dat\"\r\n fn_e_states = \"e_states_ex4.dat\"\r\nelse:\r\n print(\"Let example be either 1, 2, or 3\")\r\n\r\n# Graph transition\r\nGVp, GEdges = trans_sys(V1, V2, T1, T2, bridge, U)\r\n\r\n# Initial Winning set:\r\nsys_W0 = [] # Winning states from system action states\r\nenv_W0 = [] # Winning states from environment action states\r\n# Goal states of system and environment\r\nenv_goal = e_states\r\nsys_goal = [M*N]\r\nfor env_state in env_goal:\r\n for sys_state in sys_goal:\r\n w0 = state(sys_state, env_state)\r\n sys_W0.extend([\"v2_\"+str(w0)])\r\n env_W0.extend([\"v1_\"+str(w0)])\r\nW0 = [env_W0, sys_W0]\r\n\r\n# No. of winning sets\r\nW = synt_winning_set(GVp, GEdges, U, W0)\r\nN = len(W)\r\n\r\nW, W_env, W_sys = synt_winning_set2(GVp, GEdges, U, W0)\r\n\r\n# Reachability: \r\n# If this is a winning set, it is a winning set only ... \r\n# Create copies of vertices to store their winning set information:\r\n# -1 denotes that the vertex has not yet been designated in a winning set\r\nW_V1 = [[v1, get_state(int(v1[3:])), -1] for v1 in V1] # Env. action states\r\nW_V2 = [[v2, get_state(int(v2[3:])), -1] for v2 in V2] # Sys. action states\r\nW_Vp = [[vp, get_state(int(vp[3:])), -1] for vp in Vp] # Prob. action states\r\n\r\n# env_win, sys_win = retrieve_win_states(W, W_V1, W_V2) # Retrieves winning sets of states in env winning set and system winning set\r\nenv_win, sys_win = retrieve_win_states2(W_sys, W_env, W_V1, W_V2) # Retrieves winning sets of states in env winning set and system winning set\r\n# Finding edge information to then pass into synth_test_strategies:\r\nenv_edge_info, sys_edge_info = edge_info(GEdges, N, sys_win, env_win, W_V1, W_V2)\r\nonline_test_runs = []\r\n\r\n# Save using pickle:\r\n# Saving edge_info, env_win, sys_win, W, W_V1, W_V2, W0, ...\r\n# Perhaps clears all variables:\r\n# os.system('CLS')\r\npickle.dump(GVp, open(fn_GVp,\"wb\"))\r\npickle.dump(GEdges, open(fn_GEdges,\"wb\"))\r\npickle.dump(env_edge_info, open(fn_env_edge_info,\"wb\"))\r\npickle.dump(sys_edge_info, open(fn_sys_edge_info,\"wb\"))\r\npickle.dump(env_win, open(fn_env_win_set,\"wb\"))\r\npickle.dump(sys_win, open(fn_sys_win_set,\"wb\"))\r\npickle.dump(W_V1, open(fn_W_V1,\"wb\"))\r\npickle.dump(W_V2, open(fn_W_V2,\"wb\"))\r\npickle.dump(W, open(fn_W,\"wb\"))\r\npickle.dump(W0, open(fn_W0,\"wb\"))\r\npickle.dump(e_states, open(fn_e_states,\"wb\"))\r\npickle.dump(online_test_runs, open(fn_online_test_runs, \"wb\"))","sub_path":"online_test_preliminaries2.py","file_name":"online_test_preliminaries2.py","file_ext":"py","file_size_in_byte":26397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"600988902","text":"\"\"\"\nSphinx plugins for RapidSMS documentation.\n\"\"\"\n\ntry:\n import json\nexcept ImportError:\n try:\n import simplejson as json\n except ImportError:\n try:\n from django.utils import simplejson as json\n except ImportError:\n json = None\n\nfrom sphinx import addnodes, roles\nfrom sphinx.util.compat import Directive\n\n\ndef setup(app):\n app.add_crossref_type(\n directivename = \"setting\",\n rolename = \"setting\",\n indextemplate = \"pair: %s; setting\",\n )\n app.add_crossref_type(\n directivename = \"templatetag\",\n rolename = \"ttag\",\n indextemplate = \"pair: %s; template tag\"\n )\n app.add_crossref_type(\n directivename = \"templatefilter\",\n rolename = \"tfilter\",\n indextemplate = \"pair: %s; template filter\"\n )\n app.add_crossref_type(\n directivename = \"router\",\n rolename = \"router\",\n indextemplate = \"pair: %s; router\",\n )\n app.add_config_value('rapidsms_next_version', '0.0', True)\n app.add_directive('versionadded', VersionDirective)\n app.add_directive('versionchanged', VersionDirective)\n\n\nclass VersionDirective(Directive):\n has_content = True\n required_arguments = 1\n optional_arguments = 1\n final_argument_whitespace = True\n option_spec = {}\n\n def run(self):\n env = self.state.document.settings.env\n arg0 = self.arguments[0]\n is_nextversion = env.config.rapidsms_next_version == arg0\n ret = []\n node = addnodes.versionmodified()\n ret.append(node)\n if not is_nextversion:\n if len(self.arguments) == 1:\n linktext = 'Please, see the release notes ' % (arg0)\n xrefs = roles.XRefRole()('doc', linktext, linktext,\n self.lineno, self.state)\n node.extend(xrefs[0])\n node['version'] = arg0\n else:\n node['version'] = \"Development version\"\n node['type'] = self.name\n if len(self.arguments) == 2:\n inodes, messages = self.state.inline_text(self.arguments[1],\n self.lineno+1)\n node.extend(inodes)\n if self.content:\n self.state.nested_parse(self.content, self.content_offset,\n node)\n ret = ret + messages\n env.note_versionchange(node['type'], node['version'], node,\n self.lineno)\n return ret\n","sub_path":"docs/_ext/rapidsmsdocs.py","file_name":"rapidsmsdocs.py","file_ext":"py","file_size_in_byte":2569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"583509865","text":"'''\r\nCOSC264 Check Port\r\nLuke McIntyre\r\nRyan Cox\r\n'''\r\n\r\ndef check_ports(ports):\r\n '''Returns true if all given ports are vaild'''\r\n\r\n try:\r\n for port in ports:\r\n if 1024 < int(port) < 64000:\r\n continue\r\n else:\r\n return False\r\n return True\r\n\r\n except ValueError:\r\n return False\r\n ","sub_path":"check_port.py","file_name":"check_port.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"231996653","text":"import logging\nimport random\nimport time\nfrom pycarol import Carol, CDSStaging, Tasks\n\nlogger = logging.getLogger(__name__)\n\n\ndef consolidate_staging(staging_name, connector_name):\n\n login = Carol()\n cds = CDSStaging(login)\n carol_task = Tasks(login)\n task_name = f'Consolidating Staging Table: {staging_name}'\n task_id = cds.consolidate(\n staging_name=staging_name, connector_name=connector_name)\n task_id = task_id['data']['mdmId']\n while carol_task.get_task(task_id).task_status in ['READY', 'RUNNING']:\n # avoid calling task api all the time.\n time.sleep(round(12 + random.random() * 5, 2))\n logger.debug(f'Running {task_name}')\n task_status = carol_task.get_task(task_id).task_status\n if task_status == 'COMPLETED':\n logger.info(f'Task {task_id} for {connector_name}/{task_name} completed.')\n elif task_status in ['FAILED', 'CANCELED']:\n logger.error(f'Something went wrong while processing: {connector_name}/{task_name}')\n raise ValueError(f'Something went wrong while processing: {connector_name}/{task_name}')\n return 'done'\n","sub_path":"app/functions/consolidate.py","file_name":"consolidate.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"525816665","text":"import argparse\nimport copy\n\nfrom settings.app_settings import MAX_PRODUCT_LENGTH\nfrom src.processors.xls_processor import make_table\nfrom src.utils import split_array\n\n\nclass OrderProcessor:\n response = None\n products = dict()\n\n def __init__(self, client, extra_args: argparse.Namespace):\n self.client = client\n self.extra_args = extra_args\n\n def start(self):\n self.response = self.client.search_orders()\n orders = self.make_list_of_orders()\n product_ids = self.prepare_product_request(orders)\n product_ids = split_array(product_ids, MAX_PRODUCT_LENGTH)\n products = []\n for array in product_ids:\n response = self.client.get_products(array).get('items')\n products.extend(response)\n products = self.create_products_dict(products)\n make_table(\n orders,\n products,\n self.extra_args.mult,\n self.extra_args.dim,\n self.extra_args.dtype,\n self.extra_args.dimconv,\n self.extra_args.country_code,\n )\n\n def create_products_dict(self, products):\n return {\n item.get('id'): item\n for item in products\n if item.get('id')\n }\n\n def prepare_product_request(self, orders):\n ids = {str(o.get('productId')) for o in orders}\n return ids\n\n def split_order(self, order):\n orders_result = []\n items = order.pop('items')\n for item in items:\n each_item = copy.deepcopy(order)\n each_item.update(item)\n orders_result.append(each_item)\n return orders_result\n\n def make_list_of_orders(self):\n orders_list = []\n for item in self.response.get('items'):\n orders = self.split_order(item)\n orders_list.extend(orders)\n return orders_list\n","sub_path":"src/processors/order_processor.py","file_name":"order_processor.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"223098491","text":"# %%\n# importing the libraries\n# basic stuff\nimport pandas as pd\nimport numpy as np\nimport math\nimport re\nimport nltk #swiss knife army for nlp\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.stem import WordNetLemmatizer, PorterStemmer\nfrom nltk.stem.snowball import SnowballStemmer \nfrom nltk.corpus import stopwords\nfrom tqdm import tqdm\n# %%\n# regularization \nimport artm\n# sklearn\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.decomposition import LatentDirichletAllocation\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import train_test_split\nfrom pymystem3 import Mystem\n\n# nltk stemmers\nstemmerRu = SnowballStemmer(\"russian\") \nstemmerEn = PorterStemmer()\n\n#%%\n# made data more suitable for json parsing mechanism\n# uploading data\ndf0 = pd.read_json(r'~/BDML/id-psy_posts.json/0_28c5a7ee_id-psy_posts.json')\ndf1 = pd.read_json(r'~/BDML/id-psy_posts.json/1_18f10508_id-psy_posts.json')\ndf2 = pd.read_json(r'~/BDML/id-psy_posts.json/2_8e726921_id-psy_posts.json')\ndf3 = pd.read_json(r'~/BDML/id-psy_posts.json/3_a5e719df_id-psy_posts.json')\n# alternative\ndf = pd.read_csv(r'/Users/apple/BDML/НИР/train.csv')\n# %%\n#union all and dropping empty lines \ndf = pd.concat([df0[['text', 'owner_id']], df1[['text', 'owner_id']], df2[['text', 'owner_id']], df3[['text', 'owner_id']]])\ndf['text'].replace('', np.nan, inplace=True)\ndf.dropna(subset=['text'], inplace=True)\ndf.reset_index(drop=True, inplace=True)\n#%% \n#defining preprocessing function \n\ndef preprocess(sentence):\n sentence=str(sentence)\n sentence = sentence.lower()\n sentence=sentence.replace('{html}',\"\") \n cleanr = re.compile('<.*?>')\n cleantext = re.sub(cleanr, '', sentence)\n rem_url=re.sub(r'http\\S+', '',cleantext)\n rem_num = re.sub('[0-9]+', '', rem_url)\n tokenizer = RegexpTokenizer(r'\\w+')\n tokens = tokenizer.tokenize(rem_num) \n filtered_words = [w for w in tokens if len(w) > 2 if not w in stopwords.words('russian')]\n stem_words=[stemmerRu.stem(w) for w in filtered_words]\n #lemms = [Mystem().lemmatize(str(w)) for w in filtered_words]\n #stem_words=[stemmerEn.stem(w) for w in stem_words]\n return \" \".join(stem_words)\n\n# cleaning text\ndf['clean'] = df['text'].map(lambda s:preprocess(s))\ndf.drop(['text'], axis = 1, inplace = True)\ndf.drop_duplicates(inplace=True)\ndf.index.is_unique\ndf.dropna(subset=['clean'], inplace=True)\ndf.reset_index(drop=True, inplace=True)\n#%%\n# creating the function for transformation to vowpal_wabbit format\n\n\ndef df_to_vw_regression(df, filepath='in.txt', columns=None, target=None, namespace='text'):\n if columns is None:\n columns = df.columns.tolist()\n columns.remove(target)\n\n with open(filepath, 'w') as f:\n for _, row in tqdm(df.iterrows()):\n if namespace:\n f.write('|{0} '.format( namespace))\n else:\n f.write('{0} | '.format(row[target]))\n last_feature = row.index.values[-1]\n for idx, val in row.iteritems():\n if idx not in columns:\n continue\n if isinstance(val, str):\n f.write('{0}'.format(val.replace(' ', ' ').replace(':', ' ')))\n elif isinstance(val, float) or isinstance(val, int):\n if not math.isnan(val):\n f.write('{0}:{1}'.format(idx.replace(' ', ' ').replace(':', ' '), val))\n else:\n continue\n else:\n f.write('{0}'.format(val.replace(' ', ' ').replace(':', ' ')))\n if idx != last_feature:\n f.write(' ')\n f.write('\\n')\n\n\n# changing the type of data created\n\nvw = df_to_vw_regression(df, filepath='/Users/apple/BDML/topic_modeling/TopicModeling/data.txt', target = 'owner_id')\n\n#%%\n# batching data for applying it to our model\nbatch_vectorizer = artm.BatchVectorizer(data_path='/Users/apple/BDML/topic_modeling/TopicModeling/data.txt',\n data_format='vowpal_wabbit',\n collection_name= 'vw',\n target_folder='my_collection_batches')\n\n#batch_vectorizer = artm.BatchVectorizer(data_path='/Users/apple/BDML/topic_modeling/TopicModeling/my_collection_batches',\n# data_format='batches')\n#%%\n# LDA (BigARTM package) Model\n# setting up lda parameters\n\nlda = artm.LDA(num_topics=20,\n alpha=0.001, beta=0.019,\n cache_theta=True,\n num_document_passes=5,\n dictionary=batch_vectorizer.dictionary)\n\n#Phi is the ‘parts-versus-topics’ matrix, and theta is the ‘composites-versus-topics’ matrix\nlda.fit_offline(batch_vectorizer=batch_vectorizer, num_collection_passes=1)\n\n#checking up the parametrs of the matricies\nlda.sparsity_phi_last_value\nlda.sparsity_theta_last_value\nlda.perplexity_last_value\n\n#%%\n\n#top tokens for each class of all the clusters we've got\ntop_tokens = lda.get_top_tokens(num_tokens=10)\nfor i, token_list in enumerate(top_tokens):\n print('Topic #{0}: {1}'.format(i, token_list))\n\nd = pd.DataFrame(top_tokens)\ntop_tokens_vec= d.apply(lambda x: ' '.join(x), axis=1)\n#%%\n\nlda_phi = lda.phi_\nlda_theta = lda.get_theta()\n\n#%% \n# alternaive lda via sklearn\ntf_idf = TfidfVectorizer(stop_words=stopwords.words('russian'), ngram_range = (1, 2), max_df=.25, max_features=5000) \n#count = CountVectorizer(stop_words=stopwords.words('russian'), max_df=.1, max_features=5000) \nX = tf_idf.fit_transform(df['text'].values)\nlda = LatentDirichletAllocation(n_components=25, random_state=123, learning_method='batch', n_jobs = -1, max_iter = 10)\n\n#%%\nX_topics = lda.fit_transform(X)\nn_top_words = 10\nfeature_names = tf_idf.get_feature_names()\n#%%\n# leading topic\nX_topics = pd.DataFrame(X_topics)\nX_topics.reset_index(drop=True, inplace=True)\n\n#%%\n# top tokens\n\nfor topic_idx, topic in enumerate(lda.components_):\n print(\"Topic %d:\" % (topic_idx + 1))\n print(' '.join([feature_names[i]\n for i in topic.argsort()\n [:-n_top_words - 1:-1]]))\n \n#%%\nphi_numbers = pd.DataFrame(lda.components_).transpose()\nf_names = pd.DataFrame(feature_names)\nlda_skl_phi = pd.concat([ f_names, phi_numbers], axis=1)\n#%%\n# concating initial dataset with topics\nmessages_topics = pd.concat([df, X_topics], axis = 1)\n\n# adding leading topic\nmessages_topics['leading_topic'] = X_topics.idxmax(axis=1)\n#%%\nimport markovify\nmt = messages_topics[messages_topics['leading_topic'] == 1]\n\n# simple state markov chain \n\ntext_model = markovify.Text(mt['text'], state_size= 2 )\ntext_model.compile(inplace = True)\nfor i in range(5):\n print(text_model.make_short_sentence(280))\n#%% \n# combining 2 models \n\nmodel_a = markovify.Text(messages_topics[messages_topics['leading_topic'] == 11]['text'], state_size = 2 )\nmodel_b = markovify.Text(messages_topics[messages_topics['leading_topic'] == 7]['text'], state_size= 2)\n\nmodel_combo = markovify.combine([ model_a, model_b ], [ 1.5, 1 ])\nfor i in range(5):\n print(model_combo.make_sentence())\n#%%\n# ARTM (BigARTM package) Model\n\ndictionary = artm.Dictionary()\ndictionary.gather(data_path='/Users/apple/BDML/topic_modeling/TopicModeling/my_collection_batches')\ndictionary.save_text(dictionary_path='/Users/apple/BDML/topic_modeling/TopicModeling/my_collection_batches/my_dictionary.txt')\n\n#%%\n# intial objects creation\nT=40\ntopic_names = ['topic_{}'.format(i) for i in range(T)]\n\nmodel_artm = artm.ARTM(dictionary = dictionary, topic_names= topic_names, cache_theta= True)\nmodel_artm.scores.add(artm.PerplexityScore(name='PerplexityScore',dictionary = dictionary))\nmodel_artm.scores.add(artm.TopTokensScore(name='top_words',num_tokens = 10))\n#model_artm.regularizers.add(artm.SmoothSparsePhiRegularizer(name='sparse_phi_regularizer', tau=-0.7,\n# topic_names=topic_names[:35]))\nmodel_artm.regularizers.add(artm.SmoothSparsePhiRegularizer(name='smooth_phi_regularizer', tau=0.3,\n topic_names=topic_names))#[35:]))\n\n#%%\n# initializing the model we've set up\nmodel_artm.initialize(dictionary)\nmodel_artm.num_document_passes = 3\n#%%\nmodel_artm.fit_offline(batch_vectorizer=batch_vectorizer, num_collection_passes=16)\n\n#%%\nperplexityScore = list(model_artm.score_tracker['PerplexityScore'].value)\n\n#%%\n#%matplotlib inline\nimport glob\nimport os\nimport matplotlib.pyplot as plt\n\n# %%\n# visualizing perplexity\nplt.scatter(range(len(perplexityScore)), perplexityScore)\nplt.xlabel('number of iterations')\nplt.ylabel('perplexity score')\n# %%\ntop_tokens = model_artm.score_tracker['top_words']\nfor topic_name in model_artm.topic_names:\n print ('\\n',topic_name)\n for (token, weight) in zip(top_tokens.last_tokens[topic_name][:40],\n top_tokens.last_weights[topic_name][:40]):\n print (token, '-', weight)\n# %%\n# extraction of phi and theta to enviroment \n#artm_phi = model_artm.get_phi()\nartm_theta = model_artm.get_theta()\n\n# transposing theta\n\ntheta_transposed = artm_theta.transpose()\ntheta_texts = pd.concat([df, theta_transposed], axis = 1)\n# %%\n# aglomerative clustering \nn_clusters = 15\nmodel = AgglomerativeClustering(n_clusters=n_clusters, affinity='euclidean', linkage='ward')\nmodel.fit(theta_transposed)\nlabels = model.labels_\n# %%\ntheta_transposed['labels'] = labels\n#theta_texts['leading_topic'] = theta_transposed.idxmax(axis=1)\ndf['label'] = labels\n#merged = df.merge(initial_text, left_on='clean', right_on = 'clean',left_index=True )\n\n#%%\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nfor i in range(n_clusters):\n #sns.set(color_codes=True)\n #sns.distplot(theta_transposed[theta_transposed['labels'] == i].drop(['labels'], axis = 1).mean())\n plt.plot(theta_transposed[theta_transposed['labels'] == i].drop(['labels'], axis = 1).mean(),label = i)\n \n#%%\n#sns.distplot(theta_transposed[theta_transposed['labels'] == 4].drop(['labels'], axis = 1).mean())\nplt.plot(theta_transposed[theta_transposed['labels'] == 14].drop(['labels'], axis = 1).mean())\n#%%\n# Checkpoint\n\nfile1 = open(\"myfile.txt\",\"w\")\n\nfor i in merged[ merged['label'] == 1]['text']:\n file1.write(i+'. \\n')\n#file1.writelines(df[df['label'] == 3]['clean']) \n\nfile1.close() \n# %%\n\n# starting pytorch \n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport numpy as np\nfrom collections import Counter\nimport os\nfrom argparse import Namespace\n\n\nflags = Namespace(\n train_file='myfile.txt',\n seq_size=32,\n batch_size=16,\n embedding_size=64,\n lstm_size=64,\n gradients_norm=5,\n initial_words=['просто'],\n predict_top_k=5,\n checkpoint_path='checkpoint',\n)\n\ndef get_data_from_file(train_file, batch_size, seq_size):\n with open(train_file, 'r') as f:\n text = f.read()\n text = text.split()\n\n word_counts = Counter(text)\n sorted_vocab = sorted(word_counts, key=word_counts.get, reverse=True)\n int_to_vocab = {k: w for k, w in enumerate(sorted_vocab)}\n vocab_to_int = {w: k for k, w in int_to_vocab.items()}\n n_vocab = len(int_to_vocab)\n\n print('Vocabulary size', n_vocab)\n\n int_text = [vocab_to_int[w] for w in text]\n num_batches = int(len(int_text) / (seq_size * batch_size))\n in_text = int_text[:num_batches * batch_size * seq_size]\n out_text = np.zeros_like(in_text)\n out_text[:-1] = in_text[1:]\n out_text[-1] = in_text[0]\n in_text = np.reshape(in_text, (batch_size, -1))\n out_text = np.reshape(out_text, (batch_size, -1))\n return int_to_vocab, vocab_to_int, n_vocab, in_text, out_text\n\ndef get_batches(in_text, out_text, batch_size, seq_size):\n num_batches = np.prod(in_text.shape) // (seq_size * batch_size)\n for i in range(0, num_batches * seq_size, seq_size):\n yield in_text[:, i:i+seq_size], out_text[:, i:i+seq_size]\n\nclass RNNModule(nn.Module):\n def __init__(self, n_vocab, seq_size, embedding_size, lstm_size):\n super(RNNModule, self).__init__()\n self.seq_size = seq_size\n self.lstm_size = lstm_size\n self.embedding = nn.Embedding(n_vocab, embedding_size)\n self.lstm = nn.LSTM(embedding_size,\n lstm_size,\n batch_first=True)\n self.dense = nn.Linear(lstm_size, n_vocab)\n def forward(self, x, prev_state):\n embed = self.embedding(x)\n output, state = self.lstm(embed, prev_state)\n logits = self.dense(output)\n\n return logits, state\n def zero_state(self, batch_size):\n return (torch.zeros(1, batch_size, self.lstm_size),\n torch.zeros(1, batch_size, self.lstm_size))\ndef get_loss_and_train_op(net, lr=0.001):\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(net.parameters(), lr=lr)\n\n return criterion, optimizer\n\ndef main():\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n int_to_vocab, vocab_to_int, n_vocab, in_text, out_text = get_data_from_file(\n flags.train_file, flags.batch_size, flags.seq_size)\n\n net = RNNModule(n_vocab, flags.seq_size,\n flags.embedding_size, flags.lstm_size)\n net = net.to(device)\n\n criterion, optimizer = get_loss_and_train_op(net, 0.01)\n\n iteration = 0\n for e in range(50):\n batches = get_batches(in_text, out_text, flags.batch_size, flags.seq_size)\n state_h, state_c = net.zero_state(flags.batch_size)\n \n # Transfer data to GPU\n state_h = state_h.to(device)\n state_c = state_c.to(device)\n for x, y in batches:\n iteration += 1\n \n # Tell it we are in training mode\n net.train()\n\n # Reset all gradients\n optimizer.zero_grad()\n\n # Transfer data to GPU\n x = torch.tensor(x).to(device)\n y = torch.tensor(y).to(device)\n\n logits, (state_h, state_c) = net(x, (state_h, state_c))\n loss = criterion(logits.transpose(1, 2), y)\n\n state_h = state_h.detach()\n state_c = state_c.detach()\n\n loss_value = loss.item()\n\n # Perform back-propagation\n loss.backward()\n\n _ = torch.nn.utils.clip_grad_norm_(\n net.parameters(), flags.gradients_norm)\n # Update the network's parameters\n optimizer.step()\n if iteration % 100 == 0:\n print('Epoch: {}/{}'.format(e, 200),\n 'Iteration: {}'.format(iteration),\n 'Loss: {}'.format(loss_value))\n\n if iteration % 300 == 0:\n predict(device, net, flags.initial_words, n_vocab,\n vocab_to_int, int_to_vocab, top_k=5)\n\ndef predict(device, net, words, n_vocab, vocab_to_int, int_to_vocab, top_k=5):\n net.eval()\n\n state_h, state_c = net.zero_state(1)\n state_h = state_h.to(device)\n state_c = state_c.to(device)\n for w in words:\n ix = torch.tensor([[vocab_to_int[w]]]).to(device)\n output, (state_h, state_c) = net(ix, (state_h, state_c))\n \n _, top_ix = torch.topk(output[0], k=top_k)\n choices = top_ix.tolist()\n choice = np.random.choice(choices[0])\n\n words.append(int_to_vocab[choice])\n for _ in range(100):\n ix = torch.tensor([[choice]]).to(device)\n output, (state_h, state_c) = net(ix, (state_h, state_c))\n\n _, top_ix = torch.topk(output[0], k=top_k)\n choices = top_ix.tolist()\n choice = np.random.choice(choices[0])\n words.append(int_to_vocab[choice])\n\n print(' '.join(words))\n \nif __name__ == '__main__':\n main()\n# %%\n\n# %%\nimport markovify\n#%%\n\n# simple state markov chain \ntt = theta_texts[theta_texts['leading_topic'] == 'topic_32']\ntext_model = markovify.Text(tt['text'], state_size= 2 )\ntext_model.compile(inplace = True)\nfor i in range(5):\n print(text_model.make_short_sentence(280))\n\n#%%\n# multistate markov chain \nmodel_a = markovify.Text(theta_texts[theta_texts['leading_topic'] == 'topic_18']['text'], state_size = 2 )\nmodel_b = markovify.Text(theta_texts[theta_texts['leading_topic'] == 'topic_25']['text'], state_size= 2)\n\nmodel_combo = markovify.combine([ model_a, model_b ], [ 1.5, 1 ])\nfor i in range(5):\n print(model_combo.make_sentence())\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#%% md\n\n# RuBETR classifier\n\n#%%\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n#%%\n\n#from deeppavlov.dataset_iterators.basic_classification_iterator import BasicClassificationDatasetIterator\n#iterator = BasicClassificationDatasetIterator(data, seed=42, shuffle=True)\n#for batch in iterator.gen_batches(data_type=\"train\", batch_size=13):\n# print(batch)\n# break\n\n#%%\n\n\n#downloading te right vocabulaty\nfrom deeppavlov.models.preprocessors.bert_preprocessor import BertPreprocessor\nbert_preprocessor = BertPreprocessor(vocab_file=\"~/.deeppavlov/downloads/bert_models/rubert_cased_L-12_H-768_A-12_v2/vocab.txt\",\n do_lower_case=False,\n max_seq_length=64)\n\n\n\n#%%\n\nfrom deeppavlov.models.bert.bert_classifier import BertClassifierModel\n#from deeppavlov.metrics.accuracy import sets_accuracy\nbert_classifier = BertClassifierModel(\n n_classes=15,\n return_probas=False,\n one_hot_labels=True,\n bert_config_file=\"~/.deeppavlov/downloads/bert_models/rubert_cased_L-12_H-768_A-12_v2/bert_config.json\",\n pretrained_bert=\"~/.deeppavlov/downloads/bert_models/rubert_cased_L-12_H-768_A-12_v2/bert_model.ckpt\",\n save_path=\"ru_bert_model/model\",\n load_path=\"ru_bert_model/model\",\n keep_prob=0.5,\n learning_rate=1e-05,\n learning_rate_drop_patience=5,\n learning_rate_drop_div=2.0\n)\n\n#%%\n\n#changing vocabulary format\nfrom deeppavlov.core.data.simple_vocab import SimpleVocabulary\nvocab = SimpleVocabulary(save_path=\"./binary_classes.dict\")\n#iterator.get_instances(data_type=\"train\")\n#vocab.fit(iterator.get_instances(data_type=\"train\")[1])\n#list(vocab.items())\n#bert_classifier(bert_preprocessor(top_tokens_vec))\n#bert_classifier(bert_preprocessor(artmToks))\n\n#%% md\n\n# Turning BERT classifier into pretrained PyTorch\n\n#%%\n\nfrom pytorch_transformers import BertForPreTraining, BertConfig, BertTokenizer, load_tf_weights_in_bert #BertModel\n\n#%% md\n\n#transformin deeppavlov BERT model into PyTorch pretrained model\n\ndef convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, bert_config_file):\n config = BertConfig.from_json_file(bert_config_file)\n model = BertForPreTraining(config)\n model = load_tf_weights_in_bert(model, config, tf_checkpoint_path)\n\n return model\n\nBERT_MODEL_PATH = \"/Users/apple/.deeppavlov/downloads/bert_models/rubert_cased_L-12_H-768_A-12_v2/\"\ntf_checkpoint_path = BERT_MODEL_PATH + 'bert_model.ckpt'\nbert_config_file = BERT_MODEL_PATH + 'bert_config.json'\n\ndownloaded = convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, bert_config_file)\ntokenizer = BertTokenizer.from_pretrained(BERT_MODEL_PATH, cache_dir=None, do_lower_case=False)\n\n#%%\n\nencoder = downloaded.bert\n\n","sub_path":"topic_modeling .py","file_name":"topic_modeling .py","file_ext":"py","file_size_in_byte":19149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"184648046","text":"from scrapfly import ScrapeConfig\nfrom scrapfly.scrapy import ScrapflyMiddleware, ScrapflyScrapyRequest, ScrapflySpider, ScrapflyScrapyResponse\n\n\nclass BEA(ScrapflySpider):\n name = \"bea\"\n\n allowed_domains = [\"www.bea.aero\", \"bea.aero\"]\n start_urls = [ScrapeConfig(\"https://bea.aero/en/investigation-reports/notified-events/?tx_news_pi1%5Baction%5D=searchResult&tx_news_pi1%5Bcontroller%5D=News&tx_news_pi1%5BfacetAction%5D=add&tx_news_pi1%5BfacetTitle%5D=year_intS&tx_news_pi1%5BfacetValue%5D=2016&cHash=408c483eae88344bf001f9cdbf653010\")]\n\n def parse(self, response:ScrapflyScrapyResponse):\n for href in response.css('h1.search-entry__title > a::attr(href)').extract():\n yield ScrapflyScrapyRequest(\n scrape_config=ScrapeConfig(url=response.urljoin(href)),\n callback=self.parse_report\n )\n\n def parse_report(self, response:ScrapflyScrapyResponse):\n for el in response.css('li > a[href$=\".pdf\"]:first-child'):\n yield ScrapflyScrapyRequest(\n scrape_config=ScrapeConfig(url=response.urljoin(el.attrib['href'])),\n callback=self.save_pdf\n )\n\n def save_pdf(self, response:ScrapflyScrapyResponse):\n response.sink(path='pdf', name=response.url.split('/')[-1])\n","sub_path":"examples/scrapy/bea/bea/spiders/bea.py","file_name":"bea.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"497067137","text":"# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nimport luigi\n\nfrom servicecatalog_puppet.workflow.portfolio.portfolio_management import (\n disassociate_product_from_portfolio_task,\n)\nfrom servicecatalog_puppet.workflow.portfolio.portfolio_management import (\n portfolio_management_task,\n)\n\n\nclass DisassociateProductsFromPortfolio(\n portfolio_management_task.PortfolioManagementTask\n):\n account_id = luigi.Parameter()\n region = luigi.Parameter()\n portfolio_id = luigi.Parameter()\n\n def params_for_results_display(self):\n return {\n \"account_id\": self.account_id,\n \"region\": self.region,\n \"portfolio_id\": self.portfolio_id,\n \"cache_invalidator\": self.cache_invalidator,\n }\n\n def api_calls_used(self):\n return {\n f\"servicecatalog.search_products_as_admin_single_page_{self.account_id}_{self.region}_{self.portfolio_id}\": 1,\n }\n\n def requires(self):\n disassociates = list()\n requirements = dict(disassociates=disassociates)\n with self.spoke_regional_client(\"servicecatalog\") as servicecatalog:\n results = servicecatalog.search_products_as_admin_single_page(\n PortfolioId=self.portfolio_id\n )\n for product_view_detail in results.get(\"ProductViewDetails\", []):\n disassociates.append(\n disassociate_product_from_portfolio_task.DisassociateProductFromPortfolio(\n account_id=self.account_id,\n region=self.region,\n portfolio_id=self.portfolio_id,\n product_id=product_view_detail.get(\"ProductViewSummary\").get(\n \"ProductId\"\n ),\n manifest_file_path=self.manifest_file_path,\n )\n )\n return requirements\n\n def run(self):\n self.write_output(self.params_for_results_display())\n","sub_path":"servicecatalog_puppet/workflow/portfolio/portfolio_management/disassociate_products_from_portfolio_task.py","file_name":"disassociate_products_from_portfolio_task.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"461274936","text":"import logging\nfrom functools import wraps\nfrom json import JSONDecodeError\n\nfrom requests import HTTPError\n\n\ndef protect(default=None):\n \"\"\"This decorator can be used on any method the requests some\n resource and expects:\n\n A) The response status to be non 4XX and non 5XX (aka, response OK)\n B) The response content to be parsable JSON\n\n In the event the method throws these errors uncaught, it will\n catch these errors (HTTPError and JSONDecodeError) and return\n the ``default`` value.\n\n :param default=None: Default value to return if exceptions are\n raised.\n \"\"\"\n def wrapper(fn, *args, **kwargs):\n @wraps(fn)\n def wrapped(self, *args, **kwargs):\n logger = logging.getLogger(\"nest\")\n\n rv = None\n try:\n rv = fn(self, *args, **kwargs)\n except (HTTPError) as error:\n url = error.response.url\n logger.error(f\"Could not get {url}: {error}\")\n except (JSONDecodeError) as error:\n logger.error(f\"Could not decode response JSON: {error}\")\n return rv or default\n return wrapped\n return wrapper\n","sub_path":"nest/apis/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"600109154","text":"from flask import Flask, render_template, request, jsonify\nfrom googletrans import LANGCODES\nfrom func import run\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n languages = LANGCODES\n return render_template('index.html', languages=languages)\n\n\n@app.route('/detect', methods=['POST'])\ndef detect():\n if request.method == 'POST':\n url = request.form['url']\n if url:\n results = run(url, 'vi')\n return render_template('result.html', results=results)\n else:\n return \"1\"\n\n\ndef combine(dictionaries):\n combined_dict = {}\n for dictionary in dictionaries:\n for key, value in dictionary.items():\n combined_dict.setdefault(key, []).append(value)\n return combined_dict\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=7000, debug=True)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"228819613","text":"import tensorflow as tf\nimport nice_model as nice_model\n#---------------------------------------------------------------------------------------------------------------------------------------\nbatch_size =5\ndef source_to_seq(text):\n '''\n 对源数据进行转换\n '''\n sequence_length = 120\n return [nice_model.source_letter_to_int.get(word, nice_model.source_letter_to_int['_UNK']) for word in text.split(' ')] + [nice_model.source_letter_to_int['_PAD']]*(sequence_length-len(text))\n\n#测试\n# 输入一个单词\n#input_word=[]\n#with open(\"D:/python project me/data\\text_summar\\nice data\\nice data dev/content_dev_id.txt\") as f2:\n#\tfor line in f2:\n\t#\tinput_line=line\n\t#\tinput_word\n \ninput_word=\"国际 显示 人员 希望 数据 告诉 媒体 一定 关注 近日 调查\"\n#input_word = \"3288 117 492 7 234 1338 3621 475 23 4 20 7 234 475 5 7 48 1577 369 1042 297 1924 1083 6 8 411 94 59 39 3095 11 4169 11 2616 11 2765 17 3068 216 127 274 3199 42 7 234 2456 320 8028 475 6\"\n'''\n NUMBER 反对 宪法 基本 原则 危害 国家 安全 政权 稳定 统一 的 煽动 民族 仇恨 民族 歧视 的 NUMBER 宣扬 邪教 和 封建迷信 的 散布 谣言 破坏 社会 稳定 的 侮辱 诽谤 他人 侵害 他人 合法权益 的 NUMBER 散布 淫秽 色情 赌博 暴力 凶杀 恐怖 或者 教唆 犯罪 的\n '''\ntext = source_to_seq(input_word)\n\ncheckpoint = \"./checkpoint_f/trained_model.ckpt\"\n\nloaded_graph = tf.Graph()\nwith tf.Session(graph=loaded_graph) as sess:\n # 加载模型\n loader = tf.train.import_meta_graph(checkpoint + '.meta')\n loader.restore(sess, checkpoint)\n\n input_data = loaded_graph.get_tensor_by_name('inputs:0')\n logits = loaded_graph.get_tensor_by_name('predictions:0')\n source_sequence_length = loaded_graph.get_tensor_by_name('source_sequence_length:0')\n target_sequence_length = loaded_graph.get_tensor_by_name('target_sequence_length:0')\n \n answer_logits = sess.run(logits, {input_data: [text]*batch_size, \n target_sequence_length: [len(input_word)]*batch_size, \n source_sequence_length: [len(input_word)]*batch_size})[0] \n\n\npad = nice_model.source_letter_to_int[\"_PAD\"]\n\nprint('原始输入:', input_word)\n\nprint('\\nSource')\nprint(' Word 编号: {}'.format([i for i in text]))\nprint(' Input Words: {}'.format(\" \".join([nice_model.source_int_to_letter[i] for i in text])))\n\nprint('\\nTarget')\nprint(' Word 编号: {}'.format([i for i in answer_logits if i != pad]))\nprint(' Response Words: {}'.format(\" \".join([nice_model.target_int_to_letter[i] for i in answer_logits if i != pad])))","sub_path":"nice_main.py","file_name":"nice_main.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"133900810","text":"from random import shuffle, random, choice\nfrom sys import argv\n\nlista = \"abcdefghijklmnopqrstuvwxyz\"\n\ndef peor(nombre, rango):\n for j in range(10):\n PEOR = \"\"\n peor = []\n for char in lista:\n for i in range(rango):\n peor.append(char)\n shuffle(peor, random)\n for char in peor:\n PEOR+=char\n file = open(nombre+\"_\"+str(j)+\".txt\", \"w\")\n file.write(PEOR)\n file.close()\n\ndef tipico(nombre, rango):\n for j in range(10):\n TIPICO = \"\"\n for i in range(len(lista)):\n for j in range(rango):\n TIPICO += choice(lista)\n file = open(nombre+\"_\"+str(j)+\".txt\", \"w\")\n file.write(TIPICO)\n file.close()\n\nfor i in range(int(argv[1])):\n iter = int(argv[2])\n tipico(\"TIPICO_\"+str(i), iter)\n iter = iter**2\n","sub_path":"CASOS/best_worst_case.py","file_name":"best_worst_case.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"226348740","text":"import numpy as np\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport math\r\n\r\ndef ClassifyColor( BGR, width, height ): ##分類顏色 (BGR, width, height)\r\n r_threshold = 20 ##r閾值 before 10\r\n b_threshold = 20 ##b閾值 before 10\r\n FortyFive_degree = math.pi / 4 ## 45度\r\n grey_threshold = 10.0 * math.pi / 180.0 ##色角上下限 before 5\r\n \r\n for y in range(0, height, 1):\r\n cur_row = BGR[y]\r\n for x in range(0, width, 1):\r\n [b1, g1, r1] = cur_row[x] #b1, g1 and r1 are type unsigned integer 8 bits \r\n #Convert to 32 bits integer #b1,g1和r1是無符號整數8位類型 轉換為32位整數\r\n b = int(b1)\r\n g = int(g1)\r\n r = int(r1)\r\n #Red color\r\n if r - b > r_threshold:\r\n if r - g > r_threshold:\r\n cur_row[x] = [255, 255, 255]\r\n continue ##跳过某些循环\r\n \r\n #Blue color\r\n if b - r > b_threshold:\r\n if b - g > b_threshold:\r\n cur_row[x] = [0, 0, 0]\r\n continue\r\n \r\n #Other colors\r\n cur_row[x] = [0, 0, 0]\r\n\r\n return BGR\r\n\r\n\r\ncap = cv2.VideoCapture(0) \r\n\r\nwhile(1): \r\n \r\n if __name__ == '__main__':\r\n \r\n ret, frame = cap.read() \r\n\r\n if frame.size == 0:\r\n ##if ret == False: \r\n print(f\"Fail to read image {filename}\")\r\n else:\r\n cv2.imshow('Original frame',frame) \r\n\r\n (height, width, channels) = frame.shape\r\n print(f\"frame dimension ( {height} , {width}, {channels})\\n\" )\r\n if channels != 3:\r\n print(\"Image is not a color image ##################\")\r\n\r\n if frame.dtype != \"uint8\":\r\n print(\"Image is not of type uint8 #################\")\r\n\r\n ms = frame.copy()\r\n\r\n kernel = np.ones((5,5), np.uint8)\r\n ##dilation = cv2.dilate(test, kernel, iterations = 3)\r\n dilation = cv2.dilate(ms, kernel, iterations = 7)\r\n\r\n cv2.imshow('dilation', dilation)\r\n\r\n\r\n kernel = np.ones((7,7), np.uint8)\r\n ##erosion = cv2.erode(dilation, kernel, iterations = 3)\r\n erosion = cv2.erode(dilation, kernel, iterations = 9)\r\n cv2.imshow('erosion', erosion)\r\n \r\n #Convert image to NumPy array (Create a new 2D array)\r\n # Note: The order is in BGR format! 將圖像轉換為NumPy數組(創建新的2D數組)\r\n BGR_array = np.array( erosion )\r\n \r\n #Classify red, blue and grey color\r\n Result_array = ClassifyColor( BGR_array, width, height )\r\n \r\n cv2.imshow('BGR',Result_array)\r\n\r\n k = cv2.waitKey(5) & 0xFF\r\n if k == 27: \r\n break\r\n\r\n \r\n# Close the window \r\ncap.release() \r\n \r\n# De-allocate any associated memory usage \r\ncv2.destroyAllWindows() \r\n\r\n","sub_path":"vs/real_time_rgb_v2.py","file_name":"real_time_rgb_v2.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"399236887","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Sep 6 16:39:13 2019\r\n\r\n@author: vr_lab\r\n\"\"\"\r\n\r\n# python convert_tetgen_to_abaqus.py –-mode= write_mesh\r\n\r\n\r\nimport argparse\r\nimport numpy as np\r\nimport os\r\nimport pdb\r\nimport read_tetgen\r\n\r\nTOLERANCE = 0.5\r\n\r\n# abaqus starts with index 1\r\n# mesh_type is either NODE or ELEMENT\r\n# boundary_condition mode is outdataded. We can assign in Abaqus directly\r\n\r\ndef write_mesh(input_file_name, output_file_name, mesh_type):\r\n output_file = open(output_file_name, 'a+')\r\n with open(input_file_name, \"r\") as file:\r\n line_num = 0\r\n for line in file:\r\n if line_num == 0:\r\n num_mesh = int(line.split()[0])\r\n if mesh_type.lower() == 'element':\r\n output_file.write('*ELEMENT, TYPE = C3D4,ELSET=breast' + '\\n')\r\n elif mesh_type.lower() == \"node\":\r\n output_file.write('*NODE' + '\\n')\r\n else:\r\n return\r\n line_num += 1\r\n continue\r\n if line_num > num_mesh:\r\n return\r\n li = line.strip().split()\r\n li_new = ''\r\n for index, temp_li in enumerate(li):\r\n if index == 0:\r\n li_new += str(int(temp_li) + 1) + ','\r\n elif index == len(li) - 1:\r\n if mesh_type.lower() == 'element':\r\n li_new += str(int(temp_li) + 1)\r\n else:\r\n li_new += temp_li\r\n else:\r\n if mesh_type.lower() == 'element':\r\n li_new += str(int(temp_li) + 1) + ','\r\n else:\r\n li_new += temp_li + ','\r\n output_file.write(li_new + '\\n')\r\n line_num += 1\r\n output_file.close() \r\n\r\ndef read_y_value(node_file):\r\n y_axes = []\r\n with open(node_file, \"r\") as file:\r\n line_num = 0\r\n for line in file:\r\n if line_num == 0:\r\n num_mesh = int(line.split()[0])\r\n line_num += 1\r\n continue\r\n if line_num > num_mesh:\r\n return y_axes\r\n li = line.strip().split()\r\n y_axes.append(float(li[2]))\r\n line_num += 1\r\n return y_axes\r\n\r\ndef return_content_and_insert_position(file_name, search_line):\r\n output_file = open(file_name, 'r')\r\n content = output_file.readlines()\r\n output_file.close()\r\n # pdb.set_trace()\r\n line_index = content.index(search_line)\r\n return content, line_index\r\n\r\ndef combine_insert_content(content, file_name):\r\n content = ''.join(content)\r\n output_file = open(file_name, 'w')\r\n output_file.write(content)\r\n output_file.close() \r\n\r\ndef reformat_node_indices(node_indices):\r\n nums = sorted(set(node_indices))\r\n gaps = [[s, e] for s, e in zip(nums, nums[1:]) if s+1 < e]\r\n edges = iter(nums[:1] + sum(gaps, []) + nums[-1:])\r\n return list(zip(edges, edges))\r\n\r\n''' \r\ndef add_node_set(file_name, node_indices):\r\n search_line = '*End Assembly\\n'\r\n content, insert_pos = return_content_and_insert_position(file_name, search_line)\r\n node_indices_range = reformat_node_indices(node_indices)\r\n for count, node_index in enumerate(node_indices_range):\r\n content.insert(insert_pos + 2 * count - 1, '*Nset, nset' + '=' + 'n' + str(count) + ', instance=PART-1-2, generate\\n')\r\n content.insert(insert_pos + 2 * count, str(node_index[0]) + ',' + str(node_index[1]) + '\\n')\r\n combine_insert_content(content, file_name)\r\n'''\r\n\r\n# input is a list of numbers that needs to be written\r\ndef write_sixteen_num_perline(numbers, file_name):\r\n write_file = open(file_name, 'a+')\r\n line = []\r\n for num in numbers:\r\n if len(line) == 16:\r\n for index, word in enumerate(line):\r\n if index == 15:\r\n write_file.write(str(word) + '\\n') \r\n else:\r\n write_file.write(str(word) + ',') \r\n line = [] \r\n line.append(num)\r\n for index, li in enumerate(line):\r\n if index != len(line) - 1:\r\n write_file.write(str(li) + ',') \r\n else:\r\n write_file.write(str(li) + '\\n')\r\n write_file.close()\r\n \r\ndef add_node_set(file_name, node_indices):\r\n search_line = '*End Assembly\\n'\r\n content, insert_pos = return_content_and_insert_position(file_name, search_line)\r\n content.insert(insert_pos, '*Nset, nset' + '=' + 'n0' + ', instance=PART-1-2\\n')\r\n line = []\r\n count = 0\r\n for node_index in node_indices:\r\n if len(line) == 16:\r\n content.insert(insert_pos + count + 1, str(line).strip('[]') + '\\n')\r\n line = []\r\n count += 1\r\n else:\r\n line.append(node_index)\r\n if len(line) != 0:\r\n content.insert(insert_pos + count, str(line).strip('[]') + '\\n')\r\n combine_insert_content(content, file_name)\r\n \r\n# the fixed vertices are those who has largest y value\r\ndef fixed_boundary_condition(file_name, y_axes):\r\n search_line = '*Step, name=Step-1, nlgeom=YES, inc=1000\\n'\r\n content, step_index = return_content_and_insert_position(file_name, search_line)\r\n max_y = max(y_axes)\r\n \r\n content.insert(step_index + 4, '*BOUNDARY\\n')\r\n node_indices = []\r\n for index, y in enumerate(y_axes):\r\n if abs(y - max_y) < TOLERANCE:\r\n node_indices.append(index + 1) \r\n content.insert(step_index + 5, 'n0' + ',ENCASTRE' + '\\n')\r\n combine_insert_content(content, file_name) \r\n add_node_set(file_name, node_indices) \r\n\r\ndef element_to_index(elementfile, nodefile):\r\n elem_to_index = {}\r\n content = read_tetgen.ReadTetGen(elementfile, nodefile)\r\n elems = content.read_elements()\r\n for i in range(elems.shape[0]):\r\n content = str(elems[i][0] + 1) + ',' + str(elems[i][1] + 1) + ',' \\\r\n + str(elems[i][2] + 1) + ',' + str(elems[i][3] + 1)\r\n elem_to_index[content] = i + 1\r\n return elem_to_index\r\n\r\n# layer order should be from innermost to outermost\r\ndef add_element_set(output_file, all_layer_elemfile, \r\n all_layer_nodefile):\r\n assigned_elem = {''}\r\n outmost_elefile = all_layer_elemfile[-1]\r\n outmost_nodefile = all_layer_nodefile[-1]\r\n elem_to_index = element_to_index(outmost_elefile, outmost_nodefile)\r\n \r\n for (elem_file, node_file) in zip(all_layer_elemfile, all_layer_nodefile):\r\n content = read_tetgen.ReadTetGen(elem_file, node_file)\r\n elems = content.read_elements()\r\n write_file = open(output_file_name, 'a+')\r\n pdb.set_trace()\r\n write_file.write('*Elset, elset=' + os.path.splitext(elem_file)[0] + ', instance=PART-1-1\\n')\r\n write_file.close()\r\n current_layer_elem = []\r\n for i in range(elems.shape[0]):\r\n content = str(elems[i][0] + 1) + ',' + str(elems[i][1] + 1) + ',' \\\r\n + str(elems[i][2] + 1) + ',' + str(elems[i][3] + 1)\r\n if content in assigned_elem:\r\n continue \r\n current_layer_elem.append(elem_to_index[content])\r\n assigned_elem.add(content)\r\n write_sixteen_num_perline(current_layer_elem, output_file)\r\n \r\ndef write_to_eof(content, output_file):\r\n write_file = open(output_file, 'a+')\r\n for line in content:\r\n write_file.write(line)\r\n write_file.close()\r\n \r\nif __name__ == '__main__':\r\n arg_parser = argparse.ArgumentParser()\r\n arg_parser.add_argument('--mode', help='What are you trying to do? write_mesh or boundary_condition', type=str)\r\n args = arg_parser.parse_args()\r\n mode = args.mode\r\n # output_file_name = 'Fat_Solid_hete_no_nipple.inp'\r\n output_file_name = 'skin_no_nipple.inp'\r\n if mode == 'write_mesh':\r\n # input_file_name = 'Fat_Solid_hete_no_nipple.node'\r\n input_file_name = 'Skin_Layer.node'\r\n write_mesh(input_file_name, output_file_name, 'node') \r\n # input_file_name = 'Fat_Solid_hete_no_nipple.ele' \r\n input_file_name = 'Skin_Layer.ele' \r\n write_mesh(input_file_name, outpcut_file_name, 'element') \r\n \r\n #####################################\r\n #### This mode is depricated, Abaqus can assign boundary directly\r\n if mode == 'boundary_condition':\r\n # node_file = 'Fat_Solid_hete.1.node'\r\n # output_file_name = 'breast_hete.inp'\r\n y_axes = read_y_value(node_file)\r\n fixed_boundary_condition(output_file_name, y_axes)\r\n \r\n if mode == 'add_elemset':\r\n first_layer_node = 'Skin_Layer.node'\r\n first_layer_ele = 'Skin_Layer.ele'\r\n second_layer_ele = 'fat_fromskin.ele'\r\n third_layer_ele = 'FGT_Cluster_1-2.ele'\r\n fourth_layer_ele = 'tumor_fromskin.ele'\r\n add_element_set(output_file_name, [fourth_layer_ele, third_layer_ele, \r\n second_layer_ele, first_layer_ele], [first_layer_node, \r\n first_layer_node, first_layer_node, first_layer_node])\r\n \r\n if mode == 'add_material':\r\n first_layer_property = '*Material, name=skin\\n \\\r\n *Density\\n \\\r\n 9.996e-10,\\n \\\r\n *Hyperelastic, mooney-rivlin\\n \\\r\n 0.002, 0.004, 3.36\\n'\r\n second_layer_property = '*Material, name=fat\\n \\\r\n *Density\\n \\\r\n 9.21e-10,\\n \\\r\n *Hyperelastic, mooney-rivlin\\n \\\r\n 0.0013, 0.002, 6.04\\n'\r\n third_layer_property = '*Material, name=glandular\\n \\\r\n *Density\\n \\\r\n 9.485e-10,\\n \\\r\n *Hyperelastic, mooney-rivlin\\n \\\r\n 0.0023, 0.0035, 3.45\\n'\r\n fourth_layer_property = '*Material, name=tumor \\\r\n *Density\\n \\\r\n 9.21e-10,\\n \\\r\n *Elastic \\\r\n 0.7193, 0.4531\\n'\r\n write_to_eof([first_layer_property, second_layer_property, \r\n third_layer_property, fourth_layer_property], \r\n output_file_name)","sub_path":"ChangeAbaqusInput/convert_tetgen_to_abaqus.py","file_name":"convert_tetgen_to_abaqus.py","file_ext":"py","file_size_in_byte":10352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"260898251","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport webbrowser\r\nimport random\r\nres = requests.get('https://zh.wikipedia.org/wiki/%E9%AE%9F%E9%B1%87%E9%AD%9A')\r\nsoup = BeautifulSoup(res.text, 'lxml')\r\nlinks = soup.find_all('a')\r\nfor link in links:\r\n if link.get('href')!=None:\r\n print(link.get('href'))\r\n\r\noutput = []\r\nwhile len(output)<5:\r\n link = random.choice(links)\r\n href = link.get('href')\r\n if href!=None and href not in output:\r\n output.append(href)\r\n\r\nfor url in output:\r\n if url.startswith('//'):\r\n webbrowser.open('https:'+url)\r\n elif url.startswith('/'):\r\n webbrowser.open('https://zh.wikipedia.org'+url)\r\n else:\r\n webbrowser.open(url)\r\n","sub_path":"lec16/lec16-class-1.py","file_name":"lec16-class-1.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"285232859","text":"#! /usr/bin/env python3.4\n#\n#$Author: ee364e07 $\n#$Date: 2015-10-06 17:25:38 -0400 (Tue, 06 Oct 2015) $\n#$HeadURL: svn+ssh://ece364sv@ecegrid/home/ecegrid/a/ece364sv/svn/F15/students/ee364e07/Lab06/parseData.py $\n#$Revision: 82610 $\n\nimport re\n\ndef getAllData():\n with open('UserData.txt','r') as f:\n data = f.readlines()\n\n namefl = re.compile('(?P[a-zA-Z]+) (?P[a-zA-Z]+)')\n namelf = re.compile('(?P[a-zA-Z]+), (?P[a-zA-Z]+)')\n #namelf = re.compile('(?P[a-zA-Z]+,\\ [a-zA-Z]+)')\n email = re.compile('([\\w_.-0-9]*)@([\\w_.-0-9]*)')\n phone = re.compile('(\\([0-9]{3}\\)\\ [0-9]{3}\\-[0-9]{4})|([0-9]{3}\\-[0-9]{3}\\-[0-9]{4})|([0-9]{10})')\n state = re.compile('([a-zA-Z]+|[a-zA-Z]+ [a-zA-Z]+)$')\n info = {}\n\n for item in data:\n test = re.match(namefl,item)\n test2 = re.match(namelf,item)\n etest = re.search(email,item)\n ptest = re.search(phone,item)\n stest = re.search(state,item)\n\n\n if test:\n first = test.group('fname1')\n last = test.group('lname1')\n full = first + ' ' + last\n info.update({full:[]})\n if etest:\n newmail = etest.group()\n info[full].append(newmail)\n if ptest:\n info[full].append(ptest.group())\n\n if stest:\n info[full].append(stest.group())\n\n if test2:\n first = test2.group('fname2')\n last = test2.group('lname2')\n full = first + ' ' + last\n info.update({full:[]})\n if etest:\n newmail = etest.group()\n info[full].append(newmail)\n if ptest:\n info[full].append(ptest.group())\n\n if stest:\n info[full].append(stest.group())\n\n print(info)\n return info\n\ndef getInvalidUsers():\n data = getAllData()\n iusers = []\n for key in data:\n if len(data[key]) == 0:\n iusers.append(key)\n\n iusers.sort()\n\n return iusers\n\n\ndef getUsersWithEmails():\n pass\n\ndef getValidUsers():\n data = getAllData()\n valid = []\n\n for key in data:\n if len(data[key]) == 3:\n newset = (key,data[key][0],data[key][1],data[key][2])\n valid.append(newset)\n\n print(valid)\n valid.sort()\n return valid\n\nif __name__ == \"__main__\":\n getInvalidUsers()\n getValidUsers()\n\n\n","sub_path":"Lab06/parseData.py","file_name":"parseData.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"237935355","text":"import numpy as np\nimport scipy as sp\nimport scipy.stats\nimport types\nimport statsmodels.sandbox.stats.multicomp\n\n\n# data transformation\ndef rankdata(data):\n rdata=np.zeros(np.shape(data))\n for crow in range(np.shape(data)[0]):\n rdata[crow,:]=sp.stats.rankdata(data[crow,:])\n return rdata\n\n\ndef log2data(data):\n data[data < 2] = 2\n data = np.log2(data)\n return data\n\n\ndef binarydata(data):\n data[data != 0] = 1\n return data\n\n\ndef normdata(data):\n data = data / np.sum(data, axis = 0)\n return data\n\n\n# different methods to calculate test statistic\ndef meandiff(data, labels):\n mean0 = np.mean(data[:, labels==0], axis = 1)\n mean1 = np.mean(data[:, labels==1], axis = 1)\n tstat = mean1 - mean0\n return tstat\n\ndef stdmeandiff(data, labels):\n mean0 = np.mean(data[:, labels==0], axis = 1)\n mean1 = np.mean(data[:, labels==1], axis = 1)\n sd0 = np.std(data[:, labels==0], axis = 1, ddof = 1)\n sd1 = np.std(data[:, labels==1], axis = 1, ddof = 1)\n tstat = (mean1 - mean0)/(sd1 + sd0)\n return tstat\n\ndef mannwhitney(data, labels):\n group0 = data[:, labels == 0]\n group1 = data[:, labels == 1]\n tstat = np.array([scipy.stats.mannwhitneyu(group0[i, :],group1[i, :]).statistic for i in range(np.shape(data)[0])])\n return tstat\n\n\ndef kruwallis(data, labels):\n n = len(np.unique(labels))\n allt=[]\n for cbact in range(np.shape(data)[0]):\n group = []\n for j in range(n):\n group.append(data[cbact, labels == j])\n tstat = scipy.stats.kruskal(*group).statistic\n allt.append(tstat)\n return allt\n\n\n\n# new fdr method\ndef dsfdr(data,labels, method='meandiff', transform='rankdata', alpha=0.1, numperm=1000,fdrmethod='dsfdr'):\n '''\n calculate the Discrete FDR for the data\n\n input:\n data : N x S numpy array\n each column is a sample (S total), each row an OTU (N total)\n labels : a 1d numpy array (length S)\n the labels of each sample (same order as data) with the group (0/1 if binary, 0-G-1 if G groups, or numeric values for correlation)\n method : str or function\n the method to use for the t-statistic test. options:\n 'meandiff' : mean(A)-mean(B) (binary)\n 'mannwhitney' : mann-whitneu u-test (binary)\n 'kruwallis' : kruskal-wallis test (multiple groups)\n 'stdmeandiff' : (mean(A)-mean(B))/(std(A)+std(B)) (binary)\n 'spearman' : spearman correlation (numeric)\n 'pearson' : pearson correlation (numeric)\n 'nonzerospearman' : spearman correlation only non-zero entries (numeric)\n 'nonzeropearson' : pearson correlation only non-zero entries (numeric)\n function : use this function to calculate the t-statistic (input is data,labels, output is array of float)\n\n transform : str or ''\n transformation to apply to the data before caluculating the statistic\n 'rankdata' : rank transfrom each OTU reads\n 'log2data' : calculate log2 for each OTU using minimal cutoff of 2\n 'normdata' : normalize the data to constant sum per samples\n 'binarydata' : convert to binary absence/presence\n\n alpha : float\n the desired FDR control level\n numperm : int\n number of permutations to perform\n\n output:\n reject : np array of bool (length N)\n True for OTUs where the null hypothesis is rejected\n tstat : np array of float (length N)\n the t-statistic value for each OTU (for effect size)\n '''\n\n data=data.copy()\n # transform the data\n if transform == 'rankdata':\n data = rankdata(data)\n elif transform == 'log2data':\n data = log2data(data)\n elif transform == 'binarydata':\n data = binarydata(data)\n elif transform == 'normdata':\n data = normdata(data)\n\n numbact=np.shape(data)[0]\n\n labels=labels.copy()\n if method == \"meandiff\":\n # do matrix multiplication based calculation\n method = meandiff\n tstat=method(data,labels)\n t=np.abs(tstat)\n numsamples=np.shape(data)[1]\n p=np.zeros([numsamples,numperm])\n k1=1/np.sum(labels == 0)\n k2=1/np.sum(labels == 1)\n for cperm in range(numperm):\n np.random.shuffle(labels)\n p[labels==0, cperm] = k1\n p2 = np.ones(p.shape)*k2\n p2[p>0] = 0\n mean1 = np.dot(data, p)\n mean2 = np.dot(data, p2)\n u = np.abs(mean1 - mean2)\n\n elif method == 'mannwhitney':\n method = mannwhitney\n tstat=method(data,labels)\n t=np.abs(tstat)\n u=np.zeros([numbact,numperm])\n for cperm in range(numperm):\n rlabels=np.random.permutation(labels)\n rt=method(data,rlabels)\n u[:,cperm]=rt\n\n elif method == 'kruwallis':\n method = kruwallis\n tstat=method(data,labels)\n t=np.abs(tstat)\n u=np.zeros([numbact,numperm])\n for cperm in range(numperm):\n rlabels=np.random.permutation(labels)\n rt=method(data,rlabels)\n u[:,cperm]=rt\n\n elif method == 'stdmeandiff':\n method = stdmeandiff\n tstat=method(data,labels)\n t=np.abs(tstat)\n u=np.zeros([numbact,numperm])\n for cperm in range(numperm):\n rlabels=np.random.permutation(labels)\n rt=method(data,rlabels)\n u[:,cperm]=rt\n\n elif method == 'spearman' or method == 'pearson':\n # do fast matrix multiplication based correlation\n if method == 'spearman':\n data = rankdata(data)\n labels = sp.stats.rankdata(labels)\n meanval=np.mean(data,axis=1).reshape([data.shape[0],1])\n data=data-np.repeat(meanval,data.shape[1],axis=1)\n labels=labels-np.mean(labels)\n tstat=np.dot(data, labels)\n t=np.abs(tstat)\n permlabels = np.zeros([len(labels), numperm])\n for cperm in range(numperm):\n rlabels=np.random.permutation(labels)\n permlabels[:,cperm] = rlabels\n u=np.abs(np.dot(data,permlabels))\n\n elif method == 'nonzerospearman' or method == 'nonzeropearson':\n t = np.zeros([numbact])\n tstat = np.zeros([numbact])\n u = np.zeros([numbact, numperm])\n for i in range(numbact):\n index = np.nonzero(data[i, :])\n label_nonzero = labels[index]\n sample_nonzero = data[i, :][index]\n if method == 'nonzerospearman':\n sample_nonzero = sp.stats.rankdata(sample_nonzero)\n label_nonzero = sp.stats.rankdata(label_nonzero)\n sample_nonzero = sample_nonzero - np.mean(sample_nonzero)\n label_nonzero = label_nonzero - np.mean(label_nonzero)\n tstat[i] = np.dot(sample_nonzero, label_nonzero)\n t[i]=np.abs(tstat[i])\n\n permlabels = np.zeros([len(label_nonzero), numperm])\n for cperm in range(numperm):\n rlabels=np.random.permutation(label_nonzero)\n permlabels[:,cperm] = rlabels\n u[i, :] = np.abs(np.dot(sample_nonzero, permlabels))\n\n elif isinstance(method, types.FunctionType):\n # if it's a function, call it\n t=method(data,labels)\n tstat=t.copy()\n u=np.zeros([numbact,numperm])\n for cperm in range(numperm):\n rlabels=np.random.permutation(labels)\n rt=method(data,rlabels)\n u[:,cperm]=rt\n else:\n print('unsupported method %s' % method)\n return None,None\n\n # fix floating point errors (important for permutation values!)\n for crow in range(numbact):\n closepos=np.isclose(t[crow],u[crow,:])\n u[crow,closepos]=t[crow]\n\n # calculate permutation p-vals\n pvals=np.zeros([numbact]) # p-value for original test statistic t\n pvals_u=np.zeros([numbact,numperm]) # pseudo p-values for permutated test statistic u \n for crow in range(numbact):\n allstat=np.hstack([t[crow],u[crow,:]])\n allstat=1-(sp.stats.rankdata(allstat,method='min')/len(allstat))\n pvals[crow]=allstat[0] \n pvals_u[crow,:]=allstat[1:]\n\n # calculate FDR\n if fdrmethod=='dsfdr':\n # sort the p-values for original test statistics from big to small\n sortp=list(set(pvals))\n sortp=np.sort(sortp)\n sortp=sortp[::-1]\n\n foundit=False\n allfdr=[]\n allt=[]\n for cp in sortp:\n realnum=np.sum(pvals<=cp)\n fdr=(realnum+np.count_nonzero(pvals_u<=cp)) / (realnum*(numperm+1))\n allfdr.append(fdr)\n allt.append(cp)\n if fdr<=alpha:\n realcp=cp\n foundit=True\n break \n\n if not foundit:\n # no good threshold was found\n reject=np.repeat([False],numbact)\n return reject, tstat, pvals\n\n # fill the reject null hypothesis\n reject=np.zeros(numbact,dtype=int)\n reject= (pvals<=realcp) \n \n elif fdrmethod=='bhfdr':\n t_star = np.array([t, ] * numperm).transpose()\n pvals=(np.sum(u>=t_star,axis=1)+1)/(numperm+1)\n reject=statsmodels.sandbox.stats.multicomp.multipletests(pvals,alpha=alpha,method='fdr_bh')[0]\n\n elif fdrmethod=='byfdr':\n t_star = np.array([t, ] * numperm).transpose()\n pvals=(np.sum(u>=t_star,axis=1)+1)/(numperm+1)\n reject=statsmodels.sandbox.stats.multicomp.multipletests(pvals,alpha=alpha,method='fdr_by')[0]\n\n return reject, tstat, pvals\n\n\n## qiime 2 layout goes below\nfrom numpy import log, sqrt\nfrom scipy.stats import (f_oneway, kruskal, mannwhitneyu,\n wilcoxon, ttest_ind, ttest_rel, kstest, chisquare,\n friedmanchisquare)\nfrom skbio.stats.composition import clr\n\n_sig_tests = {'f_oneway': f_oneway,\n 'kruskal': kruskal,\n 'mannwhitneyu': mannwhitneyu,\n 'wilcoxon': wilcoxon,\n 'ttest_ind': ttest_ind,\n 'ttest_rel': ttest_rel,\n 'kstest': kstest,\n 'chisquare': chisquare,\n 'friedmanchisquare': friedmanchisquare}\n\n\n_transform_functions = {'sqrt': sqrt,\n 'log': log,\n 'clr': clr}\n\ndef statistical_tests():\n return list(_sig_tests.keys())\n\n\ndef transform_functions():\n return list(_transform_functions.keys())\n\n\ndef permutation_fdr(output_dir: str,\n table : pd.DataFrame,\n metadata: qiime.MetadataCategory,\n statistical_test: str='f_oneway',\n transform_function: str='rank',\n permutations: int=1000) -> None:\n # See q2-composition for more details\n # https://github.com/qiime2/q2-composition/blob/master/q2_composition/_ancom.py\n\n # TODO : Consider renaming the functions to match q2-composition\n\n metadata_series = metadata.to_series()[table.index]\n # Make sure that metadata and table match up\n reject_idx = _pfdr(table.value,\n metadata_series.values,\n statistical_test,\n transform_function,\n alpha, numperm)\n # TODO : create heatmap using matplotlib imshow\n # and embed inside of html\n\n # TODO : write table to a csv\n","sub_path":"q2_dfdr/_dfdr.py","file_name":"_dfdr.py","file_ext":"py","file_size_in_byte":11214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"284445470","text":"# 示例 1:\n# 输入: [1,2,3,1]\n# 输出: 4\n# 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。\n# 偷窃到的最高金额 = 1 + 3 = 4 。\n# 示例 2:\n# 输入: [2,7,9,3,1]\n# 输出: 12\n# 解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。\n# 偷窃到的最高金额 = 2 + 9 + 1 = 12 。\n\nclass Solution:\n def rob(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # 动态规划简化版\n last_max = 0\n curr_max = 0\n for i in nums:\n curr_max, last_max= max(last_max+i,curr_max), curr_max\n return curr_max\n\n # 动态规划思想详细版\n # if len(nums) == 0:\n # return 0\n # elif len(nums) == 1:\n # return nums[0]\n # elif len(nums) == 2:\n # return max(nums[0], nums[1])\n # import numpy as np\n # opt = np.zeros(len(nums))\n # len_arr = len(nums)\n # opt[0] = nums[0]\n # opt[1] = max(nums[0],nums[1])\n # for i in range(2, len_arr):\n # opt[i] = max(opt[i-2]+nums[i], opt[i-1])\n # return int(opt[-1])\n\na = Solution()\nprint(a.rob([2,7,9,3,1]))","sub_path":"all_topic/esay_topic/198.打家劫舍.py","file_name":"198.打家劫舍.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"562060097","text":"#定义一个蚂蚁类,这个蚂蚁类有名字属性和速度属性\nclass Ant(object):\n\n def __init__(self, name, speed):\n self.name = name\n self.speed = speed\n\n#环形追及相遇的要点是当快的追上慢的的时候路程差刚好是一圈\n#由此我们可以列出一个公式\n#1圈=(快的的速度-慢的的��度)*第一次追上的时间\n#第一次追上的时间=1圈/(快的的速度-慢的的速度)\n#因为相遇之后无论是在那个点下一次都是全新的一次相遇\n#所以一段时间内相遇的次数=这段时间/第一次追上的时间\ndef catch(ant1, ant2):\n #time为快的和慢的相遇一次的时间。\n time=0\n time = 1.0/abs(ant1.speed-ant2.speed)\n return time\n\n\ndef count_time(i, ant, temp, run_time, total_time):\n catch_time = catch(i, ant[temp])\n catch_num = run_time // catch_time\n total_time.append(catch_num)\n print(\"%s<-->%s:相遇一次的时间为%.2f分钟,%s分钟内相遇%s次\" % (i.name, ant[temp].name, float(catch_time), run_time, catch_num))\n\n\ndef main():\n\n num = 0\n #记录所有蚂蚁之间两两相遇的次数。\n total_time = []\n\n #创建蚂蚁A,让蚂蚁A以速度1圈/分跑起来\n A = Ant(\"蚂蚁A\", 1)\n\n # 创建蚂蚁B,让蚂蚁B以速度1.5圈/分跑起来\n B = Ant(\"蚂蚁B\", 1.5)\n\n # 创建蚂蚁C,让蚂蚁A以速度2圈/分跑起来\n C = Ant(\"蚂蚁C\", 2)\n\n # 创建蚂蚁D,让蚂蚁D以速度2.5圈/分跑起来\n D = Ant(\"蚂蚁D\", 2.5)\n\n ant = [A, B, C, D]\n run_time = float(input(\"请输入蚂蚁跑步的时间:\"))\n\n for i in ant:\n if i == A:\n for temp in range(1, 4):\n count_time(i, ant, temp, run_time, total_time)\n\n elif i == B:\n for temp in range(2, 4):\n count_time(i, ant, temp, run_time, total_time)\n\n elif i == C:\n for temp in range(3, 4):\n count_time(i, ant, temp, run_time, total_time)\n\n for i in total_time:\n\n num += i\n\n print(\"在%s分钟后四只蚂蚁两两相遇的次数为:%s\" % (run_time, num))\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"面向对象/相遇问题/01-蚂蚁跑圈.py","file_name":"01-蚂蚁跑圈.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"393645276","text":"import sys\nimport os\nfrom shutil import copyfile\nimport unittest\nfrom click.testing import CliRunner\nsys.path.append(\"../scripts\")\nimport srcget\nfrom srcget import _make_dest\n\nclass TestSrcGet(unittest.TestCase):\n\n def setUp(self):\n runner = CliRunner()\n result = runner.invoke(srcget.init)\n self.assertEqual(result.exit_code, 0)\n # Use the mokecppsrc.json file\n os.remove('cppsrc.json')\n copyfile('mokecppsrc.json', 'cppsrc.json')\n\n def test_init(self):\n self.assertTrue( os.path.exists('cppsrc.json'))\n\n def test_make_dest(self):\n destFiles = _make_dest(['single_include/catch.hpp'], 'thirdParty')\n self.assertListEqual(destFiles, ['thirdParty/catch.hpp'])\n\n def test_install(self):\n runner = CliRunner()\n result = runner.invoke(srcget.install)\n self.assertEqual(result.exit_code, 0)\n self.assertTrue (os.path.exists('thirdParty/catch/catch.hpp'))\n self.assertTrue (os.path.exists('thirdParty/cliarg/include/cliapp.h'))\n self.assertTrue (os.path.exists('thirdParty/cliarg/include/clicmd.h'))\n self.assertTrue (os.path.exists('thirdParty/cliarg/src/cliapp.cpp'))\n self.assertTrue (os.path.exists('thirdParty/cliarg/src/clicmd.cpp'))\n\n def tearDown(self):\n os.remove('cppsrc.json')\n\nif __name__ == '__main__':\n unittest.main()\n\n\n","sub_path":"tests/test_srcget.py","file_name":"test_srcget.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"216657954","text":"sandwich_orders = ['pastrami','tuna','italian','pastrami','roast beef', 'italian',\n 'pastrami', 'italian']\nfinished_sandwiches = []\n\n# Remove the pastrami hoagies\nprint(\"The shop has run out of Pastrami Hoagies.\")\nwhile('pastrami' in sandwich_orders):\n sandwich_orders.remove('pastrami')\n\nwhile sandwich_orders:\n current_sandwich = sandwich_orders.pop()\n print(\"I made you a \" + current_sandwich.title() + \" Hoagie!\")\n finished_sandwiches.append(current_sandwich)\n\n# Print out the list of all completed sandwiches.\nprint(\"\\nCompleted sandwiches:\")\nfor sandwich in finished_sandwiches:\n print(sandwich.title() + \" Hoagie.\")\n\n# Print out a message that there are no completed pastrami sandwiches\nif 'pastrami' not in finished_sandwiches:\n print(\"There are no completed Pastrami Hoagies.\")","sub_path":"ch7/pastrami.py","file_name":"pastrami.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"513727724","text":"import PyInstaller.__main__\r\nimport requests\r\nimport os\r\nimport zipfile\r\nimport sys\r\nfrom argparse import ArgumentParser\r\n\r\n\r\ndef getTorExpertBundle():\r\n\t# create directory for the tor expert bundle\r\n\tos.mkdir('torbundle')\r\n\tos.chdir('torbundle')\r\n\t\r\n\t# download tor expert bundle\r\n\ttorURL = 'https://www.torproject.org/dist/torbrowser/10.0.17/tor-win32-0.4.5.8.zip'\r\n\tfileData = requests.get(torURL, allow_redirects=True)\r\n\r\n\t# write downloaded tor expert bundle\r\n\ttry:\r\n\t\tfile = open('tor.zip', 'wb')\r\n\t\tfile.write(fileData.content)\r\n\texcept Exception as error:\r\n\t\tprint('[-] Error while writing tor expert bundle: {}'.format(error))\r\n\t\tsys.exit(1)\r\n\telse:\r\n\t\tprint('[*] Wrote tor expert bundle to file')\r\n\t\r\n\t# unzip tor expert bundle\r\n\ttry:\r\n\t\tfile = zipfile.ZipFile('tor.zip')\r\n\t\tfile.extractall('.')\r\n\texcept Exception as error:\r\n\t\tprint(\"[-] Error while unpacking tor library: {}\".format('error'))\r\n\t\tsys.exit(1)\r\n\telse:\r\n\t\tprint(\"[*] Unpacked Tor expert bundle\")\r\n\r\n\t# change directory back to \\client\r\n\tos.chdir('..')\r\n\r\ndef parse_args():\r\n\tparser = ArgumentParser(description='Python3 Tor Rootkit Client')\r\n\tparser.add_argument('onion', type=str, help='The remote onion address of the listener.')\r\n\tparser.add_argument('port', type=int, help='The remote hidden service port of the listener.')\r\n\targs = parser.parse_args()\r\n\treturn args.onion, args.port\r\n\r\n\r\nif __name__ == '__main__':\r\n\tonion, port = parse_args()\r\n\t# replace the onion and port line in client.py,\r\n\t# since if havent found a more elegant way to do this yet.\r\n\tlines = open('client.py').read().splitlines()\r\n\t# onion address is defined in line 6\r\n\tlines[5] = 'onion = \"{}\"'.format(onion)\r\n\t# onion port is defined in line 7\r\n\tlines[6] = 'port = {}'.format(port)\r\n\t# write modified script to file\r\n\topen('client.py','w').write('\\n'.join(lines))\r\n\t# dont download everytime\r\n\tif not os.path.isdir('torbundle'):\r\n\t\tgetTorExpertBundle()\r\n\r\n\tPyInstaller.__main__.run([\r\n\t 'client.py',\r\n\t '--onefile',\r\n\t '--add-data=torbundle;torbundle'\r\n\t])\r\n","sub_path":"client/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"277343332","text":"\n\n\ndef getDirectory(datafolder):\n\timport os\n\tdata_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", datafolder)\n\treturn data_dir\n\ndef getFiles(filepattern,topdir):\n import os\n import fnmatch\n for path, dirlist, filelist in os.walk(topdir):\n for name in fnmatch.filter(filelist,filepattern):\n yield os.path.join(path,name)\n\ndef openFiles(filenames):\n import gzip, bz2\n for name in filenames:\n if name.endswith(\".gz\"):\n yield gzip.open(name)\n elif name.endswith(\".bz2\"):\n yield bz2.BZ2File(name)\n else:\n yield open(name)\n\ndef streamFiles(sources):\n\tfor s in sources:\n\t\tlinenumber = -1\n\t\tfor item in s:\n\t\t\tlinenumber +=1\n\t\t\tif linenumber == 0:\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tyield item\n","sub_path":"backend/data_eng/calendar/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"15227785","text":"from qcp import converters, utils\nfrom pathlib import Path\nimport pytest\nimport json\n\n\n@pytest.mark.parametrize(\"src\", utils.get_project_root(\"tests\", \"test_Converter\").glob(\"*\"))\ndef test_OggConverter(tmp_path, src):\n \"\"\"OggConverter converts src to .ogg\"\"\"\n dst = Path(tmp_path.joinpath(src.stem + \".ogg\"))\n\n co = converters.OggConverter()\n\n assert src.exists()\n assert not dst.exists()\n co.run(src, dst)\n assert src.exists()\n assert dst.exists()\n\n\ndef test_serialize_OggConverter_to_json():\n \"\"\"OggConverter can be serialized and unserialized\"\"\"\n co1 = converters.OggConverter(bitrate=\"123k\")\n cos = co1.to_dict()\n co2 = converters.from_json(json.dumps(cos))\n\n assert co1 == co2\n assert co2.bitrate == \"123k\"\n","sub_path":"tests/test_converters.py","file_name":"test_converters.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"26305153","text":"import csv\nimport json\nimport pandas as pd\nimport sys, getopt, pprint\nimport os\nfrom pymongo import MongoClient\n#CSV to JSON Conversion\npath = os.getcwd() + \"/data/car.data\"\ncsvfile = open(path, 'r')\nreader = csv.DictReader( csvfile )\nnext(reader) # Skip header row.\nmongo_client=MongoClient()\ndb=mongo_client.car3\ndb.segment.drop()\nheader= ['buying','maint','doors','persons','lug_boot','safety','class']\n\nfor i in range(1,7):\n\n for each in reader:\n row={}\n for field in header:\n row[field]=each[field]\n\n db.segment.insert_one(row)\n csvfile.seek(0)\n next(reader) # Skip header row.","sub_path":"CaseStudy_KNN/LoadData_in_Mongo.py","file_name":"LoadData_in_Mongo.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"23903207","text":"import subprocess\nimport logging\n\nfrom types import SimpleNamespace\nfrom pathlib import Path\n\nfrom jinja2 import Environment, FileSystemLoader\nfrom ops.framework import (\n Object,\n StoredState,\n)\n\nfrom tcp_lb import BalancingAlgorithm\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass HaproxyInstanceManager(Object):\n\n _stored = StoredState()\n HAPROXY_ENV_FILE = Path('/etc/default/haproxy')\n\n def __init__(self, charm, key, tcp_backend_manager, bind_addresses=None):\n super().__init__(charm, key)\n self.tcp_backend_manager = tcp_backend_manager\n self.tcp_pool_adapter = TCPLoadBalancerPoolAdapter(\n self.tcp_backend_manager.pools,\n bind_addresses,\n )\n\n self._stored.set_default(is_started=False)\n self.haproxy_conf_file = Path(f'/etc/haproxy/juju-{self.model.app.name}.cfg')\n\n @property\n def is_started(self):\n return self._stored.is_started\n\n def install(self):\n self._install_haproxy()\n self._update_haproxy_env_file()\n\n def _install_haproxy(self):\n logger.info('Installing the haproxy package')\n subprocess.check_call(['apt', 'update'])\n subprocess.check_call(['apt', 'install', '-yq', 'haproxy'])\n\n def _update_haproxy_env_file(self):\n \"\"\"Update the maintainer-provided environment file.\n\n This is done to include the config rendered by us in addition to\n the default config provided by the package.\n \"\"\"\n ctxt = {'haproxy_app_config': self.haproxy_conf_file}\n env = Environment(loader=FileSystemLoader('templates'))\n template = env.get_template('haproxy.env.j2')\n rendered_content = template.render(ctxt)\n self.HAPROXY_ENV_FILE.write_text(rendered_content)\n self.haproxy_conf_file.write_text('')\n\n def start(self):\n if not self._stored.is_started:\n logger.info('Starting the haproxy service')\n self._run_start()\n self._stored.is_started = True\n\n def _run_start(self):\n subprocess.check_call(['systemctl', 'start', 'haproxy'])\n\n def stop(self):\n if not self._stored.is_started:\n logger.info('Stopping the haproxy service')\n subprocess.check_call(['systemctl', 'stop', 'haproxy'])\n self.state.is_started = False\n\n def uninstall(self):\n logger.info('Uninstalling the haproxy service')\n subprocess.check_call(['apt', 'purge', '-yq', 'haproxy'])\n\n def reconfigure(self):\n logger.info('Reconfiguring the haproxy service')\n self._do_reconfigure()\n self._run_restart()\n\n def _run_restart(self):\n logger.info('Restarting the haproxy service')\n subprocess.check_call(['systemctl', 'restart', 'haproxy'])\n\n def _do_reconfigure(self):\n logger.info('Rendering the haproxy config file')\n env = Environment(loader=FileSystemLoader('templates'))\n template = env.get_template('haproxy.conf.j2')\n\n listen_sections = self.tcp_pool_adapter.listen_sections\n rendered_content = template.render({'listen_sections': listen_sections})\n self.haproxy_conf_file.write_text(rendered_content)\n\n\nclass TCPLoadBalancerPoolAdapter:\n \"\"\"Provides a way to transform interface data structures into haproxy config.\"\"\"\n\n # A mapping of interface-specific load-balancing algorithms to the ones\n # specific to the haproxy config.\n BALANCING_ALGORITHMS = {\n BalancingAlgorithm.ROUND_ROBIN: 'roundrobin',\n BalancingAlgorithm.LEAST_CONNECTIONS: 'leastconn',\n BalancingAlgorithm.SOURCE_IP: 'source',\n }\n\n def __init__(self, backend_pools, bind_addresses):\n self._backend_pools = backend_pools\n self._bind_addresses = bind_addresses\n\n @property\n def listen_sections(self):\n sections = []\n for pool in self._backend_pools:\n sections.append(self._process_pool(pool))\n return sections\n\n def _process_pool(self, pool):\n\n socket_specs = self._bind_socket_specs(self._bind_addresses, pool.listener.port)\n socket_specs_str = ','.join([str(spec) for spec in socket_specs])\n listen_section = SimpleNamespace(\n name=pool.listener.name,\n socket_specs_str=socket_specs_str,\n mode='tcp',\n balance=self.BALANCING_ALGORITHMS[pool.listener.balancing_algorithm],\n servers=self._server_specs(pool.members),\n )\n return listen_section\n\n def _bind_socket_specs(self, addresses, port):\n \"\"\"Returns a list of BindSocketSpec instances.\n\n :param list addresses: a list of addresses to use for socket binding.\n :param str port: a port to use for binding sockets.\n \"\"\"\n socket_specs = []\n if addresses is None:\n socket_specs.append(BindSocketSpec('', port))\n else:\n for address in addresses:\n socket_specs.append(BindSocketSpec(address, port))\n return socket_specs\n\n def _server_specs(self, backends):\n server_specs = []\n for backend in backends:\n server_specs.append(ServerSpec(\n name=backend.name,\n port=backend.port,\n address=backend.address,\n check_port=backend.monitor_port,\n weight=backend.weight,\n ))\n return server_specs\n\n\nclass BindSocketSpec(SimpleNamespace):\n\n def __init__(self, address, port_range):\n \"\"\"\n :param str address: an address accepted by the haproxy bind directive\n which can be an IPv4, IPv6, unix socket, abstract namespace or file\n descriptor.\n :param str port_range: a port or range of ports: [-]\n \"\"\"\n super().__init__(address=address, port_range=port_range)\n\n def __str__(self):\n return f'{self.address}:{self.port_range}'\n\n\nclass ServerSpec(SimpleNamespace):\n\n def __init__(self, name, address, port, check_port=None, weight=None):\n self._check_port = check_port\n super().__init__(name=name, address=address, port=port, weight=weight)\n\n @property\n def check_port(self):\n return self._check_port if self._check_port is not None else self.port\n\n def __str__(self):\n s = f'server {self.name} {self.address}:{self.port} check port {self.check_port}'\n if self.weight is not None:\n s += f' weight {self.weight}'\n return s\n","sub_path":"src/haproxy_instance_manager.py","file_name":"haproxy_instance_manager.py","file_ext":"py","file_size_in_byte":6437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"32120061","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\nif len(sys.argv) > 1:\n fname = sys.argv[1]\nelse:\n fname = 'cogging_measure_final_a_4'\ndata_raw = np.load(fname+'.npy')\n\ndata = data_raw[0::16]\n# data = np.roll(data, 256)\n\nencoder_cpr = 8192/16\nstator_slots = 12\npole_pairs = 7\n\nN = data.size\nfft = np.fft.rfft(data)\nfreq = np.fft.rfftfreq(N, d=1./encoder_cpr)\n\nharmonics = [0]\nharmonics += [(i+1)*stator_slots for i in range(pole_pairs)]\nharmonics += [pole_pairs]\nharmonics += [(i+1)*2*pole_pairs for i in range(int(stator_slots/4))]\n\nfft_sparse = fft.copy()\nindicies = np.arange(fft_sparse.size)\nmask = [i not in harmonics for i in indicies]\nfft_sparse[mask] = 0.0\ninterp_data = np.fft.irfft(fft_sparse, n = 8192) * 16\n\n#%%\n\nplt.figure(figsize=(14, 7))\n# plt.subplot(3, 1, 1)\nplt.plot(np.arange(0, 8192, 16), data, label='raw')\nplt.plot(interp_data, label='selected harmonics IFFT')\nplt.title('cogging map')\nplt.xlabel('counts')\nplt.ylabel('A')\nplt.legend(loc='best')\n# plt.ylim([-3, 3])\n\nplt.savefig(fname)\nnp.save(fname+'_interp.npy', interp_data)\n#plt.figure()\n# plt.subplot(3, 1, 2)\n# plt.stem(freq, np.abs(fft)/N, label='raw')\n# plt.stem(freq[harmonics], np.abs(fft_sparse[harmonics])/N, markerfmt='ro', label='selected harmonics')\n# plt.title('cogging map spectrum')\n# plt.xlabel('cycles/turn')\n# plt.ylabel('A')\n# plt.legend(loc='best')\n\n# #plt.figure()\n# plt.subplot(3, 1, 3)\n# plt.stem(freq, np.abs(fft)/N, label='raw')\n# plt.stem(freq[harmonics], np.abs(fft_sparse[harmonics])/N, markerfmt='ro', label='selected harmonics')\n# plt.title('cogging map spectrum')\n# plt.xlabel('cycles/turn')\n# plt.ylabel('A')\n# plt.legend(loc='best')\n\nplt.show()","sub_path":"analysis/cogging_torque/coggingmap_analysis.py","file_name":"coggingmap_analysis.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"298340721","text":"from django.db import connection\nimport pandas as pd\nfrom Bigflow.Master.Model import mVariable\nimport json\n\n\nclass JV(mVariable.variable):\n def print_parameters(sp_name, parameters):\n pass\n def jv_process_set_model(self):\n cursor = connection.cursor()\n parameters = (self.action, self.type, self.filter, self.classification, self.create_by, '')\n\n JV.print_parameters(\"sp_JVProcess_Set\", parameters);\n\n cursor.callproc('sp_JVProcess_Set', parameters)\n cursor.execute('select @_sp_JVProcess_Set_5')\n sp_out_message = cursor.fetchall()\n return {\"MESSAGE\": sp_out_message[0]}\n\n def jv_process_get_model(self):\n cursor = connection.cursor()\n parameters = (self.action, self.type, self.filter, self.classification, '')\n\n JV.print_parameters(\"sp_JVProcess_Get\", parameters);\n if(self.type!=\"JV_FIND_ALL\"):\n cursor.callproc('sp_JVProcess_Get', parameters)\n columns = [x[0] for x in cursor.description]\n rows = cursor.fetchall()\n cursor.execute('select @_sp_JVProcess_Get_4')\n outmsg_sp = cursor.fetchone()\n rows = list(rows)\n jv_data = pd.DataFrame(rows, columns=columns)\n return jv_data\n elif(self.type==\"JV_FIND_ALL\"):\n try:\n cursor.callproc('sp_JVProcess_Get', parameters)\n columns = [x[0] for x in cursor.description]\n rows = cursor.fetchall()\n cursor.execute('select @_sp_JVProcess_Get_4')\n outmsg_sp = cursor.fetchone()\n rows = list(rows)\n jv_data = pd.DataFrame(rows, columns=columns)\n my = jv_data.get(\"@finaldata\")[0]\n item = json.loads(my)\n r = str(item).replace(\"'\", '')\n data = json.loads(r)\n jv_data = pd.DataFrame(data)\n return jv_data\n except:\n cursor.callproc('sp_JVProcess_Get', parameters)\n cursor.execute('select @_sp_JVProcess_Get_4')\n outmsg_sp = cursor.fetchone()\n rows = list(outmsg_sp)\n jv_data = pd.DataFrame(rows)\n return jv_data\n\n def get_bank_details(self):\n cursor = connection.cursor()\n parameters = (self.action, self.type, self.filter, self.classification, '');\n\n JV.print_parameters(\"sp_APProcess_Get\", parameters)\n\n cursor.callproc('sp_APProcess_Get', parameters)\n columns = [x[0] for x in cursor.description]\n rows = cursor.fetchall()\n rows = list(rows)\n grn_dtl = pd.DataFrame(rows, columns=columns)\n return grn_dtl\n\n\n\n\n","sub_path":"Bigflow/JV/Model/mJV.py","file_name":"mJV.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"227869626","text":"from django.urls import path\r\n\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n path('', views.signIn, name=\"LogIn\"),\r\n path('stationList', views.stationList, name=\"stationList\"),\r\n path('LogOut', views.LogOut, name=\"LogOut\"),\r\n path('signUp', views.signUp, name=\"signUp\"),\r\n path('transportationList/', views.transportationList, name=\"transportationList\"),\r\n path('userList', views.userList, name=\"userList\"),\r\n path('removeUser', views.removeUser, name=\"removeUser\"),\r\n path('addTr_station', views.addTr_station, name=\"addTr_station\"),\r\n path('editTr_station/', views.editTr_station, name=\"editTr_station\"),\r\n path('removeTr_station', views.removeTr_station, name=\"removeTr_station\"),\r\n path('addTransportation', views.addTransportation, name=\"addTransportation\"),\r\n path('editTransportation/', views.editTransportation, name=\"editTransportation\"),\r\n path('removeTransportation', views.removeTransportation, name=\"removeTransportation\"),\r\n]\r\n","sub_path":"coursework/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"95013847","text":"#encoding='utf-8'\nimport pandas as pd\nimport re\nimport numpy as np\nallphones=pd.read_csv(\"H:\\\\毕业设计\\\\tianmaoshangchengphone(1-19)3.29.csv\",encoding='gbk')\n# print(allphones)\ndata_csv=pd.DataFrame(columns=['brand','product','sales'])\nx=0\n# print(allphones)\n# print(allphones.sort_index(by='sales')) #手机总排行\nbrands=pd.read_csv(\"H:\\\\毕业设计\\\\phonebrands.csv\",encoding='gbk')\nfor m in allphones.index:\n product=allphones.loc[m,'product']\n for n in brands.index:\n if(re.search(brands.loc[n,'brand'],product)):\n allphones.loc[m,'brand']=brands.loc[n,'brand']\n break\n# print(allphones)\ndef totlerank(phones): #手机品牌总排行\n rank1=phones.sort_index(by='sales',ascending=False).reset_index()\n return rank1\n\ndef brandrank(phones): #手机按品牌排行\n rank2=phones['sales'].groupby(phones['brand'])\n rank2=rank2.aggregate(np.sum).reset_index().sort(['sales'],ascending=False).reset_index()\n return rank2\n\ndef brandinternaorank(phones): #手机品牌内部排行\n rank3=phones['sales'].groupby([phones['brand'],phones['product'],phones['price']])\n rank3=rank3.sum()\n\n rank3=pd.DataFrame(rank3).reset_index()\n return rank3\ndef pricerangerank(phones): #价格区间排行\n for m in phones.index:\n if(phones.loc[m,'price']<500):\n phones.loc[m,'pricerange']='0~500'\n elif(phones.loc[m,'price']<1000):\n phones.loc[m,'pricerange']='500~1000'\n elif (phones.loc[m, 'price'] < 1500):\n phones.loc[m, 'pricerange'] = '1000~1500'\n elif (phones.loc[m, 'price'] < 2000):\n phones.loc[m, 'pricerange'] = '1500~2000'\n elif (phones.loc[m, 'price'] < 3000):\n phones.loc[m, 'pricerange'] = '2000~3000'\n elif (phones.loc[m, 'price'] < 4000):\n phones.loc[m, 'pricerange'] = '3000~4000'\n else :\n phones.loc[m, 'pricerange'] = '4000以上'\n rank4=phones['sales'].groupby([phones['pricerange'],phones['brand']])\n rank4=rank4.sum()\n rank4 = pd.DataFrame(rank4).reset_index()\n return(rank4)\nif __name__ == '__main__':\n rank1=totlerank(allphones)\n print(rank1[0:50])\n rank2=brandrank(allphones)\n print(rank2)\n # print(rank2['brand'][0:15])\n rank3=brandinternaorank(allphones)\n print(rank3)\n # for m in rank2['brand'][0:15]:\n # print(m)\n # for n in rank3.index:\n # if(rank3.loc[n,'brand']==m):\n # print(rank3.loc[[n]]\n rank3.to_csv(\"C:\\\\Users\\\\washingli\\\\Desktop\\\\手机品牌内部排行.csv\")\n rank4=pricerangerank(allphones)\n print(rank4)\n\n\n","sub_path":"phonespider/phoneanalysis.py","file_name":"phoneanalysis.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"501672672","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport multiprocessing\nimport time\n\nimport numpy as np\n\nimport tensorflow as tf\nimport tensorlayer as tl\nfrom tensorlayer.layers import (BatchNorm, Conv2d, Dense, Flatten, Input, LocalResponseNorm, MaxPool2d)\nfrom tensorlayer.models import Model\n\n# enable debug logging\ntl.logging.set_verbosity(tl.logging.DEBUG)\ntl.logging.set_verbosity(tl.logging.DEBUG)\n\n\n# define the network\ndef get_model(inputs_shape):\n # self defined initialization\n W_init = tl.initializers.truncated_normal(stddev=5e-2)\n W_init2 = tl.initializers.truncated_normal(stddev=0.04)\n b_init2 = tl.initializers.constant(value=0.1)\n\n # build network\n ni = Input(inputs_shape)\n nn = Conv2d(64, (5, 5), (1, 1), padding='SAME', act=tf.nn.relu, W_init=W_init, b_init=None, name='conv1')(ni)\n nn = MaxPool2d((3, 3), (2, 2), padding='SAME', name='pool1')(nn)\n nn = LocalResponseNorm(depth_radius=4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name=\"norm1\")(nn)\n\n nn = Conv2d(64, (5, 5), (1, 1), padding='SAME', act=tf.nn.relu, W_init=W_init, b_init=None, name='conv2')(nn)\n nn = LocalResponseNorm(depth_radius=4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name=\"norm2\")(nn)\n nn = MaxPool2d((3, 3), (2, 2), padding='SAME', name='pool2')(nn)\n\n nn = Flatten(name='flatten')(nn)\n nn = Dense(384, act=tf.nn.relu, W_init=W_init2, b_init=b_init2, name='dense1relu')(nn)\n nn = Dense(192, act=tf.nn.relu, W_init=W_init2, b_init=b_init2, name='dense2relu')(nn)\n nn = Dense(10, act=None, W_init=W_init2, name='output')(nn)\n\n M = Model(inputs=ni, outputs=nn, name='cnn')\n return M\n\n\ndef get_model_batchnorm(inputs_shape):\n # self defined initialization\n W_init = tl.initializers.truncated_normal(stddev=5e-2)\n W_init2 = tl.initializers.truncated_normal(stddev=0.04)\n b_init2 = tl.initializers.constant(value=0.1)\n\n # build network\n ni = Input(inputs_shape)\n nn = Conv2d(64, (5, 5), (1, 1), padding='SAME', W_init=W_init, b_init=None, name='conv1')(ni)\n nn = BatchNorm(decay=0.99, act=tf.nn.relu, name='batch1')(nn)\n nn = MaxPool2d((3, 3), (2, 2), padding='SAME', name='pool1')(nn)\n\n nn = Conv2d(64, (5, 5), (1, 1), padding='SAME', W_init=W_init, b_init=None, name='conv2')(nn)\n nn = BatchNorm(decay=0.99, act=tf.nn.relu, name='batch2')(nn)\n nn = MaxPool2d((3, 3), (2, 2), padding='SAME', name='pool2')(nn)\n\n nn = Flatten(name='flatten')(nn)\n nn = Dense(384, act=tf.nn.relu, W_init=W_init2, b_init=b_init2, name='dense1relu')(nn)\n nn = Dense(192, act=tf.nn.relu, W_init=W_init2, b_init=b_init2, name='dense2relu')(nn)\n nn = Dense(10, act=None, W_init=W_init2, name='output')(nn)\n\n M = Model(inputs=ni, outputs=nn, name='cnn')\n return M\n\n\n# get the network\nnet = get_model([None, 24, 24, 3])\n\n# training settings\nbatch_size = 128\nn_epoch = 50000\nlearning_rate = 0.0001\nprint_freq = 5\n# init_learning_rate = 0.1\n# learning_rate_decay_factor = 0.1\n# num_epoch_decay = 350\n\ntrain_weights = net.trainable_weights\n# learning_rate = tf.Variable(init_learning_rate)\noptimizer = tf.optimizers.Adam(learning_rate)\n\n\ndef _fn_train(img, target):\n # 1. Randomly crop a [height, width] section of the image.\n img = tl.prepro.crop(img, 24, 24, False)\n # 2. Randomly flip the image horizontally.\n img = tl.prepro.flip_axis(img, is_random=True)\n # 3. Subtract off the mean and divide by the variance of the pixels.\n img = tl.prepro.samplewise_norm(img)\n target = np.reshape(target, ())\n return img, target\n\n\ndef _fn_test(img, target):\n # 1. Crop the central [height, width] of the image.\n img = tl.prepro.crop(img, 24, 24)\n # 2. Subtract off the mean and divide by the variance of the pixels.\n img = tl.prepro.samplewise_norm(img)\n img = np.reshape(img, (24, 24, 3))\n target = np.reshape(target, ())\n return img, target\n\n\n# dataset API and augmentation\ntrain_ds = tl.data.CIFAR10(train_or_test='train', shape=(-1, 32, 32, 3))\ntrain_dl = tl.data.Dataloader(train_ds, transforms=[_fn_train], shuffle=True,\n batch_size=batch_size, output_types=(np.float32, np.int32))\ntest_ds = tl.data.CIFAR10(train_or_test='test', shape=(-1, 32, 32, 3))\ntest_dl = tl.data.Dataloader(test_ds, transforms=[_fn_test], batch_size=batch_size)\n\nfor epoch in range(n_epoch):\n start_time = time.time()\n\n train_loss, train_acc, n_iter = 0, 0, 0\n for X_batch, y_batch in train_dl:\n net.train()\n\n with tf.GradientTape() as tape:\n # compute outputs\n _logits = net(X_batch)\n # compute loss and update model\n _loss_ce = tl.cost.cross_entropy(_logits, y_batch, name='train_loss')\n _loss_L2 = 0\n # for p in tl.layers.get_variables_with_name('relu/W', True, True):\n # _loss_L2 += tl.cost.lo_regularizer(1.0)(p)\n _loss = _loss_ce + _loss_L2\n # print(_loss)\n\n grad = tape.gradient(_loss, train_weights)\n optimizer.apply_gradients(zip(grad, train_weights))\n\n train_loss += _loss\n train_acc += np.mean(np.equal(np.argmax(_logits, 1), y_batch))\n n_iter += 1\n\n # use training and evaluation sets to evaluate the model every print_freq epoch\n if epoch + 1 == 1 or (epoch + 1) % print_freq == 0:\n\n print(\"Epoch {} of {} took {}\".format(epoch + 1, n_epoch, time.time() - start_time))\n\n print(\" train loss: {}\".format(train_loss / n_iter))\n print(\" train acc: {}\".format(train_acc / n_iter))\n\n net.eval()\n\n val_loss, val_acc, n_iter = 0, 0, 0\n for X_batch, y_batch in test_dl:\n _logits = net(X_batch) # is_train=False, disable dropout\n val_loss += tl.cost.cross_entropy(_logits, y_batch, name='eval_loss')\n val_acc += np.mean(np.equal(np.argmax(_logits, 1), y_batch))\n n_iter += 1\n print(\" val loss: {}\".format(val_loss / n_iter))\n print(\" val acc: {}\".format(val_acc / n_iter))\n\n # FIXME : how to apply lr decay in eager mode?\n # learning_rate.assign(tf.train.exponential_decay(init_learning_rate, epoch, num_epoch_decay,\n # learning_rate_decay_factor))\n\n# use testing data to evaluate the model\nnet.eval()\ntest_loss, test_acc, n_iter = 0, 0, 0\nfor X_batch, y_batch in test_dl:\n _logits = net(X_batch)\n test_loss += tl.cost.cross_entropy(_logits, y_batch, name='test_loss')\n test_acc += np.mean(np.equal(np.argmax(_logits, 1), y_batch))\n n_iter += 1\nprint(\" test loss: {}\".format(test_loss / n_iter))\nprint(\" test acc: {}\".format(test_acc / n_iter))\n","sub_path":"examples/basic_tutorials/tutorial_cifar10_cnn_static_dataloader.py","file_name":"tutorial_cifar10_cnn_static_dataloader.py","file_ext":"py","file_size_in_byte":6613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"468806426","text":"# Tai Sakuma \nimport sys\nimport pytest\n\ntry:\n import unittest.mock as mock\nexcept ImportError:\n import mock\n\nfrom alphatwirl.progressbar import ProgressReport\nfrom alphatwirl.progressbar import ProgressReporter\n\n##__________________________________________________________________||\n@pytest.fixture()\ndef mock_queue():\n return mock.Mock()\n\n@pytest.fixture()\ndef mock_time(monkeypatch):\n ret = mock.Mock()\n mock_time_module = mock.Mock()\n mock_time_module.time = ret\n module = sys.modules['alphatwirl.progressbar.ProgressReporter']\n monkeypatch.setattr(module, 'time', mock_time_module)\n return ret\n\n@pytest.fixture()\ndef obj(mock_queue, mock_time):\n ret = ProgressReporter(mock_queue)\n return ret\n\n##__________________________________________________________________||\ndef test_repr(obj):\n repr(obj)\n\n##__________________________________________________________________||\ndef test_report_need_to_report(obj, monkeypatch, mock_queue, mock_time):\n current_time = 15324.345\n taskid = 234\n mock_time.return_value = current_time\n monkeypatch.setattr(obj, '_need_to_report', mock.Mock(return_value=True))\n report = ProgressReport('task1', 0, 10, taskid)\n obj.report(report)\n assert [mock.call(report)] == mock_queue.put.call_args_list\n assert {taskid: current_time} == obj.last_time\n\ndef test_report_no_need_to_report(obj, monkeypatch, mock_queue, mock_time):\n current_time = 15324.345\n taskid = 234\n mock_time.return_value = current_time\n monkeypatch.setattr(obj, '_need_to_report', mock.Mock(return_value=False))\n report = ProgressReport('task1', 0, 10, taskid)\n obj.report(report)\n assert [ ] == mock_queue.put.call_args_list\n assert { } == obj.last_time\n\n##__________________________________________________________________||\nparams = [\n pytest.param(ProgressReport('task1', 0, 10, 1), {}, 10.0, True),\n pytest.param(ProgressReport('task1', 10, 10, 1), {}, 10.0, True),\n pytest.param(ProgressReport('task1', 0, 10, 1), {1: 10.0}, 10.0, True),\n pytest.param(ProgressReport('task1', 1, 10, 1), {1: 10.0}, 30.0, True),\n pytest.param(ProgressReport('task1', 1, 10, 1), {1: 10.0}, 15.0, False),\n]\nparam_names = (\n 'report, last_time, current_time, '\n 'expected'\n)\n\n@pytest.mark.parametrize(param_names, params)\ndef test_need_to_report(\n obj, mock_time, report,\n last_time, current_time, expected):\n\n obj.interval = 10\n obj.last_time = last_time\n mock_time.return_value = current_time\n assert expected == obj._need_to_report(report)\n\n##__________________________________________________________________||\n","sub_path":"tests/unit/progressbar/test_ProgressReporter.py","file_name":"test_ProgressReporter.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"618159115","text":"import sys\nfrom Question import Question\nfrom lib.db.RedisHelper import redisHelper\n\n\nreload(sys)\nsys.setdefaultencoding('UTF8')\n\n\nclass User(object):\n def __init__(self, people):\n self.max_count = 50\n self.user_id = people.id\n print(self.user_id)\n self.user_name = people.name\n print(self.user_name)\n self.answer_time_list = self.get_answer_time_list(people)\n print(self.answer_time_list)\n self.article_time_list = self.get_article_time_list(people)\n print(self.article_time_list)\n self.crawl_comment_data(people)\n print(\"finish crawl comment data\")\n self.favorite_column_list = self.get_favorite_column_list(people)\n for column in self.favorite_column_list:\n print(column)\n self.favorite_topic_list = self.get_favorite_topic_list(people)\n for topic in self.favorite_topic_list:\n print(topic)\n self.question_time_list = self.get_question_time_list(people)\n print(self.question_time_list)\n self.favorite_user_id_list = self.get_favorite_user_id_list(people)\n print(self.favorite_user_id_list)\n self.follower_user_id_list = self.get_follower_user_id_list(people)\n print(self.follower_user_id_list)\n self.live_time_list = self.get_live_time_list(people)\n print(self.live_time_list)\n self.thought_time_list = self.get_thought_time_list(people)\n print(self.thought_time_list)\n self.activity_time_list = self.get_activity_time_list(people)\n print(self.activity_time_list)\n\n def get_answer_time_list(self, people):\n time_set = set()\n count = 0\n for answer in people.answers:\n time_set.add(answer.created_time)\n time_set.add(answer.updated_time)\n count += 1\n if count > self.max_count:\n break\n return list(time_set)\n\n def get_article_time_list(self, people):\n time_set = set()\n count = 0\n for article in people.articles:\n time_set.add(article.updated_time)\n count += 1\n if count > self.max_count:\n break\n return list(time_set)\n\n def crawl_comment_data(self, people):\n print(\"question count: %d\" % people.question_count)\n count = 0\n for question in people.questions:\n Question.handle(question)\n count += 1\n if count > self.max_count:\n break\n print(\"answer count: %d\" % people.answer_count)\n count = 0\n for answer in people.answers:\n Question.handle_answer(answer)\n count += 1\n if count > self.max_count:\n break\n\n def get_comment_time_list(self):\n return redisHelper.get_user_comment(self.user_id)\n\n def get_favorite_column_list(self, people):\n column_list = []\n count = 0\n for favoriate_column in people.following_columns:\n column_list.append(favoriate_column.title)\n count += 1\n if count > self.max_count:\n break\n return column_list\n\n def get_favorite_topic_list(self, people):\n topic_list = []\n count = 0\n for favoriate_topic in people.following_topics:\n topic_list.append(favoriate_topic.name)\n count += 1\n if count > self.max_count:\n break\n return topic_list\n\n def get_question_time_list(self, people):\n time_set = set()\n count = 0\n for question in people.questions:\n time_set.add(question.created_time)\n time_set.add(question.updated_time)\n count += 1\n if count > self.max_count:\n break\n return list(time_set)\n\n def get_favorite_user_id_list(self, people):\n user_list = []\n count = 0\n for user in people.followings:\n user_list.append(user.id)\n count += 1\n if count > self.max_count:\n break\n return user_list\n\n def get_follower_user_id_list(self, people):\n user_list = []\n count = 0\n for user in people.followers:\n user_list.append(user.id)\n count += 1\n if count > self.max_count:\n break\n return user_list\n\n def get_live_time_list(self, people):\n time_list = []\n count = 0\n for live in people.lives:\n time_list.append(live.created_at)\n count += 1\n if count > self.max_count:\n break\n return time_list\n\n def get_thought_time_list(self, people):\n # NO API for this\n return []\n\n def get_activity_time_list(self, people):\n time_list = []\n count = 0\n for activity in people.activities:\n time_list.append(activity.created_time)\n count += 1\n if count > self.max_count:\n break\n return time_list\n\n def __str__(self):\n return \"user_id = %s, user_name = %s, answer_time_list = %s, article_time_list = %s, favorite_column_list = \" \\\n \"%s, favorite_topic_list = %s, question_time_list = %s, favorite_user_id_list = %s, \" \\\n \"follower_user_id_list = %s, live_time_list = %s, thought_time_list = %s, activity_time_list = %s\" % (\n str(self.user_id), str(self.user_name), str(self.answer_time_list), str(self.article_time_list),\n str(self.favorite_column_list), str(self.favorite_topic_list), str(self.question_time_list),\n str(self.favorite_user_id_list), str(self.follower_user_id_list), str(self.live_time_list),\n str(self.thought_time_list), str(self.activity_time_list))\n\n\n\n","sub_path":"lib/model/User.py","file_name":"User.py","file_ext":"py","file_size_in_byte":5754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"317469012","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.6-x86_64/egg/hydro/exceptions.py\n# Compiled at: 2014-11-23 10:45:29\n__author__ = 'moshebasanchig'\n\nclass HydroException(Exception):\n\n def __init__(self, message, errors=None):\n Exception.__init__(self, message)\n self.errors = errors","sub_path":"pycfiles/Hydro-0.1.7-py2.7/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"282481692","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.optimize import curve_fit\nfrom uncertainties import unumpy as unp\nfrom scipy.constants import R\n\n\nRp2, Rz2, U2, I2 = np.genfromtxt('data/messung.txt',unpack=True)\nRp5, Rz5, U5, I5 = np.genfromtxt('data/messung2.txt',unpack=True)\n\nt2 = np.ones(len(Rp2))*150\nt5 = np.ones(len(Rp5))*300\n\nM = 0.0635 # molare Masse\nm = 0.342 # Masse\n\n## combine 2 arrays\n\nRp = np.append(Rp2,Rp5)\nRz = np.append(Rz2,Rz5)\nU = np.append(U2,U5)\nI = np.append(I2,I5)\nt = np.append(t2,t5)\n\n#print(Rp2)\n#print(Rp)\n\n#for Rp, Rz, U, I, t in [[Rp2,Rz2,U2,I2,t2],[Rp5,Rz5,U5,I5,t5]]:\n\n# I = I*1e-3\n\n## add estimated uncertainties to the data\n\nRp = unp.uarray(Rp, np.ones(len(Rp))*0.1)\nRz = unp.uarray(Rz, np.ones(len(Rz))*0.1)\nU = unp.uarray(U, np.ones(len(U))*0.01)\nI = unp.uarray(I, np.ones(len(I))*0.1)*1e-3\nt = unp.uarray(t, np.ones(len(t))*5)\n\n#print(Rp)\n\n## calculate temperature (Kelvin) from resistance\n\ndef R_to_T(R):\n return (0.00134*R**2 + 2.296*R - 243.02) +273.15\n\nTp = R_to_T(Rp)\nTz = R_to_T(Rz)\n\n#print(Tp)\n\n## calculate differnces of temperatures\n\nT_first = Tp[1:]\nT_last = Tp[:-1]\n\nT_delta = -(T_last - T_first)\n\n#print(T_first)\n#print(T_last)\n#print(T_delta)\n\n## delete last elements because there are just n-1 differnces\n\nTp = Tp[:-1]\nTz = Tz[:-1]\nU = U[:-1]\nI = I[:-1]\nt = t[:-1]\n\n## calculate C_p\n\n#print(T_delta[0])\n#print(U[0])\n#print(I[0])\n#print(t[0])\n\nCp = (U*I*t*M)/(T_delta*m)\n\n#print(Cp)\n\n## remove value because it timesteps changed from 2.5 to 5 min\n\nCp = np.delete(Cp, 23)\nTp = np.delete(Tp, 23)\nTz = np.delete(Tz, 23)\nU = np.delete(U, 23)\nI = np.delete(I, 23)\nt = np.delete(t, 23)\n\n## plot C_p\n\nplt.errorbar(unp.nominal_values(Tp),unp.nominal_values(Cp), yerr=unp.std_devs(Cp), fmt='k.', capsize=3, label=r'$C_p$')\nplt.plot([70,310], [3*R , 3*R], \"r-\", label=r'$3 R$' )\nplt.xlim(75,299)\nplt.xlabel(r'$T$ / K')\nplt.ylabel(r'$C_p$ / $\\text{J}\\text{mol}^{-1}\\text{K}^{-1}$')\nplt.legend(loc='best')\nplt.savefig('build/plot1.pdf')\nplt.clf()\n\n## extrapolate alpha\n\nT_alpha = np.linspace(70, 300, 24)\nalpha = np.array([\n 7,8.5,9.75,10.7,11.5,12.1,12.65,13.15,\n 13.6,13.9,14.25,14.5,14.75,14.95,15.2,15.4,\n 15.6,15.75,15.9,16.1,16.25,16.35,16.5,16.65])*1e-6\n\n#print(len(Tp))\n#print(T_alpha)\n#print(unp.nominal_values(Tp))\n#print(alpha)\n\ndef lin(x,a,b):\n return a*x+b\n\nvar1, cov1 = curve_fit(lin, T_alpha[0:7], alpha[0:7])\nerrs1 = np.sqrt(np.diag(cov1))\n\nplt.plot(T_alpha[0:7], alpha[0:7]*1e6, \"b.\")\nplt.plot(T_alpha[0:7], lin(T_alpha[0:7], *var1)*1e6, \"b-\")\nplt.plot(unp.nominal_values(Tp[0:12]), lin(unp.nominal_values(Tp[0:12]), *var1)*1e6, \"k.\")\n\nvar2, cov2 = curve_fit(lin, T_alpha[7:], alpha[7:])\nerrs2 = np.sqrt(np.diag(cov2))\n\nplt.plot(T_alpha[7:], alpha[7:]*1e6, \"r.\")\nplt.plot(T_alpha[7:], lin(T_alpha[7:], *var2)*1e6, \"r-\")\nplt.plot(unp.nominal_values(Tp[12:]), lin(unp.nominal_values(Tp[12:]), *var2)*1e6, \"k.\")\n\nplt.savefig('build/plot2.pdf')\nplt.clf()\n\n## calculate C_v\n\nCv1 = Cp[0:12] - 9*lin(Tp[0:12], *var1)**2*137.8*1e9*7.09*1e-6*Tp[0:12]\nCv2 = Cp[12:] - 9*lin(Tp[12:], *var2)**2*137.8*1e9*7.09*1e-6*Tp[12:]\n\nCv = np.append(Cv1,Cv2)\n\n#print(Cv)\n\n## plot C_v\n\nplt.errorbar(unp.nominal_values(Tp),unp.nominal_values(Cv), yerr=unp.std_devs(Cv), fmt='k.', capsize=3, label=r'$C_v$')\n#plt.plot(unp.nominal_values(Tp),unp.nominal_values(Cp), 'b.', label=r'$C_p$')\nplt.plot([70,310], [3*R , 3*R], \"r-\", label=r'$3 R$' )\nplt.xlim(75,299)\nplt.xlabel(r'$T$ / K')\nplt.ylabel(r'$C_v$ / $\\text{J}\\text{mol}^{-1}\\text{K}^{-1}$')\nplt.legend(loc='best')\nplt.savefig('build/plot3.pdf')\nplt.clf()\n\n## Tabellen\n\ncount = 0\nwhile(count < len(Tp)):\n print(T_delta[count], \"&\", U[count], \"&\", I[count], \"&\", t[count], \"&\", Cp[count], \"\\\\\\\\\")\n count += 1\n\nprint()\n\ncount = 0\nwhile(count < len(Tp[0:12])):\n print(Tp[count], \"&\", Cp[count], \"&\", lin(Tp[count], *var1), \"&\", Cv[count], \"\\\\\\\\\")\n count += 1\n\nwhile(count < len(Tp)):\n print(Tp[count], \"&\", Cp[count], \"&\", lin(Tp[count], *var2), \"&\", Cv[count], \"\\\\\\\\\")\n count += 1\n\nprint()\n\nquo = np.array([4.1,3.3,2.9,2.9,2.7,2.4,2.7,2.7,2.7,2.1,2.1,2.1,2.1,2.2,2.2,1.8,1.8,1.8,1.3,1.8,1.8,1.8])\ndeby_temp = []\ncount = 0\nwhile(count < len(Tp[0:22])):\n deby_temp = np.append(deby_temp, quo[count]*Tp[count])\n print(Cv[count], \"&\",quo[count], \"&\", Tp[count], \"&\", quo[count]*Tp[count], \"\\\\\\\\\")\n count += 1\n\nprint(len(Cp[34:]))\nprint(np.mean(deby_temp))\nprint(np.mean(Cp[34:]))\n###\n","sub_path":"V47 Molwärme/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":4454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"530429757","text":"__author__ = 'wwli'\n\nimport datetime\nimport json\nfrom ebaysdk.finding import Connection as Finding\n\ndef search(name):\n api = Finding(domain = 'svcs.ebay.com', appid = \"WillWagn-eb9e-4f01-92ea-d5962762e053\" )\n\n response = api.execute('findItemsAdvanced', {'keywords': name})\n assert(response.reply.ack == 'Success')\n assert(type(response.reply.timestamp) == datetime.datetime)\n assert(type(response.reply.searchResult.item) == list)\n\n return response\n\nwith open('AllCards.json') as json_file:\n data = json.load(json_file)\n\nkeys = data.keys()\ncards = list(keys)\n\nprint(cards[380])\ntarget = search(cards[380])\n\nfor items in target.reply.searchResult.item:\n print(items)\n\nfor items in target.reply.searchResult.item.next_page:\n print(items)","sub_path":"card_search.py","file_name":"card_search.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"629687216","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[4]:\n\n\nimport pandas as pd\nimport pickle\nimport itertools\nfrom ast import literal_eval\n\n\n# In[5]:\n\n\ngdf = pickle.load(open('/home/osboxes/proj/twitter/trackRetraites/graphdf.pkl', 'rb'))\nfilename = '/home/osboxes/proj/twitter/retraite.data'\n\n\n# In[6]:\n\n\ndef RetrieveTweetsFromLastPoint(filename,LineMemorisied):\n\n # Initialisation\n maliste = []\n errors = 0\n ntweets = 0\n \n # Read New Tweets\n with open(filename) as fp:\n for line in fp:\n ntweets = ntweets + 1 \n if ntweets > LineMemorisied:\n try:\n maliste.append(literal_eval(line))\n except:\n errors = errors + 1\n\n return maliste,errors,ntweets,LineMemorisied\n\n\n# In[7]:\n\n\nmaliste,NewErrors,NewNtweets,NewLineMemorisied = RetrieveTweetsFromLastPoint(filename,0)\n\n\n# In[8]:\n\n\ntdf = pd.DataFrame(maliste)\n\n\n# In[9]:\n\n\na = tdf[[\"USERNAME\",\n \"USERID\",\n \"USERFOLLOWERS\",\n \"USERFNAME\",\n \"USERDESCRIPTION\"]].\\\nrename(columns = {\"USERNAME\" : \"NAME\",\n \"USERID\" : \"ID\",\n \"USERFOLLOWERS\" : \"NFOL\",\n \"USERFNAME\" : \"FNAME\",\n \"USERDESCRIPTION\":\"DESCRIPTION\"})\n\nb = tdf[[\"AUTHORNAME\",\n \"AUTHORID\",\n \"AUTHORFOLLOWERS\",\n \"AUTHORFNAME\",\n \"AUTHORDESCRIPTION\"]].\\\nrename(columns = {\"AUTHORNAME\" : \"NAME\",\n \"AUTHORID\" : \"ID\",\n \"AUTHORFOLLOWERS\" :\"NFOL\",\n \"AUTHORFNAME\":\"FNAME\",\n \"AUTHORDESCRIPTION\":\"DESCRIPTION\"})\n\n\n# In[10]:\n\n\ntdf = pd.concat([a,b],axis=0, sort=False)\ntdf.sort_values(by=\"FNAME\",ascending=False,inplace=True)\ntdf = tdf.drop_duplicates(subset = [\"ID\"])\n\n\n# In[11]:\n\n\nfinal = gdf.merge(tdf,how=\"left\",left_on=\"A\",right_on=\"ID\",).rename(columns = {\"NAME\" : \"ANAME\",\n \"NFOL\":\"ANFOL\",\n \"DESCRIPTION\" : \"ADESCRIPTION\",\"FNAME\":\"AFNAME\"}).drop(columns='ID')\n\nfinal = final.merge(tdf,how=\"left\",left_on=\"B\",right_on=\"ID\").rename(columns = {\"NAME\" : \"BNAME\",\n \"NFOL\":\"BNFOL\",\n \"DESCRIPTION\" : \"BDESCRIPTION\",\"FNAME\":\"BFNAME\"}).drop(columns=['ID'])\n\nfinal.sort_values(by=\"f\",ascending=False,inplace=True)\nfinal = final[final.A != final.B]\nfinal.reset_index(drop=True,inplace=True)\n\n\n# In[12]:\n\n\npickle.dump(final, open('/home/osboxes/proj/twitter/trackRetraites/GraphIdentity.pkl', 'wb'))\n\n\n# In[13]:\n\n\nprint(\"Nombre de links :\",len(final))\n\n\n# In[14]:\n\n\nprint(\"\")\nprint(final[[\"A\",\"B\",\"f\"]].head())\n\n\n# In[15]:\n\n\nfinal.to_csv(\"graph.csv\",index=False)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"trackRetraites/BuildGraph.py","file_name":"BuildGraph.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"469948758","text":"import torch\n\n\n\n\ndef distribution_to_point(predictions):\n pass\n\n\ndef distribution_to_quantile(predictions, quantiles=None, n_quantiles=None):\n assert n_quantiles is None or quantiles is None, \"Cannot specify the quantiles or n_quantiles simultaneously\"\n assert n_quantiles is not None or quantiles is not None, \"Must specify either quantiles or n_quantiles\"\n \n if n_quantiles is not None:\n quantiles = torch.linspace(0, 1, n_quantiles+2)[1:-1]\n if len(quantiles.shape) == 1:\n quantiles = quantiles.unsqueeze(1)\n return predictions.icdf(quantiles).transpose(1, 0)\n\n\ndef distribution_to_interval(predictions, confidence=0.95):\n # Grid search the best interval with the minimum average length \n l_start = 0.0\n r_start = 1-confidence\n with torch.no_grad():\n for iteration in range(2): # Repeat the search procedure to get more finegrained results\n avg_length = torch.zeros(100)\n queried_values = torch.linspace(l_start, r_start, 100)\n for i, c_start in enumerate(queried_values):\n interval = predictions.icdf(torch.tensor([c_start, c_start+confidence]).view(-1, 1))\n avg_length[i] = (interval[1] - interval[0]).mean()\n best_ind = avg_length.argmin()\n l_start = queried_values[max(best_ind - 1, 0)]\n r_start = queried_values[min(best_ind + 1, 99)]\n c_start = (l_start + r_start) / 2.\n return predictions.icdf(torch.tensor([c_start, c_start+confidence]).view(-1, 1)).transpose(1, 0)\n\n\n","sub_path":"torchuq/transform/distribution.py","file_name":"distribution.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"364094983","text":"from flask_sqlalchemy import DeclarativeMeta\nfrom flask import jsonify, json\n\nclass AlchemyEncoder(json.JSONEncoder):\n def default(self, o):\n data = {}\n fields = o.__json__() if hasattr(o, '__json__') else dir(o)\n for field in [f for f in fields if not f.startswith('_') and f not in ['metadata', 'query', 'query_class']]:\n value = o.__getattribute__(field)\n try:\n json.dumps(value)\n data[field] = value\n except TypeError:\n data[field] = None\n return data","sub_path":"src/util/json_encoder.py","file_name":"json_encoder.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"183041855","text":"from __future__ import print_function\n\nimport random\nimport numpy as np\nimport cv2\nimport imutils\nfrom imutils import perspective\nimport json\nimport datetime\nimport argparse\n\nMAX_FEATURES = 500\nGOOD_MATCH_PERCENT = 0.80\n\ndef contadorDeDispositivos():\n\tnameFile = 'counterID.txt'\n\tcounterIdFile = open ( nameFile,\"r\" )\n\tcontagem = counterIdFile.readlines()\n\tcounterIdFile.close()\n\tcounter = int(contagem[-1]) + 1\n\tcounterIdFile.close()\n\tcounterIdFile = open(nameFile, \"w\")\n\tcounterIdFile.write(str(counter))\n\tcounterIdFile.close()\n\treturn counter\n\ndef contorno(imagem,num):\n\t# Calcular a bounding box para o objeto\n\t_orig = imagem.copy()\n\t_box = cv2.minAreaRect(num)\n\t_box = cv2.cv.BoxPoints(_box) if imutils.is_cv2() else cv2.boxPoints(_box)\n\t_box = np.array(_box, dtype=\"int\")\n\t_box = perspective.order_points(_box) # Ordenar os pontos do contorno\n\tcv2.drawContours(_orig, [_box.astype(\"int\")], -1, (0, 255, 0), 1) # Desenhar contorno\n\treturn _box,_orig\n\ndef guardarImagemObjecto(imagem,objectoID,dispositivoID):\n\tcv2.imwrite('Imagens/Objectos/' + dispositivoID +'_'+objectoID+ '.jpg', imagem)\n\ndef guardarImagemDispositivo(imagem,dispositivoID):\n\tcv2.imwrite('Imagens/Dispositivo/' + dispositivoID + '.jpg', imagem)\n\ndef obterObjecto(imagem):\n img_grey = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY)\n valorThresh, imgComFiltro = cv2.threshold(img_grey, 0, 255,cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) # Aplicar thresholding obtido pelo algoritmo Otsu's\n edged = cv2.Canny(imgComFiltro, 100, 300) # Edge detection algorithm\n edged = cv2.dilate(edged, None, iterations=1) # Aplicar dilatação\n edged = cv2.erode(edged, None, iterations=1) # Aplicar erosão\n\n # Encontrar contornos na imagem\n cnts = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n cnts = sorted(cnts, key=cv2.contourArea, reverse=True)\n\n for c in cnts: # Percorrer todos os contornos encontrados na imagem\n if cv2.contourArea(c) < 30000: # Se o contorno não for maior do que o valor definido é ignorado\n continue\n boxFinal, imgComContornosFinal = contorno(imagem, c)\n (boxTopL, boxTopR, boxBottonR, BoxBottonL) = boxFinal # Obter as coordenadas da bounding box do objecto\n largura = boxTopR[0] - boxTopL[0]\n altura = BoxBottonL[1] - boxTopR[1]\n\n (boxTL, boxTR, boxBR, BoxBL) = boxFinal\n\n x1 = int(boxTL[1])\n y1 = int(BoxBL[1])\n x2 = int(boxTL[0])\n y2 = int(boxTR[0])\n\n padding = 10\n imgObjecto = imgComContornosFinal[x1 - padding:y1 + padding, x2 - padding:y2 + padding]\n\n return imgObjecto, altura, largura, boxFinal\n\ndef calcularDimensoesObjecto(imagemOb,areaMin):\n img_grey = cv2.cvtColor(imagemOb, cv2.COLOR_BGR2GRAY)\n valorThresh, imgComFiltro = cv2.threshold(img_grey, 0, 255,\n cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) # Aplicar thresholding obtido pelo algoritmo Otsu's\n edged = cv2.Canny(imgComFiltro, 30, 100) # Edge detection algorithm\n edged = cv2.dilate(edged, None, iterations=4) # Aplicar dilatação\n edged = cv2.erode(edged, None, iterations=4) # Aplicar erosão\n\n # Encontrar contornos na imagem\n cnts = cv2.findContours(edged, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n cnts = sorted(cnts, key=cv2.contourArea, reverse=True)\n\n for c in cnts: # Percorrer todos os contornos encontrados na imagem\n if cv2.contourArea(c) < areaMin:\n continue\n boxFinal, imgComContornosFinal = contorno(imagemOb, c)\n area = cv2.contourArea(c)\n (boxTopL, boxTopR, boxBottonR, BoxBottonL) = boxFinal # Obter as coordenadas da bounding box do objecto\n largura = boxTopR[0] - boxTopL[0]\n altura = BoxBottonL[1] - boxTopR[1]\n\n return imgComContornosFinal,largura,altura,area\n\ndef alignImages(img1, img2):\n # Convert images to grayscale\n im1Gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n im2Gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n\n orb = cv2.ORB_create(MAX_FEATURES)\n\n kp1, des1 = orb.detectAndCompute(im1Gray,None)\n kp2, des2 = orb.detectAndCompute(im2Gray,None)\n\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n\n # Match features.\n matches = bf.match(des1,des2)\n # Sort matches by score\n matches = sorted(matches, key = lambda x:x.distance)\n\n # Remove not so good matches\n numGoodMatches = int(len(matches) * GOOD_MATCH_PERCENT)\n matches = matches[:numGoodMatches]\n\n img3 = cv2.drawMatches(img1,kp1,img2,kp2,matches,None, flags=2)\n\n # Extract location of good matches\n points1 = np.zeros((len(matches), 2), dtype=np.float32)\n points2 = np.zeros((len(matches), 2), dtype=np.float32)\n\n for i, match in enumerate(matches):\n points1[i, :] = kp1[match.queryIdx].pt\n points2[i, :] = kp2[match.trainIdx].pt\n\n # Find homography\n h, mask = cv2.findHomography(points1, points2, cv2.RANSAC)\n\n # Use homography\n height, width, channels = img2.shape\n im1Reg = cv2.warpPerspective(img1, h, (width, height))\n\n return im1Reg, h\n\ndef guardarDados(dispositivoID):\n\tdados = {}\n\tdados = []\n\tdados.append({\n\t\t'id': int(dispositivoID),\n\t\t'data': data,\n\t\t'hora': hora,\n\t\t'altura': int(alturaObjecto),\n\t\t'largura': int(larguraObjecto)\n\t})\n\tdados.append({\n\t\t'objecto': 1,\n\t\t'altura': int(w1),\n\t\t'largura': int(h1),\n\t\t'area': int(a1)\n\t})\n\tdados.append({\n\t\t'objecto': 2,\n\t\t'altura': int(w2),\n\t\t'largura': int(h2),\n\t\t'area': int(a2)\n\t})\n\tdados.append({\n\t\t'objecto': 3,\n\t\t'altura': int(w3),\n\t\t'largura': int(h3),\n\t\t'area': int(a3)\n\t})\n\twith open('Data/' + dispositivoID + '.json', 'w') as outfile:\n\t\tjson.dump(dados, outfile)\n\ndef guardarDados2(dispositivoID):\n dados = {}\n dados['dispositivo'] = []\n dados['dispositivo'].append({\n 'id': int(dispositivoID),\n 'data': data,\n 'hora': hora,\n 'altura': int(alturaObjecto),\n 'largura': int(larguraObjecto)\n })\n dados['dispositivo'].append({\n 'objecto': 1,\n 'comprimento': int(w1),\n 'largura': int(h1),\n 'area': int(a1)\n })\n dados['dispositivo'].append({\n 'objecto': 2,\n 'comprimento': int(w2),\n 'largura': int(h2),\n 'area': int(a2)\n })\n dados['dispositivo'].append({\n 'objecto': 3,\n 'comprimento': int(w3),\n 'largura': int(h3),\n 'area': int(a3)\n })\n with open('Data/' + dispositivoID + '.txt', 'w') as outfile:\n json.dump(dados, outfile)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Imagem para medição')\n parser.add_argument('--imagemRef', type=str, default='ImagensPeca/opencv_frame_12.png',help='Imagem referência.')\n parser.add_argument('--imagem', type=str, default='ImagensPeca/opencv_frame_14.png',help='Imagem para ser analisada')\n parser.add_argument('--largura', type=int, default=640, help='Largura da Imagem')\n parser.add_argument('--altura', type=int, default=480, help='Altura da Imagem')\n parser.add_argument('--verImagens', type=bool, default=False, help='Visualizar as imagens')\n args = parser.parse_args()\n\n # Data e tempo atual\n timeStamp = datetime.datetime.now().replace(microsecond=0).isoformat(' ')\n aux = timeStamp.split(\" \")\n data = aux[0]\n hora = aux[1]\n\n altura = args.altura # Altura da imagem\n largura = args.largura # Largura da imagem\n dispositivoID = contadorDeDispositivos() # Identificador do objecto\n\n # Carregar a imagem de referência\n print(\"Reading reference image : \", args.imagemRef)\n imReference = cv2.imread(args.imagemRef)#, cv2.IMREAD_COLOR)\n imReference = cv2.resize(imReference, (args.largura, args.altura), cv2.INTER_LINEAR) # Dimensionar a imagem\n\n # Carregar a imagem para ser alinhada\n numImagem = random.randint(13, 163)\n imag=\"ImagensPeca/opencv_frame_\"+str(numImagem)+\".png\"\n\n print(\"Reading image to align : \", args.imagem);\n im = cv2.imread(imag)#, cv2.IMREAD_COLOR)\n im = cv2.resize(im, (args.largura, args.altura), cv2.INTER_LINEAR) # Dimensionar a imagem\n cv2.imwrite('imagemCamera.png', im)\n\n print(\"Aligning images ...\")\n # Registered image will be resotred in imReg. The estimated homography will be stored in h.\n imReg, h = alignImages(im, imReference)\n\n imgObjecto, alturaObjecto, larguraObjecto, boxFinal = obterObjecto(imReg)\n print(\"dispositivoID : \",dispositivoID)\n guardarImagemDispositivo(imgObjecto, str(dispositivoID))\n\n objecto1 = imgObjecto[230:290, 80:140] # Extração do objecto 1\n objecto2 = imgObjecto[340:400, 50:100] # EXtração do objecto 2\n objecto3 = imgObjecto[290:365, 50:100] # Extração do objecto 3\n\n objecto1Dimesoes, w1, h1, a1 = calcularDimensoesObjecto(objecto1, 400) # Calcular dimensões do objecto 1\n guardarImagemObjecto(objecto1Dimesoes, '1', str(dispositivoID)) # Guardar imagem do objecto 1\n\n objecto2Dimesoes, w2, h2, a2 = calcularDimensoesObjecto(objecto2, 400) # Calcular dimensões do objecto 1\n guardarImagemObjecto(objecto2Dimesoes, '2', str(dispositivoID)) # Guardar imagem do objecto 1\n\n objecto3Dimesoes, w3, h3, a3 = calcularDimensoesObjecto(objecto3, 400) # Calcular dimensões do objecto 1\n guardarImagemObjecto(objecto3Dimesoes, '3', str(dispositivoID)) # Guardar imagem do objecto 1\n\n guardarDados(str(dispositivoID)) # Guardar os resultados num ficheiro Json\n\n if args.verImagens:\n cv2.imshow(\"Recorte da imagem\", imgObjecto)\n cv2.waitKey(0)\n\n cv2.namedWindow('Objecto 1', cv2.WINDOW_NORMAL)\n cv2.imshow('Objecto 1', objecto1Dimesoes)\n cv2.waitKey(0)\n\n cv2.namedWindow('Objecto 2', cv2.WINDOW_NORMAL)\n cv2.imshow('Objecto 2', objecto2Dimesoes)\n cv2.waitKey(0)\n\n cv2.namedWindow('Objecto 3', cv2.WINDOW_NORMAL)\n cv2.imshow('Objecto 3', objecto3Dimesoes)\n cv2.waitKey(0)","sub_path":"findObject.py","file_name":"findObject.py","file_ext":"py","file_size_in_byte":9945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"360971412","text":"from asyncio import sleep\n\nfrom nonebot import on_notice\nfrom nonebot.adapters.cqhttp import Bot, Event\n\ngugua = on_notice(priority=5)\n\n\n@gugua.handle()\nasync def message_discernment_handle(bot: Bot, event: Event):\n print(f'检测到事件:{event.notice_type}')\n if event.notice_type == 'group_increase':\n new_id = event.user_id\n print(f'检测到受害者:{new_id}')\n new_group = event.group_id\n await sleep(3)\n\n await gugua.send('您好我是您朋友给您点的孤寡青蛙')\n await sleep(0.5)\n await gugua.send('我要开始叫了')\n await sleep(0.5)\n await gugua.send('孤寡孤寡孤寡孤寡孤寡孤寡孤寡孤')\n await sleep(0.5)\n await gugua.send('寡孤寡孤寡孤寡孤寡孤寡孤寡孤寡')\n await sleep(0.5)\n await gugua.send('寡孤寡孤寡孤寡孤寡孤寡孤寡孤寡')\n await sleep(0.5)\n await gugua.send('寡孤寡孤寡孤寡孤寡孤寡孤寡孤寡')\n await sleep(0.5)\n await gugua.send('寡孤寡孤寡孤寡孤寡孤寡孤寡孤寡')\n await sleep(0.5)\n await gugua.send('服务完毕,欢迎您明年再来')\n\n await bot.set_group_kick(group_id=new_group, user_id=new_id)\n","sub_path":"孤寡机器人.py","file_name":"孤寡机器人.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"452391120","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, exceptions\n\nclass Stand(models.Model):\n \"\"\"Defines poll stands used by people for voting\"\"\"\n\n _name = 'poll.stand'\n\n name = fields.Char(\n string='Description'\n )\n number = fields.Integer(\n string='Number'\n )\n precinct_id = fields.Many2one(\n comodel_name='poll.precinct',\n string='Precinct'\n )\n person_ids = fields.One2many(\n comodel_name='res.partner',\n inverse_name='stand_id'\n )\n people_quant = fields.Integer(\n string='People quant'\n )\n gender_id = fields.Many2one(\n comodel_name='res.partner.gender',\n string='Gender'\n )\n active = fields.Boolean(\n string='Active',\n default=True\n )\n\n \n","sub_path":"poll/models/poll_stand.py","file_name":"poll_stand.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"54917935","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.http import HttpResponse\nfrom django.template import loader\nfrom django.http import Http404\nfrom .models import Question\nfrom django.shortcuts import render\n\n\n\n# Create your views here.\ndef index(request):\n latest_question_list = Question.objects.order_by('-pub_date')[:5]\n template = loader.get_template('polls/index.html')\n context = {\n 'latest_question_list': latest_question_list,\n 'title': \"Question view\"\n }\n response = HttpResponse(template.render(context, request))\n return response\n\n\ndef detail(request, question_id):\n try:\n question = Question.objects.get(pk=question_id)\n except Question.DoesNotExist:\n raise Http404(\"Question does not exist\")\n return render(request, 'polls/detail.html', {'question': question, 'title': \"question \" + question_id})\n\n\ndef results(request, question_id):\n response = \"You're looking at the results of question %s.\"\n return HttpResponse(response % question_id)\n\n\ndef vote(request, question_id):\n return HttpResponse(\"You're voting on question %s.\" % question_id)\n\n\ndef pools(request):\n return HttpResponse(\"Man you should stop doing this mistake... write\"\n \" polls not pools\")\n","sub_path":"django_tutor/mysite/polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"408701768","text":"'''\nimport sys\ninput = sys.stdin.readline\n\narb = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]\nrom = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']\n\ndef arb_to_rom(n):\n i = 0\n s = \"\"\n while i<13:\n if n>=arb[i]:\n n -= arb[i]\n s += rom[i]\n continue\n else:\n i += 1\n return s\n\ndic = {}\nfor i in range(1, 4000):\n dic[arb_to_rom(i)] = i\n\ndef rom_to_arb(s):\n return dic[s]\n\ns1 = input().rstrip()\ns2 = input().rstrip()\nr1 = rom_to_arb(s1)\nr2 = rom_to_arb(s2)\nr3 = r1+r2\ns3 = arb_to_rom(r3)\n\nprint(r3)\nprint(s3)\n'''\n\nimport sys\ninput = sys.stdin.readline\n\nM = 1000; D = 500; C = 100; L = 50; X = 10; V = 5; I = 1\n# V, L, D는 한 번만 사용 가능. I, X, C, M은 연속해서 세 번까지 사용 가능\nIV = 4; IX = 9; XL = 40; XC = 90; CD = 400; CM = 900\n# 한 번씩만 사용 가능. IV와 IX 같이 불가능. XL, XC, CD, CM 또한 같이 불가능\n# 이 경우를 제외하고는 작은 숫자가 큰 숫자 왼쪽 어디에도 나올 수 X.\n\nLA = input().rstrip() # 입력 받았을 때 \\n 제거용\nLB = input().rstrip()\n\nsumA = 0 # 아라비아숫자 넣어줄 변수\nsumB = 0\n\ncnt = 0\ncntI = 0 # IV, IX 카운트\ncntX = 0 # XL, XC 카운트\ncntC = 0 # CD, CM 카운트\nfor i in LA:\n if i == 'M':\n sumA += M\n elif i == 'D':\n sumA += D\n elif i == 'C':\n if cnt < len(LA)-1 and cntC == 0:\n if LA[cnt+1] == 'D':\n sumA += CD\n cntC += CD\n elif LA[cnt+1] == 'M':\n sumA += CM\n cntC += CM\n else:\n sumA += C\n else:\n sumA += C\n elif i == 'L':\n sumA += L\n elif i == 'X':\n if cnt < len(LA)-1 and cntX == 0:\n if LA[cnt+1] == 'L':\n sumA += XL\n cntX += XL\n elif LA[cnt+1] == 'C':\n sumA += XC\n cntX += XC\n else:\n sumA += X\n else:\n sumA += X\n elif i == 'V':\n sumA += V\n elif i == 'I':\n if cnt < len(LA)-1 and cntI == 0:\n if LA[cnt+1] == 'V':\n sumA += IV\n cntI += IV\n elif LA[cnt+1] == 'X':\n sumA += IX\n cntI += IX\n else:\n sumA += I\n else:\n sumA += I\n cnt += 1\n\nif cntI == IV:\n sumA -= V\nelif cntI == IX:\n sumA -= X\nif cntX == XL:\n sumA -= L\nelif cntX == XC:\n sumA -= C\nif cntC == CD:\n sumA -= D\nelif cntC == CM:\n sumA -= M\n\n\ncnt = 0\ncntI = 0\ncntX = 0\ncntC = 0\nfor i in LB:\n if i == 'M':\n sumB += M\n elif i == 'D':\n sumB += D\n elif i == 'C':\n if cnt < len(LB)-1 and cntC == 0:\n if LB[cnt+1] == 'D':\n sumB += CD\n cntC += CD\n elif LB[cnt+1] == 'M':\n sumB += CM\n cntC += CM\n else:\n sumB += C\n else:\n sumB += C\n elif i == 'L':\n sumB += L\n elif i == 'X':\n if cnt < len(LB)-1 and cntX == 0:\n if LB[cnt+1] == 'L':\n sumB += XL\n cntX += XL\n elif LB[cnt+1] == 'C':\n sumB += XC\n cntX += XC\n else:\n sumB += X\n else:\n sumB += X\n elif i == 'V':\n sumB += V\n elif i == 'I':\n if cnt < len(LB)-1 and cntI == 0:\n if LB[cnt+1] == 'V':\n sumB += IV\n cntI += IV\n elif LB[cnt+1] == 'X':\n sumB += IX\n cntI += IX\n else:\n sumB += I\n else:\n sumB += I\n cnt += 1\n\nif cntI == IV:\n sumB -= V\nelif cntI == IX:\n sumB -= X\nif cntX == XL:\n sumB -= L\nelif cntX == XC:\n sumB -= C\nif cntC == CD:\n sumB -= D\nelif cntC == CM:\n sumB -= M\n\nsumAB = sumA + sumB\nprint(sumAB)\n\nRAB = ''\nwhile sumAB != 0:\n if sumAB >= 1000:\n RAB += 'M'\n sumAB -= 1000\n elif sumAB >= 900:\n RAB += 'CM'\n sumAB -= 900\n elif sumAB >= 500:\n RAB += 'D'\n sumAB -= 500\n elif sumAB >= 400:\n RAB += 'CD'\n sumAB -= 400\n elif sumAB >= 100:\n RAB += 'C'\n sumAB -= 100\n elif sumAB >= 90:\n RAB += 'XC'\n sumAB -= 90\n elif sumAB >= 50:\n RAB += 'L'\n sumAB -= 50\n elif sumAB >= 40:\n RAB += 'XL'\n sumAB -= 40\n elif sumAB >= 10:\n RAB += 'X'\n sumAB -= 10\n elif sumAB >= 9:\n RAB += 'IX'\n sumAB -= 9\n elif sumAB >= 5:\n RAB += 'V'\n sumAB -= 5\n elif sumAB >= 4:\n RAB += 'IV'\n sumAB -=4\n elif sumAB >= 1:\n RAB += 'I'\n sumAB -= 1\n\nprint(RAB)\n","sub_path":"etc/2608.py","file_name":"2608.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"429124984","text":"# Your Agent for solving Raven's Progressive Matrices. You MUST modify this file.\n#\n# You may also create and submit new files in addition to modifying this file.\n#\n# Make sure your file retains methods with the signatures:\n# def __init__(self)\n# def Solve(self,problem)\n#\n# These methods will be necessary for the project's main method to run.\n\n# Install Pillow and uncomment this line to access image processing.\n# from PIL import Image\n# import numpy\nimport RavensObject\n\nclass Agent:\n # The default constructor for your Agent. Make sure to execute any\n # processing necessary before your Agent starts solving problems here.\n #\n # Do not add any variables to this signature; they will not be used by\n # main().\n def __init__(self):\n self.transformation_lists = []\n # initial/final object context are in sync based on index number\n self.initial_object_context = []\n self.final_object_context = []\n self.removable_attributes = ['inside', 'above', 'shape', 'left-of', 'overlaps']\n self.known_shape_types = ['circle', 'square', 'right triangle', 'plus', 'pac-man', 'octagon', 'diamond']\n self.known_fill_types = ['yes', 'no', 'right-half', 'left-half', 'top-half', 'bottom-half']\n self.problem_name = \"\"\n\n\n '''\n transformation weights are as follows:\n Unchanged = 5\n Reflected = 4\n Rotated = 3\n Scaled = 2\n Deleted/Added = 1\n Shape Changed = 0\n '''\n\n\n # The primary method for solving incoming Raven's Progressive Matrices.\n # For each problem, your Agent's Solve() method will be called. At the\n # conclusion of Solve(), your Agent should return an int representing its\n # answer to the question: 1, 2, 3, 4, 5, or 6. Strings of these ints\n # are also the Names of the individual RavensFigures, obtained through\n # RavensFigure.getName(). Return a negative number to skip a problem.\n #\n # Make sure to return your answer *as an integer* at the end of Solve().\n # Returning your answer as a string may cause your program to crash.\n def Solve(self,problem):\n answer = -1\n # try:\n # reset global values from last problem\n self.transformation_lists = []\n self.initial_object_context = []\n self.final_object_context = []\n self.problem_name = problem.name\n print(problem.name)\n\n\n if(problem.hasVerbal):\n answer = self.solve_by_verbal(problem)\n else:\n pass\n # answer = self.solve_by_visual(problem)\n \n # except:\n # pass\n # finally: \n return answer\n\n def solve_by_verbal(self, problem):\n answer = -1\n # try:\n # Question names are 'A', 'B', 'C'\n question_figures = self.extract_question_figures(problem)\n\n # Answer names are '1', '2', '3', '4', '5', '6'\n answers_figures = self.extract_answers_figures(problem)\n\n\n delta = self.compute_delta_between_figures(question_figures['A'].objects, question_figures['B'].objects)\n #print(\"Problem: \"+problem.name + \" has a delta of: \"+ str(delta))\n if(delta == 0):\n\n answers_and_deltas = self.compare_guess_to_answers(question_figures['C'].objects, answers_figures)\n \n # find answer with smallest delta\n final_answer = -1\n final_delta = 100000000\n for (temp_answer, delta) in answers_and_deltas:\n if delta < final_delta:\n final_delta = delta\n final_answer = int(temp_answer)\n return final_answer\n # return min_idx + 1\n\n # create object state space from transforming each attribute and then use means-end analysis\n # to determine what states to keep\n root_node = Node(None, question_figures['A'].objects)\n guess_root_node = {}\n guess_root_node = Node(None, question_figures['C'].objects)\n final_figure = question_figures['B'].objects\n\n # hard code in a transformation attribute for the final object so it's not counted as a\n # difference\n final_figure['transformation'] = (\"\",\"\",\"\")\n self.create_object_context(root_node.objects, True)\n self.create_object_context(guess_root_node.objects, False)\n self.update_known_shape_types(problem)\n \n self.get_next_states(root_node, final_figure, 0, delta, delta)\n # get tranformation routes from linked list, the route consists of an order list of tuples\n\n # don't pass in the root nodes transformation since it doesn't have one\n self.create_transformation_states(guess_root_node, root_node)\n potential_answers = []\n\n self.get_possible_answers(guess_root_node, potential_answers, 0, [])\n winning_answers_delta_weight = []\n\n for (potential_answer, cumulative_weight) in potential_answers:\n answers_and_deltas = self.compare_guess_to_answers(potential_answer.objects, answers_figures)\n\n # find answer with smallest delta\n winning_answer = -1\n winning_delta = 100000000\n for (temp_answer, delta) in answers_and_deltas:\n if delta < winning_delta:\n winning_delta = delta\n winning_answer = int(temp_answer)\n winning_answers_delta_weight.append((winning_answer, winning_delta, cumulative_weight))\n\n # the answer has the lowest delta and highest weight from all of the potential answers\n # step 1: find smallest delta\n (answer_value, smallest_delta, weight_value) = min(winning_answers_delta_weight, key=lambda x: x[1])\n\n # step 2: there could be multiple answers that tie to be the smallest, find all of them\n answers_that_tied_on_delta = [(temp_answer, temp_delta, temp_weight) for (temp_answer, temp_delta, temp_weight) in winning_answers_delta_weight if temp_delta == smallest_delta]\n\n\n # step 3: if there was a tie with delta, breaking it with their transformation weight\n final_answer = 10\n highest_weight = -1\n if len(answers_that_tied_on_delta) > 1:\n for (temp_answer, temp_delta, temp_weight) in answers_that_tied_on_delta:\n if temp_weight > highest_weight:\n highest_weight = temp_weight\n final_answer = temp_answer\n else:\n (temp_answer, temp_delta, temp_weight) = answers_that_tied_on_delta[0]\n final_answer = temp_answer\n\n return int(final_answer)\n\n # # final_idx = 0\n # # min_delta = 10000000000000000000000\n # # for (min_weight, min_idx) in answer_weights:\n # # if min_weight < min_delta:\n # # final_idx = min_idx\n\n # answer = final_answer + 1\n\n # # except:\n # # pass\n # # finally: \n # return answer\n \n\n def create_object_context(self, object_names, for_initial_state):\n obj_list = list(object_names.keys())\n obj_list.sort()\n for obj in obj_list:\n if for_initial_state:\n self.initial_object_context.append(obj)\n else:\n self.final_object_context.append(obj)\n\n\n def compare_guess_to_answers(self, guess, answers):\n answers_delta = []\n for answer in answers:\n delta = self.compute_delta_between_figures(guess, answers[answer].objects)\n answers_delta.append((answer, delta))\n \n return answers_delta\n\n def get_transformation_lists(self, parent_node, transformation_list):\n # base case\n if(parent_node.child_nodes == None or len(parent_node.child_nodes) == 0):\n return transformation_list.append(parent_node.transformation)\n else:\n if(len(parent_node.child_nodes) > 1):\n pass\n else:\n transformation_list.append(parent_node.transformation)\n self.get_transformation_lists(parent_node.child_nodes[0], transformation_list)\n\n\n def perform_transformation(self, attr, value, transformation, weight, parent_angle = 0):\n if(attr == 'fill'):\n return self.perform_fill_transformation(attr, value, transformation, weight)\n elif(attr == 'shape'):\n return self.perform_shape_transformation(attr, value, transformation, weight)\n elif(attr == 'size'):\n return self.perform_size_transformation(attr, value, transformation, weight)\n elif(attr == 'angle'):\n return self.perform_angle_transformation(attr, value, transformation, weight, parent_angle)\n elif(attr == 'alignment'):\n return self.perform_alignment_transformation(attr, value, transformation, weight)\n elif(attr == 'inside'):\n return self.perform_inside_transformation(attr, value, transformation, weight)\n elif(attr == 'above'):\n return self.perform_above_transformation(attr, value, transformation, weight)\n elif(attr == 'left-of'):\n return self.perform_left_of_transformation(attr, value, transformation, weight)\n elif(attr == 'overlaps'):\n return self.perform_overlaps_transformation(attr, value, transformation, weight)\n else:\n print(\"attribute key: \"+attr + \", not found. Value is: \"+ str(value))\n\n # takes an object, returns the list of all possible states with a single transformation from the initial state\n def get_transformation(self, init_obj):\n # function overview: each Node will have a set of child nodes where each child node has the same objects and attributes as the parent node,\n # except that one attribute on one object will have changed\n\n # for some transformations we need to have more of a context of the entire figure (ie. inside, above). For these we\n # need to pass around a context of the other objects in scope\n\n # state space is a linked list, each node is the attributes and their properties plus an additional property: the\n # transformation that led to that state from the previous state\n new_children = []\n for obj_key in filter(lambda x: x != 'transformation', init_obj.keys()):\n # handle attributes that are only editable\n new_children.extend(self.handle_non_removable_attributes(obj_key, init_obj))\n \n # handle attributes that can be added or deleted\n new_children.extend(self.handle_removable_attributes(obj_key, init_obj))\n\n return new_children\n\n def handle_removable_attributes(self, obj_key, init_obj):\n new_children = []\n transformation_list = self.create_removable_transformations(obj_key, init_obj)\n \n for (attr, new_attr_value, transformation, weight) in transformation_list:\n # if object has attribute, create an instance without the attribute, otherwise\n # create an instance with it or an instance with it modified\n if transformation == \"removed\" or new_attr_value == None and init_obj[obj_key].attributes[attr] != None:\n new_child = self.clone_parent(init_obj)\n if attr == 'shape':\n # shape deletion deletes the entire object but just an attribute\n del new_child[obj_key]\n else:\n del(new_child[obj_key].attributes[attr])\n new_child['transformation'] = (obj_key, attr, new_attr_value, transformation, weight)\n new_children.append(new_child)\n else:\n new_child = self.clone_parent(init_obj)\n new_child[obj_key].attributes[attr] = new_attr_value\n new_child['transformation'] = (obj_key, attr, new_attr_value, transformation, weight)\n new_children.append(new_child)\n\n return new_children\n\n def handle_non_removable_attributes(self, obj_key, init_obj):\n new_children = []\n attribute_keys = filter(lambda x: x not in self.removable_attributes, init_obj[obj_key].attributes.keys())\n for attr_key in attribute_keys:\n # get transformations for each attribute\n attr_value = init_obj[obj_key].attributes[attr_key]\n transformation_list = self.create_non_removable_transformations(attr_key, attr_value)\n \n # create new child node with the new attribute value\n if transformation_list != None and len(transformation_list) > 0:\n for (attr, new_attr_value, transformation, weight) in transformation_list:\n new_child = self.clone_parent(init_obj)\n new_child[obj_key].attributes[attr_key] = new_attr_value\n # new_child['transformation'] = (\"\", \"\", \"\")\n new_child['transformation'] = (obj_key, attr_key, new_attr_value, transformation, weight)\n new_children.append(new_child)\n\n return new_children\n\n def clone_parent(self, parent):\n clone = {}\n for p in filter(lambda x: x != 'transformation', parent):\n clone[p] = RavensObject.RavensObject(parent[p].name)\n clone[p].attributes = parent[p].attributes.copy()\n return clone\n\n # TODO: Change this to only return leaf nodes with a delta == 0????????????\n def get_next_states(self, parent_node, final_obj, depth_count, running_delta, total_delta):\n if(depth_count > total_delta):\n # hit max depth\n return\n else:\n children = self.get_transformation(parent_node.objects)\n leaf_node = False\n # filter out children that don't decrease delta\n if children != None and len(children) > 0:\n for child in children:\n child_delta = self.compute_delta_between_figures(child, final_obj)\n if(child_delta == 0):\n leaf_node = True\n if(child_delta < running_delta):\n # create nodes for each of the children that reduce delta\n child_node = Node(child['transformation'], child)\n parent_node.child_nodes.append(child_node)\n\n # if any children have a delta of 0 => done\n if(leaf_node):\n return leaf_node\n\n if len(parent_node.child_nodes) > 0:\n for child_node in parent_node.child_nodes:\n found_leaf = self.get_next_states(child_node, final_obj, depth_count + 1, running_delta - 1, total_delta)\n if found_leaf:\n return True\n else:\n return\n\n\n def create_non_removable_transformations(self, attr, value):\n # the logic for determining what transformation occurred is dependent on the attribute whose\n # transformation you are examining\n\n if(attr == 'fill'):\n return self.create_fill_transformation(attr, value)\n elif(attr == 'size'):\n return self.create_size_transformation(attr, value)\n elif(attr == 'angle'):\n return self.create_angle_transformation(attr, value)\n elif(attr == 'alignment'):\n return self.create_alignment_transformation(attr, value)\n else:\n return [(attr, value, \"No Change\")]\n #print(\"attribute key: \"+attr + \", not found. Value is: \"+ str(value))\n\n # this is for attributes that can be removed/added\n def create_removable_transformations(self, obj_key, init_obj):\n transformation_list = self.create_inside_transformation(obj_key, init_obj)\n transformation_list.extend(self.create_above_transformation(obj_key, init_obj))\n transformation_list.extend(self.create_shape_transformation(obj_key, init_obj))\n transformation_list.extend(self.create_left_of_transformation(obj_key, init_obj))\n transformation_list.extend(self.create_overlaps_transformation(obj_key, init_obj))\n return transformation_list\n\n\n def extract_answers_figures(self, problems):\n answers = {}\n for problem in problems.figures.keys():\n if(problem in ['1', '2', '3', '4', '5', '6']):\n answers[problem] = problems.figures[problem]\n\n return answers\n\n def extract_question_figures(self, problems):\n questions = {}\n for problem in problems.figures.keys():\n if(problem in ['A', 'B', 'C']):\n questions[problem] = problems.figures[problem]\n\n return questions\n\n\n # only used for initial delta computation, data structure is different when\n # calculating delta for state space\n def compute_delta_between_figures(self, fig1, fig2):\n # changing to a list, allows iterating through the list easier\n question_figures_objects_list_A = list(fig1.items())\n question_figures_objects_list_B = list(fig2.items())\n\n # sort objects by name as some of the code depends on that\n question_figures_objects_list_A.sort(key=lambda x: self.sort_by_name(x), reverse = False)\n question_figures_objects_list_B.sort(key=lambda x: self.sort_by_name(x), reverse = False)\n\n # usually objects are list in order of size\n question_figures_objects_list_A.sort(key=lambda x: self.sort_by_size(x), reverse = True)\n question_figures_objects_list_B.sort(key=lambda x: self.sort_by_size(x), reverse = True)\n\n delta = 0\n list_B_length = len(question_figures_objects_list_B)\n if question_figures_objects_list_A != None and len(question_figures_objects_list_A) > 0:\n for i in range(0, len(question_figures_objects_list_A)):\n key_A, value_A = question_figures_objects_list_A[i]\n\n # in case A has more objects then B\n if(i < list_B_length):\n key_B, value_B = question_figures_objects_list_B[i]\n if(key_B != 'transformation'):\n delta += self.find_figures_delta(value_A, value_B)\n else:\n delta += 1\n return delta\n\n def sort_by_name(self, elem):\n (name, node) = elem\n return name\n\n def sort_by_size(self, elem):\n (name, node) = elem\n if name == 'transformation':\n # object deleted should go at the end\n return -1000000\n else:\n if 'size' in node.attributes:\n encoded_value = self.encode_size(node.attributes['size'])\n idx = encoded_value.index(1)\n return idx\n else:\n return 0\n\n def find_figures_delta(self, obj1, obj2):\n delta = 0\n if isinstance(obj1, tuple) or isinstance(obj2, tuple):\n # means one or both objects were deleted in a transformation\n if isinstance(obj2, tuple) and not isinstance(obj1, tuple):\n delta += 1\n # delta += len(obj1.attributes.keys())\n elif isinstance(obj1, tuple) and not isinstance(obj2, tuple):\n delta += 1\n # delta += len(obj2.attributes.keys())\n else:\n for attr_key in obj1.attributes.keys():\n value1 = obj1.attributes[attr_key]\n if attr_key not in obj2.attributes.keys():\n if attr_key != \"transformation\":\n delta += 1\n else:\n value2 = obj2.attributes[attr_key]\n if(attr_key == 'fill'):\n delta += self.fill_delta(value1, value2)\n elif(attr_key == 'shape'):\n delta += self.shape_delta(value1, value2)\n elif(attr_key == 'size'):\n delta += self.size_delta(value1, value2)\n elif(attr_key == 'angle'):\n delta += self.angle_delta(value1, value2)\n elif(attr_key == 'alignment'):\n delta += self.alignment_delta(value1, value2)\n elif(attr_key == 'inside'):\n delta += self.inside_delta(value1, value2)\n elif(attr_key == 'above'):\n delta += self.above_delta(value1, value2)\n elif(attr_key == 'left-of'):\n delta += self.left_of_delta(value1, value2)\n elif(attr_key == 'overlaps'):\n delta += self.overlaps_delta(value1, value2)\n else:\n # print(\"attribute key: \"+attr_key + \", not found. Value is: \"+ str(value1))\n pass\n\n return delta\n\n def above_delta(self, value1, value2):\n nested_levels1 = None\n nested_levels2 = None\n if isinstance(value1, list):\n nested_levels1 = value1\n else:\n nested_levels1 = value1.split(',')\n if isinstance(value2, list):\n nested_levels2 = value2\n else:\n nested_levels2 = value2.split(',')\n return abs(len(nested_levels1) - len(nested_levels2))\n\n def inside_delta(self, value1, value2):\n nested_levels1 = None\n nested_levels2 = None\n if isinstance(value1, list):\n nested_levels1 = value1\n else:\n nested_levels1 = value1.split(',')\n if isinstance(value2, list):\n nested_levels2 = value2\n else:\n nested_levels2 = value2.split(',')\n return abs(len(nested_levels1) - len(nested_levels2))\n\n def overlaps_delta(self, value1, value2):\n nested_levels1 = None\n nested_levels2 = None\n if isinstance(value1, list):\n nested_levels1 = value1\n else:\n nested_levels1 = value1.split(',')\n if isinstance(value2, list):\n nested_levels2 = value2\n else:\n nested_levels2 = value2.split(',')\n return abs(len(nested_levels1) - len(nested_levels2))\n\n\n def left_of_delta(self, value1, value2):\n nested_levels1 = None\n nested_levels2 = None\n if isinstance(value1, list):\n nested_levels1 = value1\n else:\n nested_levels1 = value1.split(',')\n if isinstance(value2, list):\n nested_levels2 = value2\n else:\n nested_levels2 = value2.split(',')\n return abs(len(nested_levels1) - len(nested_levels2))\n\n def alignment_delta(self, value1, value2):\n value1_encoded = [0,0,0,0]\n value2_encoded = [0,0,0,0]\n\n if(value1 == \"top-left\"):\n value1_encoded = [1,0,0,0]\n elif(value1 == \"top-right\"):\n value1_encoded = [0,1,0,0]\n elif(value1 == \"bottom-right\"):\n value1_encoded = [0,0,1,0]\n elif(value1 == \"bottom-left\"):\n value1_encoded = [0,0,0,1]\n else:\n # values are already encoded\n value1_encoded = value1\n\n if(value2 == \"top-left\"):\n value2_encoded = [1,0,0,0]\n elif(value2 == \"top-right\"):\n value2_encoded = [0,1,0,0]\n elif(value2 == \"bottom-right\"):\n value2_encoded = [0,0,1,0]\n elif(value2 == \"bottom-left\"):\n value2_encoded = [0,0,0,1]\n else:\n # values are already encoded\n value2_encoded = value1\n\n return abs(value1_encoded.index(1) - value2_encoded.index(1))\n\n def angle_delta(self, value1, value2):\n # if(value1 == value2):\n # return 0\n # else:\n # return 1\n \n value1 = self.parse_int(value1)\n value2 = self.parse_int(value2)\n if value1 == None:\n if value2 == None:\n return 0\n else:\n return value2\n else:\n if value2 == None:\n return value1\n else:\n return abs(int(value1) - int(value2))\n\n\n def shape_delta(self, attr1, attr2):\n if(attr1 == attr2):\n return 0\n else:\n return 1\n\n def fill_delta(self, attr1, attr2):\n if(attr1 == attr2):\n return 0\n else:\n return 1\n\n def size_delta(self, value1, value2):\n value1_encoded = [0,0,0,0,0,0]\n value2_encoded = [0,0,0,0,0,0]\n\n value1_encoded = self.encode_size(value1)\n value2_encoded = self.encode_size(value2)\n\n return abs(value1_encoded.index(1) - value2_encoded.index(1))\n\n def create_inside_transformation(self, obj_key, init_obj):\n # \"inside\" attribute can be added/deleted/edited, most attribute's values can only be edited\n # create several next states, for each inside attributes, create a next state with one inside value removed,\n # also create a next state with a inside value added\n\n return_value = []\n if 'inside' in init_obj[obj_key].attributes:\n if isinstance(init_obj[obj_key].attributes['inside'], list):\n inside_these_objects = init_obj[obj_key].attributes['inside']\n else:\n inside_these_objects = init_obj[obj_key].attributes['inside'].split(',')\n # create next states with one inside value removed\n if inside_these_objects != None and len(inside_these_objects) > 1:\n for i in range(0, len(inside_these_objects)):\n truncated_list = inside_these_objects[0 : i] + inside_these_objects[i+1 : ]\n return_value.append((\"inside\", truncated_list, \"decrement\", 2))\n # \"above\", [0:i] + [i+1:], \"decrement\")\n else:\n return_value.append((\"inside\", None, \"removed\", 1)) \n\n # create next states with one inside value added\n not_inside_these_objects = filter(lambda x: x not in inside_these_objects, self.initial_object_context)\n if not_inside_these_objects != None:\n for not_in_obj in not_inside_these_objects:\n return_value.append((\"inside\", inside_these_objects.append(not_in_obj), \"increment\", 2))\n else:\n # object currently isn't in any other objects, create next states with it inside every other object\n for obj in self.initial_object_context:\n return_value.append((\"inside\", obj, \"increment\", 1))\n\n return return_value\n \n def create_above_transformation(self, obj_key, init_obj):\n # \"above\" attribute can be added/deleted/edited, most attribute's values can only be edited\n return_value = []\n if 'above' in init_obj[obj_key].attributes:\n if isinstance(init_obj[obj_key].attributes['above'], list):\n above_these_objects = init_obj[obj_key].attributes['above']\n else:\n above_these_objects = init_obj[obj_key].attributes['above'].split(',')\n # create next states with one above value removed\n if(len(above_these_objects) > 1):\n for i in range(0, len(above_these_objects)):\n truncated_list = above_these_objects[0 : i] + above_these_objects[i+1 : ]\n return_value.append((\"above\", truncated_list, \"decrement\", 2))\n else:\n return_value.append((\"above\", None, \"removed\", 1)) \n\n # create next states with one above value added\n not_above_these_objects = filter(lambda x: x not in above_these_objects, self.initial_object_context)\n for not_above_obj in not_above_these_objects:\n new_value = above_these_objects + [not_above_obj]\n return_value.append((\"above\", new_value, \"increment\", 2))\n else:\n # object currently isn't in any other objects, create next states with it above every other object\n for obj in self.initial_object_context:\n return_value.append((\"above\", obj, \"increment\", 1))\n\n return return_value\n\n def create_overlaps_transformation(self, obj_key, init_obj):\n return_value = []\n if 'overlaps' in init_obj[obj_key].attributes:\n if isinstance(init_obj[obj_key].attributes['overlaps'], list):\n overlaps_these_objects = init_obj[obj_key].attributes['overlaps']\n else:\n overlaps_these_objects = init_obj[obj_key].attributes['overlaps'].split(',')\n \n # create next states with one left-of value removed\n if(len(overlaps_these_objects) > 1):\n for i in range(0, len(overlaps_these_objects)):\n truncated_list = overlaps_these_objects[0 : i] + overlaps_these_objects[i+1 : ]\n return_value.append((\"overlaps\", truncated_list, \"decrement\", 2))\n # \"above\", [0:i] + [i+1:], \"decrement\")\n else:\n return_value.append((\"overlaps\", None, \"removed\", 1)) \n\n # create next states with one left-of value added\n not_overlaps_these_objects = filter(lambda x: x not in overlaps_these_objects, self.initial_object_context)\n for not_overlaps_obj in not_overlaps_these_objects:\n return_value.append((\"overlaps\", overlaps_these_objects.append(not_overlaps_obj), \"increment\", 2))\n else:\n # object currently isn't left-of any other objects, create next states with it left-of every other object\n for obj in self.initial_object_context:\n return_value.append((\"overlaps\", obj, \"increment\", 1))\n\n return return_value\n\n\n def create_left_of_transformation(self, obj_key, init_obj):\n return_value = []\n if 'left-of' in init_obj[obj_key].attributes:\n if isinstance(init_obj[obj_key].attributes['left-of'], list):\n left_of_these_objects = init_obj[obj_key].attributes['left-of']\n else:\n left_of_these_objects = init_obj[obj_key].attributes['left-of'].split(',')\n \n # create next states with one left-of value removed\n if(len(left_of_these_objects) > 1):\n for i in range(0, len(left_of_these_objects)):\n truncated_list = left_of_these_objects[0 : i] + left_of_these_objects[i+1 : ]\n return_value.append((\"left-of\", truncated_list, \"decrement\", 2))\n else:\n return_value.append((\"left-of\", None, \"removed\", 1)) \n\n # create next states with one left-of value added\n not_left_of_these_objects = filter(lambda x: x not in left_of_these_objects, self.initial_object_context)\n for not_left_of_obj in not_left_of_these_objects:\n return_value.append((\"left-of\", left_of_these_objects.append(not_left_of_obj), \"increment\", 2))\n else:\n # object currently isn't left-of any other objects, create next states with it left-of every other object\n for obj in self.initial_object_context:\n return_value.append((\"left-of\", obj, \"increment\", 1))\n\n return return_value\n\n def create_shape_transformation(self, obj_key, init_obj):\n # \"shape\" attribute can be added/deleted/edited, most attribute's values can only be edited\n return_value = []\n if 'shape' in init_obj[obj_key].attributes:\n # return a list with every shape transition \n value = init_obj[obj_key].attributes['shape']\n for shape in filter(lambda x: x != value, self.known_shape_types):\n return_value.append((\"shape\", shape, \"shape\", 0))\n\n # return a state for the deletion of the object\n return_value.append((\"shape\", None, \"removed\", 1)) \n\n return return_value\n\n def create_alignment_transformation(self, attr, value):\n # top-left => index = 0\n # top-right => index = 1\n # bottom-right => index = 2\n # bottom-left => index = 3\n\n if value == \"top-left\":\n return [(\"alignment\", [0,1,0,0], \"alignment\", 2), (\"alignment\", [0,0,1,0], \"alignment\", 2), (\"alignment\", [0,0,0,1], \"alignment\", 2)]\n elif value == \"top-right\":\n return [(\"alignment\", [1,0,0,0], \"alignment\", 2), (\"alignment\", [0,0,1,0], \"alignment\", 2), (\"alignment\", [0,0,0,1], \"alignment\", 2)]\n elif value == \"bottom-right\":\n return [(\"alignment\", [1,0,0,0], \"alignment\", 2), (\"alignment\", [0,1,0,0], \"alignment\", 2), (\"alignment\", [0,0,0,1], \"alignment\", 2)]\n elif value == \"bottom-left\":\n return [(\"alignment\", [1,0,0,0], \"alignment\", 2), (\"alignment\", [0,1,0,0], \"alignment\", 2), (\"alignment\", [0,0,1,0], \"alignment\", 2)]\n else:\n # value is already encoded\n idx = value.index(1)\n if idx == 0:\n value = \"top-left\"\n elif idx == 1:\n value = \"top-right\"\n elif idx == 2:\n value = \"bottom-right\"\n elif idx == 3:\n value = \"bottom-left\"\n \n return self.create_alignment_transformation(attr, value)\n\n def create_angle_transformation(self, attr, value):\n\n if isinstance(value, str):\n value = int(value)\n \n if(value == 0):\n value = 360\n\n lower_value = int((value -1) % 360)\n higher_value = int((value + 1) % 360)\n angle_transformations = [(\"angle\", lower_value, 'decrement', 3), (\"angle\", higher_value, 'increment', 3)]\n angle_transformations.extend(self.create_reflection_transformation(attr, value))\n return angle_transformations\n\n def create_reflection_transformation(self, attr, value):\n # return both horizontal and vertical reflections\n reflection_transformations = []\n\n # reflection on each axis and per quadrant\n value = int(value)\n # if value == 0 or value == 360:\n reflection_transformations.append(('angle', 180,'reflection', 4))\n # elif value == 180:\n reflection_transformations.append(('angle', 0,'reflection',4))\n # elif value == 90:\n reflection_transformations.append(('angle', 270,'reflection',4))\n # elif value == 270:\n reflection_transformations.append(('angle', 90,'reflection',4))\n # elif value > 0 and value < 90:\n # first quadrant reflection \n reflection_transformations.append(('angle', 180 - value,'reflection-first-second-quadrant',4))\n # elif value > 90 and value < 180:\n # second quadrant reflection\n # reflection_transformations.append(('angle', 180 - value,'reflection',4))\n # elif value > 180 and value < 270:\n # third quadrant reflection\n # delta = 360 - value\n # reflection_transformations.append(('angle', 180 + delta,'reflection',4))\n # elif value > 270 and value < 360:\n # fourth quadrant\n delta = 360 - value\n reflection_transformations.append(('angle', 180 + delta,'reflection-third-fourth-quadratn',4))\n\n return reflection_transformations\n\n def create_fill_transformation(self, attr, value):\n return_value = []\n # return a list with every fill transition except the current fill value\n for new_fill_value in filter(lambda x: x != value, self.known_fill_types):\n return_value.append((\"fill\", new_fill_value, \"fill\", 2))\n\n return return_value\n\n def create_size_transformation(self, attr, value):\n # sizes are held in an array very small, small, medium, large, very large, huge\n # [0,0,0,0,0,1] == huge\n # [1,0,0,0,0,1] == very small\n # given a size we can usually go one size larger and one size smaller\n\n if(value == \"very small\"):\n return [(\"size\", [0,1,0,0,0,0], \"increment\", 2)]\n elif(value == \"small\"):\n return [(\"size\", [1,0,0,0,0,0], \"decrement\", 2), (\"size\", [0,0,1,0,0,0], \"increment\", 2)]\n elif(value == \"medium\"):\n return [(\"size\", [0,1,0,0,0,0], \"decrement\", 2), (\"size\", [0,0,0,1,0,0], \"increment\", 2)]\n elif(value == \"large\"):\n return [(\"size\", [0,0,1,0,0,0], \"decrement\", 2), (\"size\", [0,0,0,0,1,0], \"increment\", 2)]\n elif(value == \"very large\"):\n return [(\"size\", [0,0,0,1,0,0], \"decrement\", 2), (\"size\", [0,0,0,0,0,1], \"increment\", 2)]\n elif(value == \"huge\"):\n return [(\"size\", [0,0,0,0,1,0], \"decrement\", 2)]\n else:\n # value already encoded\n size = value.index(1)\n if size == 0:\n value = \"small\"\n elif size == 1:\n value = \"very small\"\n elif size == 2:\n value = \"medium\"\n elif size == 3:\n value = \"large\"\n elif size == 4:\n value = \"very large\"\n elif size == 5:\n value = \"huge\"\n else:\n value = \"small\"\n return self.create_size_transformation(attr, value)\n \n\n def perform_above_transformation(self, attr, value, transformation, weight):\n if transformation == \"increment\":\n return (value, weight)\n elif transformation == \"decrement\":\n return (value, weight)\n elif transformation == \"removed\":\n return (None, weight)\n else: \n print(\"Error performating inside transformation. Attr: \" + attr + \", value: \" + str(value) + \", transformation: \"+ str(transformation))\n\n def perform_inside_transformation(self, attr, value, transformation, weight):\n if transformation == \"increment\":\n return (value, weight)\n elif transformation == \"decrement\":\n return (value, weight)\n elif transformation == \"removed\":\n return (None, weight)\n else: \n print(\"Error performating inside transformation. Attr: \" + attr + \", value: \" + str(value) + \", transformation: \"+ str(transformation))\n\n def perform_overlaps_transformation(self, attr, value, transformation, weight):\n if transformation == \"increment\":\n return (value, weight)\n elif transformation == \"decrement\":\n return (value, weight)\n elif transformation == \"removed\":\n return (None, weight)\n else: \n print(\"Error performating overlaps transformation. Attr: \" + attr + \", value: \" + str(value) + \", transformation: \"+ str(transformation))\n\n def perform_left_of_transformation(self, attr, value, transformation, weight):\n if transformation == \"increment\":\n return (value, weight)\n elif transformation == \"decrement\":\n return (value, weight)\n elif transformation == \"removed\":\n return (None, weight)\n else: \n print(\"Error performating left-of transformation. Attr: \" + attr + \", value: \" + str(value) + \", transformation: \"+ str(transformation))\n\n def perform_shape_transformation(self, attr, value, transformation, weight):\n return (value, weight)\n\n def perform_alignment_transformation(self, attr, value, transformation, weight):\n idx = value.index(1)\n if idx == 0:\n return (\"top-left\", weight)\n elif idx == 1:\n return (\"top-right\", weight)\n elif idx == 2:\n return (\"bottom-right\", weight)\n elif idx == 3:\n return (\"bottom-left\", weight)\n \n def perform_angle_transformation(self, attr, value, transformation, weight, parent_angle = 0):\n value = int(value)\n parent_value = int(parent_angle)\n\n if 'reflection' in transformation:\n # which quadrant is the reflection occurring in?\n if 'first'in transformation:\n # for first and second quadrant\n original_image_angle = 180 - value\n delta = abs(value - original_image_angle)\n elif 'third' in transformation:\n # for third and fourth quadrant\n original_image_angle = 540 - value\n delta = abs(value - original_image_angle)\n # delta = 540 - value\n else:\n # transformation occurred on an axis\n return (value, weight)\n\n if parent_value > 0 and parent_value < 90:\n return (delta + parent_value, weight)\n elif parent_value > 90 and parent_value < 180:\n return (delta, weight)\n elif parent_value > 180 and parent_value < 270:\n return (delta + parent_angle, weight)\n elif parent_value > 270 and parent_value < 360:\n return (parent_value - delta, weight)\n else:\n return (value, weight)\n else:\n return (value, weight)\n # if(transformation == \"increment\"):\n # return (int(value) + 1) % 360\n # elif(transformation == \"decrement\"):\n # return (int(value) - 1) % 360\n # else:\n # print(\"In perform_angle_transformation, unrecognized transformation: \"+ str(transformation))\n # print(\"attr: \" + str(attr) + \", value: \"+ str(value))\n\n def perform_fill_transformation(self, attr, value, transformation, weight):\n return (value, weight)\n # if(transformation == \"fill\"):\n # return (\"fill\", \"no\")\n # else:\n # return (\"fill\", \"yes\")\n\n def perform_size_transformation(self, attr, value, transformation, weight):\n return (value, weight)\n # size = value.index(1)\n # if size == 0:\n # return \"small\"\n # elif size == 1:\n # return \"very small\"\n # elif size == 2:\n # return \"medium\"\n # elif size == 3:\n # return \"large\"\n # elif size == 4:\n # return \"very large\"\n # elif size == 5:\n # return \"huge\"\n # if(transformation == \"increment\"):\n # return (\"size\", int(value) + 1)\n # elif(transformation == \"decrement\"):\n # return (\"size\", int(value) - 1)\n # else:\n # print(\"In perform_size_transformation, unrecognized transformation: \"+ str(transformation))\n # print(\"attr: \" + str(attr) + \", value: \"+ str(value))\n\n def solve_by_visual(self, problem):\n\n pass\n\n def get_possible_answers(self, parent_node, possible_answers, cumulative_weight, transformations_seen):\n # cumulative_weight is only for unique transformations\n # traverse to leaf nodes, each leaf node is a possible answer so collect them\n if parent_node.child_nodes == None or len(parent_node.child_nodes) == 0:\n # at leaf node\n if parent_node.transformation != None: \n (obj_key, attr_key, new_attr_value, transformation, weight) = parent_node.transformation\n if transformation not in transformations_seen:\n transformations_seen.append(transformation)\n cumulative_weight += weight\n possible_answers.append((parent_node, cumulative_weight))\n return\n else:\n for child in parent_node.child_nodes:\n if parent_node.transformation != None:\n (obj_key, attr_key, new_attr_value, transformation, weight) = parent_node.transformation\n if transformation not in transformations_seen:\n transformations_seen.append(transformation)\n cumulative_weight += weight\n self.get_possible_answers(child, possible_answers, cumulative_weight, transformations_seen)\n\n def create_transformation_states(self, parent_node, semantic_web_node):\n # each node in the semantic_web has a single transformation, create a similar semantic web with the parent_node\n # the leaves for this new semantic_web will be possible final answers\n\n if(parent_node is None):\n # fallen off semantic web (tree) (ie. finished all transformations for that route from root to leaf)\n return\n else:\n # apply semantic_web_node transformation to parent_node, if there is one (there won't be one at the root node level)\n if semantic_web_node.transformation != None:\n (obj_key, attr_key, new_attr_value, transformation, weight) = semantic_web_node.transformation\n parent_node.transformation = (obj_key, attr_key, new_attr_value, transformation, weight)\n\n # get object name to perform transformation on \n if transformation == 'removed':\n parent_obj_name_for_transformation = self.map_deleted_object_name(parent_node, semantic_web_node, obj_key)\n else:\n parent_obj_name_for_transformation = self.map_object_name(parent_node, semantic_web_node, obj_key)\n \n # perform transformation on object\n if parent_obj_name_for_transformation != None:\n if 'reflection' in transformation:\n # reflection needs the parent's angle to know how much to change it by\n parent_angle = 0\n if 'angle' in parent_node.objects[parent_obj_name_for_transformation].attributes.keys():\n parent_angle = parent_node.objects[parent_obj_name_for_transformation].attributes['angle']\n\n (new_value, weight) = self.perform_transformation(attr_key, new_attr_value, transformation, weight, parent_angle)\n else:\n (new_value, weight) = self.perform_transformation(attr_key, new_attr_value, transformation, weight)\n if new_value == None:\n # special case when transformation is deleting the object\n if parent_obj_name_for_transformation in parent_node.objects:\n del parent_node.objects[parent_obj_name_for_transformation]\n # else:\n # raise Exception(\"deleting object failed for object name: \"+ parent_obj_name_for_transformation + \". For problem: \"+\n # self.problem_name)\n else:\n parent_node.objects[parent_obj_name_for_transformation].attributes[attr_key] = new_value\n\n\n\n # for each child of the semantic web node, create that many clones of the parent node as it's children, this\n # is the number of transformation at this level from parent to child in the semantic web\n num_transformations = len(semantic_web_node.child_nodes)\n if num_transformations > 0:\n # create parent_node clones\n for i in range(0, num_transformations):\n new_node = Node(None, self.clone_parent(parent_node.objects))\n parent_node.child_nodes.append(new_node)\n\n # recursively traverse semantic web of the semantic_web_node's child nodes\n for i in range(0, len(parent_node.child_nodes)):\n self.create_transformation_states(parent_node.child_nodes[i], semantic_web_node.child_nodes[i])\n\n\n def create_object_mapping(self, parent_node, semantic_web_node):\n self.initial_object_context = []\n self.final_object_context = []\n parent_objs = list(parent_node.objects.keys())\n parent_objs.sort()\n for obj in parent_objs:\n if(obj != 'transformation'):\n self.final_object_context.append(obj)\n\n semantic_objs = list(semantic_web_node.objects.keys())\n semantic_objs.sort()\n for obj in semantic_objs:\n if(obj != 'transformation'):\n self.initial_object_context.append(obj)\n\n\n def map_deleted_object_name(self, parent_node, semantic_web_node, obj_key):\n count = 0\n for obj_name in filter(lambda x: x != 'transformation', semantic_web_node.objects):\n if obj_name == obj_key:\n break\n else:\n count += 1\n\n\n if len(parent_node.objects) >= count:\n parent_counter = 0\n for obj in parent_node.objects:\n if count == parent_counter:\n return obj\n else:\n parent_counter += 1\n else:\n # should never get here\n # hacky way to return the first object in the dictionary\n for obj in parent_node.objects:\n return obj\n\n # since object names differ from one figure to the next, we need something to be able to map an object in one figure\n # to an object in another figure\n def map_object_name(self, parent_node, semantic_web_node, object_name):\n self.create_object_mapping(parent_node, semantic_web_node)\n \n initial_name_idx = self.initial_object_context.index(object_name)\n if(initial_name_idx >= 0):\n if initial_name_idx < len(self.final_object_context):\n return self.final_object_context[initial_name_idx]\n else:\n # when object mapping fails, grab smallest object, complete hack\n return None\n # return self.final_object_context[len(self.final_object_context) - 1]\n # something went wrong as the two lists should always be the same length\n # raise Exception(\"mapping failed for initial object name: \"+ object_name + \". Initial object context: \"+ str(self.initial_object_context) \n # + \", final object context: \" + str(self.final_object_context))\n else:\n # something went wrong as the two lists should always be the same length\n # return self.initial_object_context[0]\n return None\n # raise Exception(\"mapping failed for initial object name: \"+ object_name + \". Initial object context: \"+ str(self.initial_object_context) \n # + \", final object context: \" + str(self.final_object_context))\n\n # shape changes occur, we only know about shapes we've seen, this updates the known shapes before trying to solve the problem\n # incase we need that knowledge while solving the problem\n def update_known_shape_types(self, problem):\n for fig in problem.figures:\n for obj in filter(lambda x: x != 'transformation', problem.figures[fig].objects):\n shape = problem.figures[fig].objects[obj].attributes['shape']\n if shape not in self.known_shape_types:\n self.known_shape_types.append(shape)\n\n def encode_size(self, value):\n if(value == \"huge\"):\n value_encoded = [0,0,0,0,0,1]\n elif(value == \"very large\"):\n value_encoded = [0,0,0,0,1,0]\n elif(value == \"large\"):\n value_encoded = [0,0,0,1,0,0]\n elif(value == \"medium\"):\n value_encoded = [0,0,1,0,0,0]\n elif(value == \"small\"):\n value_encoded = [0,1,0,0,0,0]\n elif(value == \"very small\"):\n value_encoded = [1,0,0,0,0,0]\n else:\n # values are already encoded\n value_encoded = value\n return value_encoded\n\n def parse_int(self, value):\n if value == None:\n return value\n else:\n if isinstance(value, int):\n return value\n elif isinstance(value, str) and value.isdigit():\n return int(value)\n \n\nclass Node:\n def __init__(self, transformation, objs):\n self.transformation = transformation\n self.child_nodes = []\n self.objects = objs\n\nclass ChildState:\n def __init__(self):\n self.attributes = {}\n self.name = ''\n","sub_path":"KBAI-package-python/Project-Code-Python/Agent.py","file_name":"Agent.py","file_ext":"py","file_size_in_byte":51752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"64375985","text":"from flask import Flask\nfrom flask_admin import Admin\nfrom flask_admin.contrib.sqla import ModelView\nfrom exts import db\nimport model\n\n\nclass MyView(ModelView):\n can_create = False\n column_list = ('id', 'jobName', 'city', 'salaryDay', 'companyName', 'web_from')\n column_searchable_list = ('jobName', 'companyName')\n\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost/computerjob'\napp.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\ndb.init_app(app)\nadmin = Admin(app, name='后台', template_mode='bootstrap3')\nadmin.add_view(MyView(model.Job, db.session))\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"64999425","text":"\"\"\"compare two solutions\n\"\"\"\nimport subprocess\n\ncases_gen = ['python', 'test.py']\nsolution1 = ['./B']\nsolution2 = ['./ans']\n\ni = 0\nwhile True:\n i += 1\n with open('in.txt', 'w') as f:\n subprocess.call(cases_gen, stdout=f)\n with open('in.txt') as f:\n a = subprocess.check_output(solution1, stdin=f)\n with open('in.txt') as f:\n b = subprocess.check_output(solution2, stdin=f)\n\n print('.', end='', flush=True)\n if a != b:\n print('\\n!!!!!!!!!!!!!!!!!')\n break\n","sub_path":"utils/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"312964127","text":"import tensorflow as tf\nfrom tensorflow.keras.layers import Conv2D, Flatten, Dense, Dropout, Input, Add, Activation, BatchNormalization, GlobalAveragePooling2D\n\n# 畳み込み層を作成\ndef conv(\n filters, \n kernel_size,\n strides=1,\n ):\n return Conv2D(\n filters,\n kernel_size,\n strides=strides,\n padding=\"same\",\n use_bias=False,\n kernel_initializer=\"he_normal\",\n kernel_regularizer=tf.keras.regularizers.l2(0.0001)\n )\n\n# 残差ブロックAを作成\ndef first_residual_unit(filters, strides):\n def f(x):\n # ->BN->ReLU\n x = BatchNormalization()(x)\n b = Activation(\"relu\")(x)\n\n # 畳み込み層->BN->Relu\n x =conv(filters // 4, 1, strides)(b)\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n\n # 畳み込み層->BN->Relu\n x =conv(filters // 4, 3)(x)\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n\n # 畳み込み層\n x = conv(filters, 1)(x)\n\n # ショートカットのシェイプサイズを調整\n sc = conv(filters, 1, strides)(b)\n\n return Add()([x, sc])\n return f\n\n# 残差ブロックBを作成\ndef residual_unit(filters):\n def f(x):\n sc = x\n\n # ->BN->ReLU\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n\n # 畳み込み層->BN->ReLU\n x = conv(filters // 4, 1)(x)\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n\n # 畳み込み層->BN->ReLU\n x = conv(filters // 4, 3)(x)\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n\n # 畳み込み層->\n x = conv(filters, 1)(x)\n\n return Add()([x, sc])\n return f\n\n# 残差ブロックAと残差ブロックBx17を作成\ndef residual_block(filters, strides, unit_size):\n def f(x):\n x = first_residual_unit(filters, strides)(x)\n for i in range(unit_size - 1):\n x = residual_unit(filters)(x)\n return x\n return f\n\n# LearningRateSchedulerを作成\ndef step_decay(epoch):\n x = 0.1\n if epoch >= 80: x = 0.01\n if epoch >= 120: x = 0.001\n return x\n\n# メイン\ndef run():\n ds = tf.keras.datasets.cifar10\n (train_data, train_label), (test_data, test_label) = ds.load_data()\n\n # 初期化\n train_data = tf.keras.utils.normalize(train_data)\n test_data = tf.keras.utils.normalize(test_data)\n\n # one-hot\n train_label = tf.keras.utils.to_categorical(train_label)\n test_label = tf.keras.utils.to_categorical(test_label)\n\n # 入力データのシェイプ\n input = Input(shape=[32,32,3])\n\n # 畳み込み層\n x = conv(16,3)(input)\n\n # 残差ブロックx54\n x = residual_block(64, 1, 18)(x)\n x = residual_block(128, 2, 18)(x)\n x = residual_block(256, 2, 18)(x)\n\n # ->BN->ReLU\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n\n # Pooling\n x = GlobalAveragePooling2D()(x)\n\n # 全結合層\n output = Dense(10, activation=\"softmax\", kernel_regularizer=tf.keras.regularizers.l2(0.0001))(x)\n\n # Model\n model = tf.keras.models.Model(inputs=input, outputs=output)\n\n model.compile(\n loss=tf.keras.losses.categorical_crossentropy,\n optimizer=tf.keras.optimizers.SGD(momentum=0.9),\n metrics=[\"acc\"]\n )\n\n lr_decay = tf.keras.callbacks.LearningRateScheduler(step_decay)\n\n batch_size = 128\n model.fit(\n train_data,\n train_label,\n epochs=1,\n batch_size=batch_size,\n callbacks=[lr_decay]\n )\n\n score = model.evaluate(test_data, test_label, batch_size=batch_size)\n return\n\n","sub_path":"python/keras/L34.py","file_name":"L34.py","file_ext":"py","file_size_in_byte":3636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"552309310","text":"\r\n\r\nx = [int(i) for i in input().split()]\r\na = x[0]\r\nb = x[1]\r\na_p = 0\r\nb_p= 0\r\ndraw = 0\r\n\r\nfor i in range(1,7):\r\n diffA = abs(a-i)\r\n diffB = abs(b-i)\r\n if diffA T:\n ans += T\n else:\n ans += s\n index += 1\nprint(ans+T)\n","sub_path":"ABC024/q2.py","file_name":"q2.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"614490702","text":"import random\n\n\ndef test_searching_in_rotated_array():\n \"\"\"\n 정렬된 배열 A가 어떠한 이유로 한번 회전이 되었습니다.\n 해당 배열에서 값을 찾는 알고리즘을 O(log n)으로 만드세요\n\n A = [15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14] 에서 5를 찾으세요\n 결과 8 (index)\n\n 한번에 해결할수 있는 코드는 09번 bitonic search를 사용하면 됨\n \"\"\"\n\n # Test find_pivot\n for _ in range(20):\n n = random.randint(3, 20)\n pivot_true = random.randint(1, n - 1)\n arr = list(range(n))\n arr = arr[pivot_true:] + arr[:pivot_true]\n pivot_pred = find_pivot(arr, 0, len(arr) - 1)\n assert n - pivot_true == pivot_pred\n\n # Pivot\n assert 8 == search_pivot([15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14], 5)\n assert 0 == search_pivot([15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14], 15)\n assert 5 == search_pivot([15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14], 1)\n assert 4 == search_pivot([15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14], 25)\n assert 11 == search_pivot([15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14], 14)\n assert 0 == search_pivot([15, 10, 13, 14], 15)\n assert 1 == search_pivot([15, 10, 13, 14], 10)\n assert 3 == search_pivot([15, 10, 13, 14], 14)\n\n\ndef search_pivot(arr, target):\n pivot = find_pivot(arr, 0, len(arr) - 1)\n\n if target >= arr[0]:\n return binary_search(arr, 0, pivot, target)\n else:\n return binary_search(arr, pivot, len(arr) - 1, target)\n\n\ndef find_pivot(arr, start, end):\n if start == end:\n return end\n elif start == end - 1:\n if arr[start] >= arr[end]:\n return end\n else:\n return start\n\n mid = (start + end) // 2\n if arr[start] <= arr[mid]:\n return find_pivot(arr, mid, end)\n else:\n return find_pivot(arr, start, mid)\n\n\ndef binary_search(arr, left, right, target):\n while left <= right:\n mid = (left + right) // 2\n\n if arr[mid] == target:\n return mid\n\n if arr[mid] <= target:\n left = mid + 1\n else:\n right = mid - 1\n return -1\n","sub_path":"03 Search/test_08_search_in_rotated_array.py","file_name":"test_08_search_in_rotated_array.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"416652793","text":"from timetableCSP.algorithme.csp_init import *\nfrom timetableCSP.algorithme.mrv import mrv_domains\ncsp = my_csp\n\ncounter = 0\nvar_domains = {}\ndegree_values = {}\n\n#init empty assignment\ndef init_assignment_con(csp):\n global var_domains\n global counter\n counter = 0\n assignment = {}\n for var in csp[VARIABLES]:\n assignment[var] = None\n var_domains[var] = csp[DOMAINS].copy()\n return assignment\n\n\ndef getRoom(csp, assignment,var, value):\n rooms = data._rooms\n rooms.sort(key=lambda c: c[1])\n \n for r in rooms:\n if (r[1] >= var._number_of_students):\n free = True\n for k in csp[VARIABLES]:\n if (assignment[k] is not None):\n if (k._room == r and assignment[k] == value):\n free = False\n if free:\n return r\n\n\n\ndef constraint_propagation(assignment,csp):\n global var_domains\n global counter\n while True:\n if is_complete(assignment):\n return assignment\n var = select_unassigned_variable(csp[VARIABLES],assignment)\n for value in csp[DOMAINS]:\n\n if is_in_domain(var, value):\n \n assignment[var] = value\n add_domains(assignment, csp, var)\n if check_for_zero(assignment,csp):\n var._room = getRoom(csp,assignment, var, value)\n counter+=1\n if is_consistent(assignment, csp[CONSTRAINTS]): \n break\n else: \n assignment[var] = None\n var._room = None\n undo(assignment,csp)\n else:\n assignment[var] = None\n return FAILURE\n\n\n\n\ndef check_for_zero(assignment, csp):\n global var_domains\n\n for i in csp[VARIABLES]:\n r = False\n for j in var_domains[i]:\n if (j is not None):\n r = True\n if r==False:\n return False\n return True\n\n\n\n\ndef is_in_domain(var,value):\n global var_domains\n for d in var_domains[var]:\n if (d == value):\n return True\n return False\n\n\n\ndef add_domains(assignment, csp, value):\n global var_domains\n j = value\n for i in csp[VARIABLES]:\n if (assignment[i] is None):\n if (not i==j):\n if (i._teacher == j._teacher):\n for k in range(len(var_domains[i])):\n if (var_domains[i][k] == assignment[j]):\n var_domains[i][k] = None\n if (i._type_of_class == j._type_of_class):\n for k in range(len(var_domains[i])):\n if (var_domains[i][k] == assignment[j]):\n var_domains[i][k] = None\n if (i._speciality == j._speciality and (i._type_of_class == \"lecture\") or (j._type_of_class == \"lecture\")):\n for k in range(len(var_domains[i])):\n if (var_domains[i][k] == assignment[j]):\n var_domains[i][k] = None\n\n\ndef undo(assignment, csp):\n global var_domains\n for var in csp[VARIABLES]:\n mrv_domains[var] = csp[DOMAINS].copy()\n for i in csp[VARIABLES]:\n for j in csp[VARIABLES]:\n if (assignment[j] is not None):\n if (not i==j):\n if (i._teacher == j._teacher):\n for k in range(len(mrv_domains[i])):\n if (var_domains[i][k] == assignment[j]):\n var_domains[i][k] = None\n if (i._type_of_class == j._type_of_class):\n for k in range(len(var_domains[i])):\n if (var_domains[i][k] == assignment[j]):\n var_domains[i][k] = None\n if (i._speciality == j._speciality and (i._type_of_class == \"lecture\") or (j._type_of_class == \"lecture\")):\n for k in range(len(var_domains[i])):\n if (var_domains[i][k] == assignment[j]):\n var_domains[i][k] = None\n\n\ndef get_counter_con():\n global counter\n return counter\n","sub_path":"timetableCSP/algorithme/constraint_propagation.py","file_name":"constraint_propagation.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"332518407","text":"\n\nfrom xai.brain.wordbase.nouns._stinker import _STINKER\n\n#calss header\nclass _STINKERS(_STINKER, ):\n\tdef __init__(self,): \n\t\t_STINKER.__init__(self)\n\t\tself.name = \"STINKERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"stinker\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_stinkers.py","file_name":"_stinkers.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"346620780","text":"import csv\nimport sys\nfrom cs50 import SQL\nfrom operator import itemgetter\n\n# checks number of input arguments\nif len(sys.argv) != 2:\n print(\"Error\")\n sys.exit(1)\n\ndb = SQL(\"sqlite:///students.db\")\n\n# gets list of dictionaries from SQL query with argv[1]\nstudents = db.execute(f\"SELECT * FROM students WHERE house = \\\"{sys.argv[1]}\\\" ORDER BY last, first\")\n\n# already sorted so check if NULL then print\nfor i in range(len(students)):\n if students[i]['middle'] == None:\n print(f\"{students[i]['first']} {students[i]['last']}, born {students[i]['birth']}\")\n else:\n print(f\"{students[i]['first']} {students[i]['middle']} {students[i]['last']}, born {students[i]['birth']}\")\n\n","sub_path":"pset7/houses/roster.py","file_name":"roster.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"170154161","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as plticker\n\n# INB_3123\n# mcdm_data = np.loadtxt(open(\"/home/pulver/Dropbox/University/PostDoc/MCDM/sim_logs/success_gazebo_INB3123_mcdm/coverage_mcdm.csv\", \"rb\"), delimiter=\",\", skiprows=1)\n# random_frontier = np.loadtxt(open(\"/home/pulver/Dropbox/University/PostDoc/MCDM/sim_logs/success_gazebo_INB3123_rf/gazebo_inb3123_coverage_rf_plot.csv\", \"rb\"), delimiter=\",\", skiprows=1)\n# random_walk = np.loadtxt(open(\"/home/pulver/Dropbox/University/PostDoc/MCDM/sim_logs/success_gazebo_INB3123_rw_5m/gazebo_inb3123_coverage_v2.csv\", \"rb\"), delimiter=\",\", skiprows=1)\n# real = np.loadtxt(open(\"/home/pulver/Dropbox/University/PostDoc/MCDM/sim_logs/success_INB3123/coverage_mcdm.csv\", \"rb\"), delimiter=\",\", skiprows=1)\n\n# INB_ENG\nmcdm_data = np.loadtxt(open(\"/home/pulver/Desktop/MCDM/mcdm/inb_eng_coverage_mcdm_final_td06_20cm.csv\", \"rb\"), delimiter=\",\", skiprows=1)\nrandom_frontier = np.loadtxt(open(\"/home/pulver/Dropbox/University/PostDoc/MCDM/sim_logs/success_gazebo_INB3ENG_rf/gazebo_inb3eng_coverage_v2.csv\", \"rb\"), delimiter=\",\", skiprows=1)\nrandom_walk = np.loadtxt(open(\"/home/pulver/Desktop/MCDM/random_walk/gazebo_ingeng_coverage_v10.csv\", \"rb\"), delimiter=\",\", skiprows=1)\nreal = np.loadtxt(open(\"/home/pulver/Dropbox/University/PostDoc/MCDM/sim_logs/success_INB3ENG/coverage_final.csv\", \"rb\"), delimiter=\",\", skiprows=1)\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8,3.0))\n# fig.suptitle('Map coverage in Gazebo')\n# Labels to use for each line\nline_labels = [\"NBS\", \"RandomFrontier\", \"RandomWalk\", \"Real\"]\n\n\n# Remove the first 4 columns containing the weights value\n# mcdm_data = mcdm_data[:, -3:]\n# random_frontier = random_frontier[:, -3:]\n# random_walk = random_walk[:, -3:]\n# real = real[:, -2:]\n\nmcdm_data = mcdm_data[:, 1:3]\nrandom_frontier = random_frontier[:, 1:3]\nrandom_walk = random_walk[:, 1:3]\nreal = real[:, 1:3]\n\n# Remove duplicare rows\nunique_1 = np.unique(mcdm_data, axis=0)\nunique_2 = np.unique(random_frontier, axis=0)\n# unique_3 = np.unique(random_walk, axis=0)\nunique_4 = np.unique(real, axis=0)\n\n\n# unique_1 = mcdm_data\n# unique_2 = random_frontier\nunique_3 = random_walk\n# unique_4 = real\n\n# x = np.arange(1, unique_1.shape[0] + 1, 1)\n# # Coverage\nl1 = ax1.plot(unique_1[:,0], color='r')[0]\nl2 = ax1.plot(unique_2[:,0], color='b')[0]\nl3 = ax1.plot(unique_3[:,0], color='g')[0]\nl4 = ax1.plot(unique_4[:,0], color='purple')[0]\n#RFID Coverage\nl1 = ax2.plot(unique_1[:,1], color='r')[0]\nl2 = ax2.plot(unique_2[:,1], color='b')[0]\nl3 = ax2.plot(unique_3[:,1], color='g')[0]\nl4 = ax2.plot(unique_4[:,1], color='purple')[0]\n\n# # # Coverage\n# l1 = ax1.plot(mcdm_data[:,0], mcdm_data[:,1], color='b')[0]\n# l2 = ax1.plot(random_frontier[:,0], random_frontier[:,1], color='g')[0]\n# l3 = ax1.plot(random_walk[:,0], random_walk[:,1], color='r')[0]\n# l4 = ax1.plot(real[:,0], real[:,1], color='purple')[0]\n# #RFID Coverage\n# l1 = ax2.plot(mcdm_data[:,0], mcdm_data[:,2], color='b')[0]\n# l2 = ax2.plot(random_frontier[:,0], random_frontier[:,2], color='g')[0]\n# l3 = ax2.plot(random_walk[:,0], random_walk[:,2], color='r')[0]\n# l4 = ax2.plot(real[:,0], real[:,2], color='purple')[0]\n# Add legend\n# plt.legend(loc=9, ncol=3)\nfig.legend([l1, l2, l3, l4], # List of the line objects\n labels= line_labels, # The labels for each line\n loc=\"upper center\", # Position of the legend\n borderaxespad=0.1, # Add little spacing around the legend box\n ncol=4) # Title for the legend\nax1.axvline(x=unique_1.shape[0], color='r', linestyle=\"--\")\nax1.axvline(x=unique_2.shape[0], color='b', linestyle=\"--\")\nax1.axvline(x=unique_3.shape[0], color='g', linestyle=\"--\")\nax1.axvline(x=unique_4.shape[0], color='purple', linestyle=\"--\")\n\nax2.axvline(x=unique_1.shape[0], color='r', linestyle=\"--\")\nax2.axvline(x=unique_2.shape[0], color='b', linestyle=\"--\")\nax2.axvline(x=unique_3.shape[0], color='g', linestyle=\"--\")\nax2.axvline(x=unique_4.shape[0], color='purple', linestyle=\"--\")\n\n# Add titles\n# plt.title(\"Map exploration in Gazebo\", loc='center', fontsize=12, fontweight=0, color='black')\nax1.set_xlabel(\"Robot configuration\")\nax1.set_ylabel(\"Coverage [%]\")\n\nax2.set_xlabel(\"Robot configuration\")\nax2.set_ylabel(\"RFID Coverage [%]\")\n\nax1.set_ylim([0, 100])\nax2.set_ylim([0, 1])\n\nplt.show()","sub_path":"scripts/plot_coverage_gazebo.py","file_name":"plot_coverage_gazebo.py","file_ext":"py","file_size_in_byte":4388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"195652367","text":"from linkedList import arrayifyLinkedList, createLinkedList\n\ndef loopDetection(source_head):\n fast = source_head\n slow = source_head\n while fast and fast.next:\n fast = fast.next.next\n slow = slow.next\n if fast == slow:\n break\n if fast and fast.next:\n slow = source_head\n while slow != fast:\n slow = slow.next\n fast = fast.next\n return fast\n\n\n\nif __name__ == \"__main__\":\n a = createLinkedList([1,2,3,4])\n a.next.next.next = a.next\n print(loopDetection(a).val)\n\n","sub_path":"Chapter 2 Linked Lists/2.8 Loop Detection/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"17975018","text":"# -*- coding: utf-8 -*-\nfrom trytond.model import ModelView, ModelSQL, ModelSingleton, fields\n\nfrom dateutil.relativedelta import *#relativedelta\nfrom datetime import * #datetime, date\nfrom trytond.pool import Pool\nfrom trytond.res import User\nfrom trytond.pyson import Eval, If, DateTime\nfrom trytond.transaction import Transaction\n\nfrom cefiro import *\n\nclass Perfil(ModelSQL,ModelView):\n\t'Perfil'\n\t_name = 'cefiro.perfil'\n\t_description = __doc__\n\n\tname=fields.Char('Nombre')\n\n\tuser = fields.Function(fields.Char('Usuario'),'get_usuario')\n\n\t#reg_usuario = fields.Reference('Registro Referencia')\n\t#reg_usuario = fields.Function(fields.Reference('Registro Usuario'),'get_reg_usuario')\n\n\t#def get_reg_usuario(self,ids,name):\n\t#\tres = {}\n\t#\tuser_obj = Pool().get('res.user')\n\t#\tusrid = Transaction().user\n\t#\tfor elem in self.browse(ids):\n\t#\t\tres[elem.id] = ',<'+str(usrid)+'>'\n\t#\treturn res\n\n\n\tperf=[]\n\tperf2=None\n\n\tdef get_usuario(self,ids,name):\n\t\tres = {}\n\t\tuser_obj = Pool().get('res.user')\n\t\tusrid = Transaction().user\n\t\tusuario = user_obj.browse(usrid)\n\t\tfor elem in self.browse(ids):\n\t\t\tres[elem.id] = usuario.login\n\t\treturn res\n\n\n\t#password = fields.Function(fields.Char(u'Contraseña'),'mensaje','crear')\n\n\n\tperfiles = fields.Function(fields.One2Many('cefiro.psicologo',None,'Perfiles'),'get_perfiles','set_perfiles')\n\n\tperfilesEst = fields.Function(fields.One2Many('cefiro.estudiante',None,'Perfiles'),'get_perfilest','set_perfiles')\n\n\tdef get_perfilest(self,ids,name):\n\t\tres = {}\n\n\t\tuser_obj = Pool().get('res.user')\n\t\tusrid = Transaction().user\n\t\tusuario = user_obj.browse(usrid)\n\n\t\test_obj = Pool().get('cefiro.estudiante')\n\t\testIDsTot = est_obj.search([])\n\n\t\tfor elem in self.browse(ids):\n\t\t\tsol=[]\n\t\t\tfor est in est_obj.browse(estIDsTot):\n\t\t\t\tif (est.login==usuario.login):\n\t\t\t\t\tsol.append(est.id)\n\t\t\tres[elem.id]=sol\n\t\treturn res\n\n\tdef get_perfiles(self,ids,name):\n\t\tres = {}\n\n\t\tuser_obj = Pool().get('res.user')\n\t\tusrid = Transaction().user\n\t\tusuario = user_obj.browse(usrid)\n\n\t\tpsi_obj = Pool().get('cefiro.psicologo')\n\t\tpsiIDsTot = psi_obj.search([])\n\n\t\tfor elem in self.browse(ids):\n\t\t\tsol=[]\n\t\t\tfor psi in psi_obj.browse(psiIDsTot):\n\t\t\t\tif (psi.login==usuario.login):\n\t\t\t\t\tsol.append(psi.id)\n\t\t\tres[elem.id]=sol\n\t\treturn res\n\n\tdef set_perfiles(self,ids,name,value):\n\t\treturn\n\n\t#perfiles = fields.One2Many('cefiro.psicologo',None,'Perfiles',domain=[('login','=',Eval('user'))])\n\nPerfil()\n\n\n\n\n\n","sub_path":"perfil.py","file_name":"perfil.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"78023125","text":"import chainer\nfrom chainer import cuda\nfrom chainer import function\nfrom chainer.functions.array import split_axis\nfrom chainer import link\nfrom chainer.links.connection import linear\nfrom chainer.utils import type_check\nimport numpy\n\n\nclass SigmoidAPLusBMultipliedByC(function.Function):\n \"\"\"SigmoidAPLusBMultipliedByC function. Computes sigmoid(a + b) * c.\n\n This is faster than doing the same thing by composing chainer operations.\n Used to optimize GRUs.\n \"\"\"\n\n def check_type_forward(self, in_types):\n type_check.expect(in_types.size() == 3)\n type_check.expect(in_types[0].dtype == numpy.float32)\n type_check.expect(in_types[1].dtype == numpy.float32)\n type_check.expect(in_types[2].dtype == numpy.float32)\n\n def forward_cpu(self, x):\n self.sigma_a_plus_b = (numpy.tanh((x[0] + x[1]) * 0.5) * 0.5 + 0.5)\n return x[2] * self.sigma_a_plus_b,\n\n def forward_gpu(self, x):\n self.sigma_a_plus_b, y = cuda.elementwise(\n 'T x1, T x2, T x3', 'T sigma_a_plus_b, T y',\n '''\n sigma_a_plus_b = tanh((x1 + x2) * 0.5) * 0.5 + 0.5;\n y = x3 * sigma_a_plus_b;\n ''',\n 'sigmoid_a_plus_b_by_c_fwd')(x[0], x[1], x[2])\n return y,\n\n def backward_cpu(self, x, gy):\n gy_by_sigma_a_plus_b = gy[0] * self.sigma_a_plus_b\n deriv1 = x[2] * gy_by_sigma_a_plus_b * (1 - self.sigma_a_plus_b)\n return deriv1, deriv1, gy_by_sigma_a_plus_b\n\n def backward_gpu(self, x, gy):\n gx1, gx2, gx3 = cuda.elementwise(\n 'T sigma_a_plus_b, T h, T gy', 'T gx1, T gx2, T gx3',\n '''\n gx3 = gy * sigma_a_plus_b;\n gx1 = h * gx3 * (1-sigma_a_plus_b);\n gx2 = gx1;\n ''',\n 'sigmoid_a_plus_b_by_c_bwd')(self.sigma_a_plus_b, x[2], gy[0])\n return gx1, gx2, gx3,\n\n\ndef sigmoid_a_plus_b_multiplied_by_c(a, b, c):\n \"\"\"Compute sigmoid(a + b) * c\"\"\"\n return SigmoidAPLusBMultipliedByC()(a, b, c)\n\n\nclass ComputeOutputGRU(function.Function):\n\n \"\"\"Function used to compute the output of a GRU.\n\n More precisely, given the five inputs z_x, z_h, h_x, h and hh, it computes:\n z = sigmoid(z_x + z_h)\n h_bar = tanh(h_x + hh)\n h_new = (1 - z) * h + z * h_bar\n return h_new\n \"\"\"\n\n# def __init__(self):\n# self.use_cudnn = use_cudnn\n\n def check_type_forward(self, in_types):\n type_check.expect(in_types.size() == 5)\n type_check.expect(in_types[0].dtype == numpy.float32)\n type_check.expect(in_types[1].dtype == numpy.float32)\n type_check.expect(in_types[2].dtype == numpy.float32)\n type_check.expect(in_types[3].dtype == numpy.float32)\n type_check.expect(in_types[4].dtype == numpy.float32)\n\n def forward_cpu(self, x):\n z_x, z_h, h_x, h, hh = x\n z = 1.0 / (1 + numpy.exp(- (z_x + z_h)))\n h_bar = numpy.tanh(h_x + hh)\n h_new = (1 - z) * h + z * h_bar\n self.z = z\n self.h_bar = h_bar\n return h_new,\n\n def forward_gpu(self, x):\n z_x, z_h, h_x, h, hh = x\n self.z, self.h_bar, h_new = cuda.elementwise(\n 'T z_x, T z_h, T h_x, T h, T hh',\n 'T z, T h_bar, T h_new',\n '''\n z = tanh((z_x + z_h) * 0.5) * 0.5 + 0.5;\n h_bar = tanh(h_x + hh);\n h_new = (1 - z) * h + z * h_bar;\n ''',\n 'compute_output_gru_fwd')(z_x, z_h, h_x, h, hh)\n return h_new,\n\n def backward_cpu(self, x, gy):\n z_x, z_h, h_x, h, hh = x\n g_h = (1 - self.z) * gy[0]\n g_hh = self.z * (1 - self.h_bar * self.h_bar) * gy[0]\n g_h_x = g_hh\n g_z_x = g_h * self.z * (self.h_bar - h)\n g_z_h = g_z_x\n return g_z_x, g_z_h, g_h_x, g_h, g_hh\n\n def backward_gpu(self, x, gy):\n z_x, z_h, h_x, h, hh = x\n g_z_x, g_z_h, g_h_x, g_h, g_hh = cuda.elementwise(\n 'T z, T h_bar, T h, T gy', 'T g_z_x, T g_z_h, T g_h_x, T g_h, T g_hh', '''\n g_h = (1 - z) * gy;\n g_hh = z * (1 - h_bar * h_bar) * gy;\n g_h_x = g_hh;\n g_z_x = g_h * z * (h_bar - h);\n g_z_h = g_z_x;\n ''', 'compute_output_gru_bwd')(\n self.z, self.h_bar, h, gy[0])\n return g_z_x, g_z_h, g_h_x, g_h, g_hh,\n\n\ndef compute_output_GRU(z_x, z_h, h_x, h, hh):\n \"\"\"Function used to compute the output of a GRU.\n\n More precisely, given the five inputs z_x, z_h, h_x, h and hh, it computes:\n z = sigmoid(z_x + z_h)\n h_bar = tanh(h_x + hh)\n h_new = (1 - z) * h + z * h_bar\n return h_new\n \"\"\"\n return ComputeOutputGRU()(z_x, z_h, h_x, h, hh)\n\n\nclass GRUBase(link.Chain):\n \"\"\"GRUBase instantiate the linear links that parameterize a GRU.\n\n Contrarily to gru.GRUBase, fast_gru.GRUBase only instantiate 3 linear links\n (vs 6 for gru.GRUBase)\n W_r_z_h merge the links W_r, W_z and W_h of gru.GRUBase\n U_r_z merge the links U_r and U_z of gru.GRUBase. In addition, these\n links do not have biases,\n as it would be redundant with the biases of W_r_z_h.\n U is equivalent to the link U of gru.GRUBase\n (minus the redundant bias).\n \"\"\"\n\n def __init__(self, n_units, n_inputs=None):\n if n_inputs is None:\n n_inputs = n_units\n super(GRUBase, self).__init__(\n W_r_z_h=linear.Linear(n_inputs, n_units * 3),\n U_r_z=linear.Linear(n_units, n_units * 2, nobias=True),\n U=linear.Linear(n_units, n_units, nobias=True),\n )\n self.n_units = n_units\n self.n_inputs = n_inputs\n\n def initialize_with_classic_implementation(self, gru):\n \"\"\"Initialize the parameters from a gru.GRUBase object.\n\n self and gru should be on the same device.\n \"\"\"\n assert isinstance(gru, chainer.links.connection.gru.GRUBase)\n # input matrices\n self.W_r_z_h.W.data[:self.n_units] = gru.W_r.W.data\n self.W_r_z_h.W.data[self.n_units: 2 * self.n_units] = gru.W_z.W.data\n self.W_r_z_h.W.data[2 * self.n_units:] = gru.W.W.data\n\n # biases\n self.W_r_z_h.b.data[:self.n_units] = gru.W_r.b.data + gru.U_r.b.data\n self.W_r_z_h.b.data[self.n_units: 2 *\n self.n_units] = gru.W_z.b.data + gru.U_z.b.data\n self.W_r_z_h.b.data[2 * self.n_units:] = gru.W.b.data + gru.U.b.data\n\n # hidden state matrices\n self.U_r_z.W.data[:self.n_units] = gru.U_r.W.data\n self.U_r_z.W.data[self.n_units:] = gru.U_z.W.data\n\n self.U.W.data[...] = gru.U.W.data\n\n @classmethod\n def from_classic_GRU(cls, gru):\n \"\"\"Creates a FastGRU object from a GRU object.\"\"\"\n assert isinstance(gru, chainer.links.connection.gru.GRUBase)\n n_units, n_inputs = gru.W_r.W.data.shape\n fast_gru = cls(n_units, n_inputs)\n\n # move to the correct device\n if not isinstance(gru.W_r.W.data, numpy.ndarray):\n fast_gru = fast_gru.to_gpu(chainer.cuda.get_device(gru.W_r.W.data))\n\n fast_gru.initialize_with_classic_implementation(gru)\n return fast_gru\n\n def to_classic_GRU(self):\n \"\"\"Convert to an object of type gru.GRU\n\n Useful for testing / converting models.\n \"\"\"\n gru = chainer.links.connection.gru.GRU(self.n_units, self.n_inputs)\n\n # move to the correct device\n if not isinstance(self.W_r_z_h.W.data, numpy.ndarray):\n gru = gru.to_gpu(chainer.cuda.get_device(self.W_r_z_h.W.data))\n\n # input matrices\n gru.W_r.W.data[...] = self.W_r_z_h.W.data[:self.n_units]\n gru.W_z.W.data[...] = self.W_r_z_h.W.data[\n self.n_units: 2 * self.n_units]\n gru.W.W.data[...] = self.W_r_z_h.W.data[2 * self.n_units:]\n\n # biases\n gru.W_r.b.data[...] = self.W_r_z_h.b.data[:self.n_units]\n gru.W_z.b.data[...] = self.W_r_z_h.b.data[\n self.n_units: 2 * self.n_units]\n gru.W.b.data[...] = self.W_r_z_h.b.data[2 * self.n_units:]\n\n gru.U_r.b.data[...] = 0\n gru.U_z.b.data[...] = 0\n gru.U.b.data[...] = 0\n\n # hidden state matrices\n gru.U_r.W.data[...] = self.U_r_z.W.data[:self.n_units]\n gru.U_z.W.data[...] = self.U_r_z.W.data[self.n_units:]\n\n gru.U.W.data[...] = self.U.W.data[...]\n\n return gru\n\n\nclass GRU(GRUBase):\n\n \"\"\"Stateless Gated Recurrent Unit function (GRU).\n\n GRU function has six parameters :math:`W_r`, :math:`W_z`, :math:`W`,\n :math:`U_r`, :math:`U_z`, and :math:`U`. All these parameters are\n :math:`n \\\\times n` matrices, where :math:`n` is the dimension of\n hidden vectors.\n\n Given two inputs a previous hidden vector :math:`h` and an input vector\n :math:`x`, GRU returns the next hidden vector :math:`h'` defined as\n\n .. math::\n\n r &=& \\\\sigma(W_r x + U_r h), \\\\\\\\\n z &=& \\\\sigma(W_z x + U_z h), \\\\\\\\\n \\\\bar{h} &=& \\\\tanh(W x + U (r \\\\odot h)), \\\\\\\\\n h' &=& (1 - z) \\\\odot h + z \\\\odot \\\\bar{h},\n\n where :math:`\\\\sigma` is the sigmoid function, and :math:`\\\\odot` is the\n element-wise product.\n\n :class:`~chainer.links.GRU` does not hold the value of\n hidden vector :math:`h`. So this is *stateless*.\n Use :class:`~chainer.links.StatefulGRU` as a *stateful* GRU.\n\n Args:\n n_units(int): Dimension of hidden vector :math:`h`.\n n_inputs(int): Dimension of input vector :math:`x`. If ``None``,\n it is set to the same value as ``n_units``.\n\n See:\n - `On the Properties of Neural Machine Translation: Encoder-Decoder\n Approaches `_\n [Cho+, SSST2014].\n - `Empirical Evaluation of Gated Recurrent Neural Networks on Sequence\n Modeling `_\n [Chung+NIPS2014 DLWorkshop].\n\n\n .. seealso:: :class:`~chainer.links.StatefulGRU`\n \"\"\"\n\n def __call__(self, h, x):\n # We compute r_x, z_x and h_x simultaneously\n r_z_h_x = self.W_r_z_h(x)\n r_x, z_x, h_x = split_axis.split_axis(\n r_z_h_x, (self.n_units, self.n_units * 2), axis=1)\n\n # We compute r_h and z_h simultaneously\n r_z_h = self.U_r_z(h)\n r_h, z_h = split_axis.split_axis(r_z_h, (self.n_units,), axis=1)\n\n # finally we compute the output using the optimized functions\n return compute_output_GRU(\n z_x,\n z_h,\n h_x,\n h,\n self.U(sigmoid_a_plus_b_multiplied_by_c(r_x, r_h, h))\n )\n","sub_path":"chainer/links/connection/fast_gru.py","file_name":"fast_gru.py","file_ext":"py","file_size_in_byte":10594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"582127140","text":"#!/usr/bin/python2\n\n\n\"\"\"\nStatement:\nThe number, 197, is called a circular prime because all rotations of the\ndigits: 197, 971, and 719, are themselves prime.\n\nThere are thirteen such primes below 100:\n2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.\n\nHow many circular primes are there below one million?\n\"\"\"\n\nfrom unittest import TestCase, main\nfrom utils import prime_sieve\n\n\nclass Problem35(object):\n def __init__(self, limit):\n self._limit = limit\n\n def circular_num(self, prime):\n circular_nums = [prime]\n length = len(str(prime))\n mf = 1\n for i in xrange(length - 1):\n mf *= 10\n for i in xrange(length - 1):\n tmp = mf * (prime % 10)\n prime = tmp + prime / 10\n circular_nums.append(prime)\n return circular_nums\n\n def fn(self):\n count = 0\n primes = prime_sieve(self._limit)\n for i, v in enumerate(primes):\n if v:\n circular_nums = self.circular_num(i)\n if all(primes[p] for p in circular_nums):\n count += 1\n return count\n\n\nclass TestProblem35(TestCase):\n def setUp(self):\n self.limit = 1000000\n self.answer = 55\n\n def test_fn(self):\n self.assertEqual(Problem35(self.limit).fn(), self.answer)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"35.py","file_name":"35.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"234840493","text":"from tornado.httpclient import AsyncHTTPClient, HTTPRequest\r\nfrom tornado.web import asynchronous, RequestHandler\r\n\r\nclass OperaMiniMirror(RequestHandler):\r\n def get(self):\r\n self.set_header('Content-Type', 'text/plain; charset=ascii')\r\n self.set_status(400, 'This page can only access with POST request.')\r\n self.finish('This page can only access with POST request.')\r\n @asynchronous\r\n def post(self):\r\n server_url = 'http://mini5.opera-mini.net/'\r\n prefer_list = self.request.headers.get_list('x-prefer-server')\r\n if prefer_list: server_url = 'http://' + prefer_list[0] + '/'\r\n headers = {'Content-Type': 'application/xml', 'Connection': 'Keep-Alive'}\r\n req = HTTPRequest(server_url, 'POST', headers, self.request.body)\r\n http_client = AsyncHTTPClient()\r\n http_client.fetch(req, self.echo_to_client)\r\n self.set_header('Content-Type', 'application/octet-stream')\r\n self.set_header('Cache-Control', 'private, no-cache')\r\n def echo_to_client(self, response):\r\n self.finish(response.body)","sub_path":"omm.py","file_name":"omm.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"279445309","text":"#!/usr/bin/env python3\n'''\nSolution for \"Reverse Nodes in k-Group\"\n'''\n\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\ndef print_ListNode(head):\n result = \"\"\n if head:\n result += str(head.val)\n\n while head.next:\n head = head.next\n result += ' -> '\n result += str(head.val)\n \n print(result)\n\ndef init_ListNode(mlist):\n if len(mlist) == 0:\n return None\n current = ListNode(mlist[0])\n head = current\n for i in mlist[1:]:\n next_one = ListNode(i)\n current.next = next_one\n current = next_one\n return head\n\nclass Solution(object):\n def reverseKGroup(self, head, k):\n \"\"\"\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n \"\"\"\n def swap_nextk(lead, next_chain):\n count = 1\n current = lead.next\n return_node = lead.next\n left = next_chain\n while count <= k:\n right = current.next\n tmp = current\n current.next = left\n left = current\n current = right\n count += 1\n lead.next = tmp\n return return_node\n \n dummy = ListNode(0)\n dummy.next = head\n current = dummy\n while True:\n count = 0\n tmp = current\n have_next_k = True\n while count <= k:\n if count == k:\n before = tmp\n if tmp:\n tmp = tmp.next\n count += 1\n else:\n have_next_k = False\n break\n if have_next_k:\n current = swap_nextk(current, before.next)\n else:\n break\n return dummy.next\n\n\nif __name__ == \"__main__\":\n print_ListNode(Solution().reverseKGroup(init_ListNode([1,2,3,4,5,6,7,8]),3))","sub_path":"25/25.py","file_name":"25.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"98859469","text":"__all__ = \"Client\"\n\nimport random\nimport typing as t\n\nimport requests\nimport requests_cache\n\nfrom ..base import BaseClient\nfrom ..exceptions import (\n GuildNotFoundError,\n HypixelAPIError,\n InvalidArgumentError,\n PlayerNotFoundError,\n RateLimitError,\n)\nfrom ..models import (\n boosters,\n caching,\n find_guild,\n friends,\n games,\n guild,\n key,\n leaderboard,\n player,\n player_status,\n recent_games,\n skyblock,\n watchdog,\n)\nfrom ..utils.constants import (\n HYPIXEL_API,\n TIMEOUT,\n)\nfrom ..utils.url import form_url\n\n\nclass Client(BaseClient):\n \"\"\"\n The client for this wrapper, that handles the requests, authentication, loading and usages of the end user.\n\n Examples\n --------\n If you have a single API key, Here's how to authenticate\n\n >>> import hypixelio\n >>> client = hypixelio.Client(api_key=\"123-456-789\")\n\n Or, If you have multiple API keys (Better option for load balancing)\n\n >>> client = hypixelio.Client(api_key=[\"123-456\", \"789-000\", \"568-908\"])\n\n If you want to enable caching, Here's how to do it\n >>> client = hypixelio.Client(cache=True)\n\n And configuring cache\n >>> from hypixelio.models.caching import Caching, CacheBackend\n >>> cache_cfg = Caching(cache_name=\"my-cache\", backend=CacheBackend.sqlite, expire_after=10)\n >>> client = hypixelio.Client(cache=True, cache_config=cache_cfg)\n\n Notes\n -----\n Keep in mind that, your keys wouldn't work if you're banned from hypixel, or if they're expired.\n And if you opt for redis, it connects with the default port and host available. For sqlite it\n creates a `.db` file.\n \"\"\"\n\n def __init__(\n self, api_key: t.Union[str, list], cache: bool = False,\n cache_config: t.Optional[caching.Caching] = None\n ) -> None:\n \"\"\"\n Parameters\n ----------\n api_key: `t.Union[str, list]`\n The API Key generated in Hypixel using `/api new` command.\n cache: `t.Optional[bool]`\n Whether to enable caching\n cache_config: `t.Optional[caching.Caching]`\n The configuration for the saving, and reusing of the cache. Defaults to None.\n \"\"\"\n super().__init__(api_key)\n\n if cache:\n if cache_config is None:\n cache_config = caching.Caching(expire_after=30, old_data_on_error=True)\n\n requests_cache.install_cache(\n cache_name=cache_config.cache_name,\n backend=cache_config.backend,\n expire_after=cache_config.expire_after,\n old_data_on_error=cache_config.old_data_on_error,\n )\n\n def _fetch(self, url: str, data: dict = None, api_key: bool = True) -> dict:\n \"\"\"\n Get the JSON Response from the Root Hypixel API URL, and also add the ability to include the GET request\n parameters with the API KEY Parameter by default.\n\n Parameters\n ----------\n url: `str`\n The URL to be accessed from the Root Domain.\n data: `t.Optional[dict]`\n The GET Request's Key-Value Pair. Example: {\"uuid\": \"abc\"} is converted to `?uuid=abc`. Defaults to None.\n api_key: bool\n If key is needed for the endpoint.\n\n Returns\n -------\n `t.Tuple[dict, bool]`\n The JSON Response from the Fetch Done to the API and the SUCCESS Value from the Response.\n \"\"\"\n # Check if ratelimit is hit\n if self._is_ratelimit_hit():\n raise RateLimitError(f\"Retry after {self.retry_after}\")\n\n # If no data for JSON\n if not data:\n data = {}\n\n # Assign a random key if the Key parameter exists.\n if api_key:\n self.headers[\"API-Key\"] = random.choice(self._api_key)\n\n # Form the URL to fetch\n url = form_url(HYPIXEL_API, url, data)\n\n # Core fetch logic\n with requests.get(url, timeout=TIMEOUT, headers=self.headers) as response:\n # 429 Code handle\n if response.status_code == 429:\n self._handle_ratelimit(response.headers)\n\n # 400 Code handle\n if response.status_code == 400:\n raise HypixelAPIError(reason=\"Invalid key specified!\")\n\n # Ratelimit handling\n if api_key and \"RateLimit-Limit\" in response.headers:\n self._update_ratelimit(response.headers)\n\n try:\n json = response.json()\n except Exception as exc:\n raise HypixelAPIError(f\"{exc}\")\n else:\n if not json[\"success\"]:\n self._handle_api_failure(json)\n\n return json\n\n def get_key_info(self, api_key: t.Optional[str] = None) -> key.Key:\n \"\"\"\n Get the Info about an API Key generated in Hypixel.\n\n Parameters\n ----------\n api_key: `t.Optional[str]`\n The API Key generated in Hypixel using `/api new` command. Defaults to None.\n\n Returns\n -------\n `key.Key`\n Key object for the API Key.\n \"\"\"\n if not api_key:\n api_key = random.choice(self._api_key)\n\n json = self._fetch(self.url[\"api_key\"], {\"key\": api_key})\n return key.Key(json[\"record\"])\n\n def get_boosters(self) -> boosters.Boosters:\n \"\"\"\n Get the List of Hypixel Coin Boosters and Their Info.\n\n Returns\n -------\n `boosters.Boosters`\n The Booster class object which depicts the booster data model.\n \"\"\"\n json = self._fetch(self.url[\"boosters\"])\n\n return boosters.Boosters(json[\"boosters\"], json)\n\n def get_player(\n self, name: t.Optional[str] = None, uuid: t.Optional[str] = None\n ) -> player.Player:\n \"\"\"\n Get the Info about a Hypixel Player using either his Username or UUID.\n\n Parameters\n ----------\n name: `t.Optional[str]`\n The Optional string value for the Username. Defaults to None.\n uuid: `t.Optional[str]`\n The Optional string Value to the UUID. Defaults to None.\n\n Returns\n -------\n `player.Player`\n The Player Class Object, Which depicts the Player Data Model\n \"\"\"\n uuid = self._filter_name_uuid(name, uuid)\n json = self._fetch(self.url[\"player\"], {\"uuid\": uuid})\n\n if not json[\"player\"]:\n raise PlayerNotFoundError(\"Null Value is returned\", name)\n\n return player.Player(json[\"player\"])\n\n def get_friends(\n self, name: t.Optional[str] = None, uuid: t.Optional[str] = None\n ) -> friends.Friends:\n \"\"\"\n Get the List of Friends of a Hypixel Player and their Info.\n\n Parameters\n ----------\n name: `t.Optional[str]`\n The Optional string value for the Username of a hypixel player.. Defaults to None.\n uuid: `t.Optional[str]`\n The UUID of a Certain Hypixel Player. Defaults to None.\n\n Returns\n -------\n `friends.Friends`\n Returns the Friend Data Model, Which has the List of Friends, each with a list of attributes.\n \"\"\"\n uuid = self._filter_name_uuid(name, uuid)\n json = self._fetch(self.url[\"friends\"], {\"uuid\": uuid})\n\n return friends.Friends(json[\"records\"])\n\n def get_watchdog_info(self) -> watchdog.Watchdog:\n \"\"\"\n Get the List of Stats About the Watchdog for the last few days.\n\n Returns\n -------\n `watchdog.Watchdog`\n The Watchdog data model with certain important attributes for you to get data about the things by watchdog.\n \"\"\"\n json = self._fetch(self.url[\"watchdog\"])\n\n return watchdog.Watchdog(json)\n\n def get_guild(\n self, name: t.Optional[str] = None, uuid: t.Optional[str] = None\n ) -> guild.Guild:\n \"\"\"\n Get the info about a Hypixel Guild, Either using Name or UUID.\n\n Parameters\n ----------\n name: `t.Optional[str]`\n The Name of the Guild. Defaults to None.\n uuid: `t.Optional[str]`\n The ID Of the guild. Defaults to None.\n\n Returns\n -------\n `guild.Guild`\n The Guild Object with certain Attributes for you to access, and use it.\n \"\"\"\n if uuid:\n json = self._fetch(self.url[\"guild\"], {\"id\": uuid})\n elif name:\n json = self._fetch(self.url[\"guild\"], {\"name\": name})\n else:\n raise InvalidArgumentError(\n \"Please provide a Named argument of the guild's Name or guild's ID.\"\n )\n\n if not json[\"guild\"]:\n raise GuildNotFoundError(\"Return Value is null\")\n\n return guild.Guild(json[\"guild\"])\n\n def get_games_info(self) -> games.Games:\n \"\"\"\n Get the List of Hypixel Games and Their Info.\n\n Returns\n -------\n `games.Games`\n The Games Data model, Containing the information, and attributes for all the games.\n \"\"\"\n json = self._fetch(self.url[\"game_info\"])\n\n return games.Games(json[\"games\"], json[\"playerCount\"])\n\n def get_leaderboards(self) -> leaderboard.Leaderboard:\n \"\"\"\n Get the Leaderboard for all the games, along with the data in it.\n\n Returns\n -------\n `leaderboard.Leaderboard`\n The Leaderboard data model, containing all the ranking for the games in Hypixel.\n \"\"\"\n json = self._fetch(self.url[\"leaderboards\"])\n\n return leaderboard.Leaderboard(json[\"leaderboards\"])\n\n def find_guild(\n self, guild_name: t.Optional[str] = None, player_uuid: t.Optional[str] = None\n ) -> find_guild.FindGuild:\n \"\"\"\n Finds the Guild By the Guild's Name or using a Player's UUID\n\n Parameters\n ----------\n guild_name: `t.Optional[str]`\n The name of the Guild. Defaults to None.\n player_uuid: `t.Optional[str]`\n The UUID of the Player to find his guild. Defaults to None.\n\n Returns\n -------\n `find_guild.FindGuild`\n The ID of the guild being find.\n \"\"\"\n if guild_name:\n json = self._fetch(self.url[\"find_guild\"], {\"byName\": guild_name})\n elif player_uuid:\n json = self._fetch(self.url[\"find_guild\"], {\"byUuid\": player_uuid})\n else:\n raise InvalidArgumentError(\n \"Please provide a Named argument of the guild's Name or guild's ID.\"\n )\n\n return find_guild.FindGuild(json)\n\n def get_player_status(\n self, name: t.Optional[str] = None, uuid: t.Optional[str] = None\n ) -> player_status.PlayerStatus:\n \"\"\"\n Get the Status info about a Hypixel Player using either his Username or UUID.\n\n Parameters\n ----------\n name: `t.Optional[str]`\n The Optional string value for the Username. Defaults to None.\n uuid: `t.Optional[str]`\n The Optional string Value to the UUID. Defaults to None.\n\n Returns\n -------\n `player_status.PlayerStatus`\n The Player Status Object, which depicts the Player's status\n \"\"\"\n uuid = self._filter_name_uuid(name, uuid)\n json = self._fetch(self.url[\"status\"], {\"uuid\": uuid})\n\n return player_status.PlayerStatus(json)\n\n def get_player_recent_games(\n self, name: t.Optional[str] = None, uuid: t.Optional[str] = None\n ) -> recent_games.RecentGames:\n \"\"\"\n Get the recent games played by a Hypixel Player using either his Username or UUID.\n\n Parameters\n ----------\n name: `t.Optional[str]`\n The Optional string value for the Username. Defaults to None.\n uuid: `t.Optional[str]`\n The Optional string Value to the UUID. Defaults to None.\n\n Returns\n -------\n `recent_games.RecentGames`\n The recent games model for the respective player specified.\n \"\"\"\n uuid = self._filter_name_uuid(name, uuid)\n json = self._fetch(self.url[\"recent_games\"], {\"uuid\": uuid})\n\n return recent_games.RecentGames(json)\n\n def get_skyblock_profile(\n self, name: t.Optional[str] = None, uuid: t.Optional[str] = None\n ) -> skyblock.SkyblockProfile:\n \"\"\"\n Get the skyblock information and profile about a specific user as passed in the requirements.\n\n Parameters\n ----------\n name: `str`\n The player's name in Hypixel\n uuid: `str`\n The player's global UUID\n\n Returns\n -------\n `skyblock.SkyblockProfile`\n The skyblock profile model for the user.\n \"\"\"\n uuid = self._filter_name_uuid(name, uuid)\n json = self._fetch(self.url[\"skyblock_profile\"], {\"profile\": uuid})\n\n if not json[\"profile\"]:\n raise PlayerNotFoundError(\n \"The skyblock player being searched does not exist!\", uuid\n )\n\n return skyblock.SkyblockProfile(json)\n\n def get_skyblock_user_auctions(\n self, name: t.Optional[str] = None, uuid: t.Optional[str] = None\n ) -> skyblock.SkyblockUserAuction:\n \"\"\"\n Get the skyblock auction info about a specific user as passed in the requirements.\n\n Parameters\n ----------\n name: `str`\n The player's name in Hypixel\n uuid: `str`\n The player's global UUID\n\n Returns\n -------\n `skyblock.SkyblockUserAuction`\n The skyblock auction model for the user.\n \"\"\"\n uuid = self._filter_name_uuid(name, uuid)\n json = self._fetch(self.url[\"skyblock_auctions\"], {\"profile\": uuid})\n\n if not json[\"auctions\"]:\n raise PlayerNotFoundError(\n \"The skyblock player being searched does not exist!\", uuid\n )\n\n return skyblock.SkyblockUserAuction(json)\n\n def get_skyblock_active_auctions(\n self, page: int = 0\n ) -> skyblock.SkyblockActiveAuction:\n \"\"\"\n Get the list of active auctions in skyblock and use the data.\n\n Parameters\n ----------\n page: int\n The skyblock auction page to lookup.\n\n Returns\n -------\n skyblock.SkyblockActiveAuction\n The active auction model.\n \"\"\"\n json = self._fetch(self.url[\"skyblock_active_auctions\"], {\"page\": page})\n return skyblock.SkyblockActiveAuction(json)\n\n def get_skyblock_bazaar(self) -> skyblock.SkyblockBazaar:\n \"\"\"\n Get the skyblock bazaar items\n\n Returns\n -------\n skyblock.SkyblockBazaar\n The bazaar model object representing each product.\n \"\"\"\n json = self._fetch(self.url[\"skyblock_bazaar\"])\n return skyblock.SkyblockBazaar(json)\n\n def get_resources_achievements(self) -> dict:\n \"\"\"\n Get the current resources.\n\n Returns\n -------\n dict\n Hypixel API response.\n \"\"\"\n data = self._fetch(self.url[\"achievements\"], api_key=False)\n return data[\"achievements\"]\n\n def get_resources_challenges(self) -> dict:\n \"\"\"\n Get the current resources.\n\n Returns\n -------\n dict\n Hypixel API response.\n \"\"\"\n data = self._fetch(self.url[\"challenges\"], api_key=False)\n return data[\"challenges\"]\n\n def get_resources_quests(self) -> dict:\n \"\"\"\n Get the current resources.\n\n Returns\n -------\n dict\n Hypixel API response.\n \"\"\"\n data = self._fetch(self.url[\"quests\"], api_key=False)\n return data[\"quests\"]\n\n def get_resources_guild_achievements(self) -> dict:\n \"\"\"\n Get the current resources.\n\n Returns\n -------\n dict\n Hypixel API response.\n \"\"\"\n data = self._fetch(self.url[\"guild_achievements\"], api_key=False)\n return {\"one_time\": data[\"one_time\"], \"tiered\": data[\"tiered\"]}\n","sub_path":"hypixelio/lib/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":16074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"492366818","text":"import sys,os\nimport argparse\nfrom yolo import YOLO, detect_video\nfrom PIL import Image\nimport cv2\n\n#制作适用于mtcnn的上半身检测数据集\n\n\ndef detect_img(yolo):\n image_path = '/home/lichen/keras-yolo3/images/'\n txt_data = open(\"/home/lichen/keras-yolo3/person.txt\",\"w\")\n for img in os.listdir(image_path):\n img_path = image_path + img\n image = Image.open(img_path)\n print(img_path)\n\n try:\n top, left, bottom, right = yolo.detect_image(image,img_path)\n except:\n continue\n finally:\n txt_data.write(str(img_path)+\" \")\n txt_data.write(str(left)+\" \")\n txt_data.write(str(top)+\" \")\n txt_data.write(str(abs(right-left))+\" \")\n txt_data.write(str(abs(bottom-top)))\n txt_data.write(\"\\n\")\n txt_data.close()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)\n parser.add_argument(\n '--model', type=str,default=\"/home/lichen/keras-yolo3/model_data/yolo.h5\",\n help='path to model weight file, default ' + YOLO.get_defaults(\"model_path\")\n )\n parser.add_argument(\n '--anchors', type=str,default=\"/home/lichen/keras-yolo3/model_data/yolo_anchors.txt\",\n help='path to anchor definitions, default ' + YOLO.get_defaults(\"anchors_path\")\n )\n parser.add_argument(\n '--classes', type=str,default=\"person\",\n help='path to class definitions, default ' + YOLO.get_defaults(\"classes_path\")\n )\n parser.add_argument(\n '--gpu_num', type=int,default=0,\n help='Number of GPU to use, default ' + str(YOLO.get_defaults(\"gpu_num\"))\n )\n parser.add_argument(\n \"--input\", nargs='?', type=str,required=False,default='/home/lichen/keras-yolo3/images/',\n help = \"Video input path\"\n )\n parser.add_argument(\n \"--output\", nargs='?', type=str, default=\"\",\n help = \"[Optional] Video output path\"\n )\n FLAGS = parser.parse_args()\n detect_img(YOLO(**vars(FLAGS)))\n\n\n\n\n","sub_path":"new_file/yolo_image.py","file_name":"yolo_image.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"631342464","text":"#This is my geometry code\nimport numpy\nimport sys\nimport os\n\nxyz_file = os.path.join('data','benzene.xyz')\noutfile = open(xyz_file, 'r')\ndata = outfile.readlines()\noutfile.close()\nwaterdata = data[2:]\ninitialcoords = []\ncoords = []\nsymbols = []\nfor i in range(0,len(waterdata)):\n initialcoords.append(waterdata[i].split())\n symbols.append(initialcoords[i][0])\ncoords = numpy.array(initialcoords)[:,1:].astype(numpy.float)\ndef calculate_distance(atom1,atom2):\n \"\"\"\n Calculate the distance between two atoms.\n\n Parameters\n ----------\n atom1: list\n A list of coordinates [x, y, z]\n atom2: list\n A list of coordinates [x, y, z]\n \n Returns\n -------\n bond_length: float\n The distance between atoms.\n Examples\n --------\n >>> calculate_distance([0,0,0], [0,0,1])\n 1.0\n \"\"\"\n x_distance = atom1[0]-atom2[0]\n y_distance = atom1[1]-atom2[1]\n z_distance = atom1[2]-atom2[2]\n distance = numpy.sqrt(x_distance**2+y_distance**2+z_distance**2)\n return distance\n\ndef bond_check(bond_distance,min=0,max=1.5):\n if bond_distance > min and bond_distance < max:\n is_a_bond = True\n else:\n is_a_bond = False\n return is_a_bond\nfor numA, atomA in enumerate(coords):\n for numB, atomB in enumerate(coords):\n distance_AB = calculate_distance(atomA, atomB)\n if bond_check(distance_AB,max=1.6):\n print(F'{symbols[numA]} to {symbols[numB]} : {distance_AB:.3f}')\n","sub_path":"geometry_analysis.py","file_name":"geometry_analysis.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"620936187","text":"import base64\nimport urllib.parse\nfrom typing import Dict, Any, TYPE_CHECKING\n\nfrom .abstract_handler import AbstractHandler\nfrom .. import Response, Request\n\n\nif TYPE_CHECKING: # pragma: no cover\n from awslambdaric.lambda_context import LambdaContext\n\n\nclass AwsApiGateway(AbstractHandler):\n \"\"\"\n Handles AWS API Gateway events, transforming them into ASGI Scope and handling\n responses\n\n See: https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html\n \"\"\"\n\n TYPE = \"AWS_API_GATEWAY\"\n\n def __init__(\n self,\n trigger_event: Dict[str, Any],\n trigger_context: \"LambdaContext\",\n api_gateway_base_path: str = \"/\",\n **kwargs: Dict[str, Any], # type: ignore\n ):\n super().__init__(trigger_event, trigger_context, **kwargs)\n self.api_gateway_base_path = api_gateway_base_path\n\n @property\n def request(self) -> Request:\n event = self.trigger_event\n\n # multiValue versions of headers take precedence over their plain versions\n # https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format\n if event.get(\"multiValueHeaders\"):\n headers = {\n k.lower(): \", \".join(v) if isinstance(v, list) else \"\"\n for k, v in event.get(\"multiValueHeaders\", {}).items()\n }\n elif event.get(\"headers\"):\n headers = {k.lower(): v for k, v in event.get(\"headers\", {}).items()}\n else:\n headers = {}\n\n request_context = event[\"requestContext\"]\n\n source_ip = request_context.get(\"identity\", {}).get(\"sourceIp\")\n\n path = event[\"path\"]\n http_method = event[\"httpMethod\"]\n\n if event.get(\"multiValueQueryStringParameters\"):\n query_string = urllib.parse.urlencode(\n event.get(\"multiValueQueryStringParameters\", {}), doseq=True\n ).encode()\n elif event.get(\"queryStringParameters\"):\n query_string = urllib.parse.urlencode(\n event.get(\"queryStringParameters\", {})\n ).encode()\n else:\n query_string = b\"\"\n\n server_name = headers.get(\"host\", \"mangum\")\n if \":\" not in server_name:\n server_port = headers.get(\"x-forwarded-port\", 80)\n else:\n server_name, server_port = server_name.split(\":\") # pragma: no cover\n server = (server_name, int(server_port))\n client = (source_ip, 0)\n\n if not path:\n path = \"/\"\n elif self.api_gateway_base_path and self.api_gateway_base_path != \"/\":\n if not self.api_gateway_base_path.startswith(\"/\"):\n self.api_gateway_base_path = f\"/{self.api_gateway_base_path}\"\n if path.startswith(self.api_gateway_base_path):\n path = path[len(self.api_gateway_base_path) :]\n\n return Request(\n method=http_method,\n headers=[[k.encode(), v.encode()] for k, v in headers.items()],\n path=urllib.parse.unquote(path),\n scheme=headers.get(\"x-forwarded-proto\", \"https\"),\n query_string=query_string,\n server=server,\n client=client,\n trigger_event=self.trigger_event,\n trigger_context=self.trigger_context,\n event_type=self.TYPE,\n )\n\n @property\n def body(self) -> bytes:\n body = self.trigger_event.get(\"body\", b\"\") or b\"\"\n\n if self.trigger_event.get(\"isBase64Encoded\", False):\n return base64.b64decode(body)\n if not isinstance(body, bytes):\n body = body.encode()\n\n return body\n\n def transform_response(self, response: Response) -> Dict[str, Any]:\n headers, multi_value_headers = self._handle_multi_value_headers(\n response.headers\n )\n\n body, is_base64_encoded = self._handle_base64_response_body(\n response.body, headers\n )\n\n return {\n \"statusCode\": response.status,\n \"headers\": headers,\n \"multiValueHeaders\": multi_value_headers,\n \"body\": body,\n \"isBase64Encoded\": is_base64_encoded,\n }\n","sub_path":"mangum/handlers/aws_api_gateway.py","file_name":"aws_api_gateway.py","file_ext":"py","file_size_in_byte":4212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"48876506","text":"\r\nimport sys\r\nimport math\r\nimport time\r\npjdir = \"..\\\\\"\r\nsys.path.append(pjdir + \"lib\\\\\")\r\nimport csv_file\r\nimport pt_lib_utility\r\nimport device_adapter\r\n\r\n#initial devices\r\nadapter = device_adapter.device_adapter();\r\nadapter.init();\r\nss = adapter.get_ss();\r\nsa = adapter.get_sa();\r\n\r\ncsv = csv_file.csv_file();\r\n\r\n#global variables\r\nrfu = 2;\r\nrx_port = 4;\r\nfreq_s = int(7.5e7);\r\nfreq_e = int(6e9 - 5e6);\r\nfreq_t = int(1e7);\r\n\r\n#start\r\nss.gen(rfu, \"ON\");\r\nss.set_tx_port(\"on\", \"off\", \"off\", \"off\", rfu);\r\nss.set_rx_port(rx_port, rfu);\r\n#sys.exit();\r\n\r\ncsv.create(\"tx_calibration_verifay\");\r\n\r\nprint(\"step1 ......\");\r\n\r\nsa.reset();\r\n\r\nsa.rbw(\"100Hz\");\r\nsa.span(\"1KHz\");\r\n\r\nsa.att(\"20\");\r\nsa.rlev(\"10dBm\");\r\nsa.pa(\"off\");\r\n\r\nfor freq in range(freq_s,freq_e,freq_t):\r\n ss.set_tx_freq(freq, rfu);\r\n sa.cen_freq(freq);\r\n csv.write(freq);\r\n csv.write(ss.read_temp(rfu));\r\n for index in range(0,13):\r\n ss.set_tx_gain(index, rfu);\r\n sa.init();\r\n rst = sa.peak();\r\n csv.write(rst[1]);\r\n csv.write(\"\\n\");\r\n\r\nprint(\"step2 ......\");\r\n\r\nsa.att(\"0\");\r\nsa.rlev(\"-20dBm\");\r\nsa.pa(\"off\");\r\n\r\nfor freq in range(freq_s,freq_e,freq_t):\r\n ss.set_tx_freq(freq, rfu);\r\n sa.cen_freq(freq);\r\n csv.write(freq);\r\n csv.write(ss.read_temp(rfu));\r\n for index in range(14,27):\r\n ss.set_tx_gain(index, rfu)\r\n sa.init();\r\n rst = sa.peak();\r\n csv.write(rst[1]);\r\n csv.write(\"\\n\");\r\n\r\nprint(\"step3 ......\");\r\n\r\nsa.rbw(\"10Hz\");\r\nsa.span(\"100Hz\");\r\nsa.att(\"0\");\r\nsa.rlev(\"-70dBm\");\r\nsa.pa(\"on\");\r\n\r\nfor freq in range(freq_s,freq_e,freq_t):\r\n ss.set_tx_freq(freq, rfu);\r\n sa.cen_freq(freq);\r\n csv.write(freq);\r\n csv.write(ss.read_temp(rfu));\r\n for index in range(28,40):\r\n ss.set_tx_gain(index, rfu)\r\n sa.init();\r\n rst = sa.peak();\r\n csv.write(rst[1]);\r\n csv.write(\"\\n\");\r\n\r\ncsv.close();\r\n","sub_path":"tools/gpib_test/calibration/t6290_tx_calibration_verify.py","file_name":"t6290_tx_calibration_verify.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"622377589","text":"\"\"\"\n作为客户端与HTTP Services交互\n\n对于简单的交互而言, 可以使用urllib.request模块足以;\n对于较为复杂的交互, 可以额外安装三方的requests库.\n\n如果必须要依赖内置的库, 可以使用low-level的http.client模块实现requests库的功能\n\n\"\"\"\n\nfrom urllib import request, parse\n\nurl = \"http://httpbin.org/get\"\n\nparms = {\n \"name1\": \"value1\",\n \"name2\": \"value2\"\n}\n\nquery_str = parse.urlencode(parms)\n\nu = request.urlopen(url + \"?\" + query_str)\nresp = u.read()\nprint(resp)","sub_path":"network_11/http_client_11_1.py","file_name":"http_client_11_1.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"494108247","text":"import json\nimport os\nfrom datetime import datetime\nfrom enum import Enum\n\nfrom Crypto.PublicKey import RSA\nfrom Crypto.PublicKey.RSA import RsaKey\nfrom django.core.management.base import BaseCommand, CommandParser\nfrom jwcrypto.jwk import JWK\n\n\nclass Command(BaseCommand):\n baseNameOption = 'basename'\n timestampFormat = '%Y%m%d%H%M%S'\n _keyFileBasePathName: str\n\n class KeyFileType(Enum):\n JWK = ('JWK', '_public-jwk.json')\n PRIVATE = ('private key', '_private.pem')\n PUBLIC = ('public key', '_public.pem')\n\n def __init__(self, description, fileSuffix):\n self.description = description\n self.fileSuffix = fileSuffix\n\n def add_arguments(self, parser: CommandParser):\n parser.add_argument(\n f'--{self.baseNameOption}',\n default=datetime.now().strftime(self.timestampFormat),\n type=str,\n required=False,\n help='Base file name of the key files generated. Default: '\n f'timestamp of \"{self.timestampFormat.replace(\"%\", \"%%\")}\"',\n dest=self.baseNameOption)\n\n def _writeKeyFile(self, keyFileType: KeyFileType, keyContent: str):\n keyFileName: str = f'{self.keyFileBasePathName}' \\\n f'{keyFileType.fileSuffix}'\n self.stdout.write(\n f'Writing {keyFileType.description} to file '\n f'\"{keyFileName}\"...')\n with open(keyFileName, 'w') as f:\n f.writelines((keyContent, '\\n'))\n self.stdout.write('File successfully written.')\n\n @property\n def keyFileBasePathName(self):\n return self._keyFileBasePathName\n\n @keyFileBasePathName.setter\n def keyFileBasePathName(self, value: str):\n self._keyFileBasePathName = value\n\n def handle(self, *args, **options: dict):\n configDir: str = os.path.dirname(\n os.getenv('ENV_FILE', '/secrets/env.json'))\n self.stdout.write('Key files will be written to '\n f'directory \"{configDir}\"...')\n\n self.keyFileBasePathName = os.path.join(\n configDir, options.get(self.baseNameOption))\n\n self.stdout.write('Generating key...')\n key: RsaKey = RSA.generate(4096)\n\n self.stdout.write('Preparing private and public key strings...')\n privateKey: bytes = key.exportKey()\n publicKey: bytes = key.publickey().exportKey()\n\n jwk_obj: JWK = JWK.from_pem(publicKey)\n public_jwk: dict = {\n **json.loads(jwk_obj.export_public()),\n **{'alg': 'RS256', 'use': 'sig'}\n }\n\n self._writeKeyFile(self.KeyFileType.PRIVATE,\n privateKey.decode('utf-8'))\n\n self._writeKeyFile(self.KeyFileType.PUBLIC,\n publicKey.decode('utf-8'))\n\n self._writeKeyFile(self.KeyFileType.JWK,\n json.dumps(public_jwk))\n","sub_path":"dashboard/management/commands/createkeys.py","file_name":"createkeys.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"512439779","text":"\"\"\"\r\nPlot a CMD for chosen cluster\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport csv\r\nimport math\r\nfrom scipy import stats\r\nimport numpy as np\r\n\r\n\r\n# dict pointing to list of gradient, intercept, x_min, x_max, y_min, y_max\r\ndict = {'true_mags_Berkeley18.csv': [8.0, 10.0, -0.5, 2.5, 10.0, 16.5],\r\n 'true_mags_NGC2099.csv': [5.0, 12.5, -2.0, 2.0, 9.0, 17.0],\r\n 'true_mags_NGC6940.csv': [6.0, 11.0, -0.5, 3.0, 9.0, 17.0],\r\n 'true_mags_NGC7092.csv': [5.5, 11.0, -0.5, 3.2, 9.0, 16.5]}\r\n\r\n\r\ndef clip_data(x, y, file):\r\n \"\"\"\r\n clip high standard deviation data (arbitrarily fit straight line to data\r\n for now, clip at some high std like 7)\r\n\r\n :param x: x axis data (list)\r\n :param y: y axis data (list)\r\n :return: clipped data x and y, fit data x and y\r\n \"\"\"\r\n # m, c, r_value, p_value, stderr = stats.linregress(x, y)\r\n\r\n residuals = []\r\n\r\n # get gradient and intercept from dictionary (fit by eye)\r\n m3 = dict[file][0]\r\n c3 = dict[file][1]\r\n\r\n # calculate residuals (y data minus fitted y data)\r\n for i, q in enumerate(x):\r\n res = abs( y[i] - (m3*q + c3) ) # changed from m and c above\r\n residuals.append(res)\r\n\r\n sigma = np.std(residuals)\r\n print(sigma)\r\n\r\n # collate new data within clipping boundaries\r\n x_new = []\r\n y_new = []\r\n\r\n for i, res in enumerate(residuals):\r\n if res < 6 * sigma:\r\n x_new.append(x[i])\r\n y_new.append(y[i])\r\n\r\n # get fit line too\r\n x_fit = []\r\n y_fit = []\r\n\r\n m2, c2, rv, pv, err = stats.linregress(x_new, y_new)\r\n\r\n print(m2, c2)\r\n\r\n for i in np.linspace(0.0, 2.5, 50):\r\n x_fit.append(i)\r\n y_fit.append(m2 * i + c2)\r\n\r\n return x_new, y_new, x_fit, y_fit\r\n\r\n\r\nfiles = ['true_mags_Berkeley18.csv',\r\n 'true_mags_NGC2099.csv',\r\n 'true_mags_NGC6940.csv',\r\n 'true_mags_NGC7092.csv']\r\n\r\nfor filename in files:\r\n filehandle = open(filename, 'r')\r\n filereader = csv.reader(filehandle)\r\n next(filereader)\r\n\r\n # plot V against V-I\r\n mag_data = []\r\n col_data = []\r\n for line in filereader:\r\n if math.isnan(float(line[1])) or math.isnan(float(line[3])):\r\n continue\r\n mag_data.append(float(line[1]))\r\n col_data.append(float(line[1])-float(line[3]))\r\n\r\n ####################################\r\n ###### Fit by eye per cluster ######\r\n ####################################\r\n\r\n x_ifit = []\r\n y_ifit = []\r\n\r\n m3 = dict[filename][0]\r\n c3 = dict[filename][1]\r\n\r\n print(m3, c3)\r\n\r\n for i in np.linspace(-0.5, 2.0, 80):\r\n x_ifit.append(i)\r\n y_ifit.append(m3*i + c3)\r\n\r\n x_min = dict[filename][2]\r\n x_max = dict[filename][3]\r\n y_min = dict[filename][4]\r\n y_max = dict[filename][5]\r\n\r\n ####################################\r\n\r\n magnitude, colour, mag_fit, col_fit = clip_data(col_data, mag_data, filename) # returns x_new, y_new\r\n fig = plt.figure()\r\n plt.plot(magnitude, colour, 'o') # cluster data\r\n plt.plot(mag_fit, col_fit, 'ro') # fit data\r\n plt.plot(x_ifit, y_ifit, 'go') # fit by eye for each cluster\r\n plt.axis([x_min, x_max, y_min, y_max])\r\n plt.gca().invert_yaxis()\r\n plt.xlabel('V-I')\r\n plt.ylabel('V')\r\n plt.title(filename.split(\"_\")[-1])\r\n\r\n plt.show()","sub_path":"cmdClipper.py","file_name":"cmdClipper.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"418712239","text":"#!/usr/bin/python3\n\nimport time\nimport serial\nimport json\nimport time\nimport mqtt\n\nmqtt.run(0)\n\nser = serial.Serial(\n port='/dev/ttyACM0',\n baudrate = 9600,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS,\n timeout=1\n )\n\nwhile 1:\n x = ser.readline().decode(\"utf8\")\n if(len(x) > 0):\n x = json.loads(x)\n #v = { 'Wirkleistung' : x.get(\"Wirkleistung\"),\n # 'Stromverbrauch' : x.get(\"Stromverbrauch\") }\n\n #mqtt.publish(\"home/strom\", json.dumps(v))\n\n print(json.dumps(x, indent=4))\n","sub_path":"readSerial.py","file_name":"readSerial.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"605507461","text":"# -*- coding: utf-8 -*-\nfrom mysql_generator import mysql_type as mt\nfrom jinja2 import Environment, FileSystemLoader\nfrom xml.etree import cElementTree\nimport os\nimport pymysql\nimport time\n_author_ = 'luwt'\n_date_ = '2019/3/5 15:17'\n\n\nclass Data:\n\n def __init__(self, name, column_name, java_type, jdbc_type, comment=None):\n # java字段名,驼峰\n self.name = name\n # 数据库字段名,下划线\n self.column_name = column_name\n self.java_type = java_type\n self.jdbc_type = jdbc_type\n self.comment = comment\n\n\ndef get_native_define_conn(host, port, user, pwd, db):\n \"\"\"打开本地数据库连接(ip/数据库用户名/登录密码/数据库名/编码)\"\"\"\n try:\n conn = pymysql.connect(\n host=host,\n port=port,\n user=user,\n passwd=pwd,\n db=db,\n charset='utf8'\n )\n print(\"获取数据库连接成功\")\n return conn\n except Exception as e:\n print(e)\n raise e\n\n\nclass MybatisGenerator:\n \"\"\"\n 默认生成lombok的@Data注释,可配置生成getter和setter方法,如果生成getter和setter则不会生成@Data,\n 可以配置生成多表字段联合的java类和resultMap,也可以指定某表的某些字段\n 参数:\n\n `table_schema`\n 数据库名称,需要传\n `table_name`\n 数据库表名,暂时只支持单表,将生成java、mapper、xml\n `column_name`\n 单表情况下可指定字段,默认为None,如果不为None,只会生成java和xml,\n 其中xml不会生成select和delete,另外所有的where语句也会缺省\n 传参形式为字符串,多个字段名用逗号分隔\n `java_tp`\n java类文件的模板,默认为当前目录下的java.txt文件,目录可选为当前目录下的子目录\n `mapper_tp`\n mapper.java接口文件的模板,默认为当前目录下的mapper.txt文件,目录可选为当前目录下的子目录\n `xml_tp`\n mapper.xml配置文件的模板,默认为当前目录下的xml.txt文件,目录可选为当前目录下的子目录\n `path`\n 输出路径,默认为'./'当前目录下,可修改\n `lombok`\n 在生成java类时是否生成lombok的@Data注释,默认true,若配置为false则生成getter和setter方法\n `exec_sql`\n 可执行的sql查询语句,用于多表联合查询情况,默认None,开启后将会生成相应的java类和xml,不会生成mapper.java,\n xml中只会生成resultMap\n \"\"\"\n def __init__(self, table_schema, table_name, column_name=None, java_tp='java.txt',\n mapper_tp='mapper.txt', xml_tp='xml.txt', path='./', lombok=True,\n exec_sql=None):\n # 库名\n self.table_schema = table_schema\n # 表名\n self.table_name = table_name\n # 可选:字段名,字符串形式,逗号分隔\n self.column_name = column_name\n # 查询结果为字段名,类型,约束(判断是否为主键PRI即可,应用在按主键查询更新删除等操作),自定义sql提供完整查询字段即可\n self.sql = 'select column_name, data_type, column_key, column_comment from information_schema.columns ' \\\n 'where table_schema = \"{}\" and table_name = \"{}\"'.format(self.table_schema, self.table_name)\\\n if exec_sql is None else 'show full fields from tmp_table'\n self.exec_sql = exec_sql\n self.data = self.get_data()\n self.primary = list(filter(lambda k: k[2] == 'PRI', self.data))\n self.java_tp = java_tp\n self.mapper_tp = mapper_tp\n self.xml_tp = xml_tp\n self.lombok = lombok\n self.appointed_columns = True if self.column_name else False\n self.mapper = True if not self.exec_sql and not self.appointed_columns else False\n # 获取模板文件\n self.env = Environment(loader=FileSystemLoader('./'), lstrip_blocks=True, trim_blocks=True)\n self.java_path = os.path.join(path, self.deal_class_name() + '.java')\n self.xml_path = os.path.join(path, self.deal_class_name() + 'Mapper.xml')\n # 如果是任意字段组合(主要用于多表字段联合情况),不需要生成Mapper.java\n self.mapper_path = os.path.join(path, self.deal_class_name() + 'Mapper.java') \\\n if self.mapper else None\n\n def get_data(self):\n \"\"\"连接数据库获取数据\"\"\"\n conn = get_native_define_conn(host, int(port), user, pwd, db)\n cursor = conn.cursor()\n if self.column_name and not self.exec_sql:\n columns = self.column_name.split(',')\n for i, c in enumerate(columns):\n if i == 0:\n self.sql += ' and column_name in (\"' + c + '\"'\n else:\n self.sql += ',\"' + c + '\"'\n self.sql += ')'\n if self.exec_sql:\n cursor.execute('use {};'.format(self.table_schema))\n cursor.execute('create temporary table tmp_table {};'.format(self.exec_sql))\n cursor.execute(self.sql)\n data = list(cursor.fetchall())\n if self.exec_sql:\n for line in data:\n ix = data.index(line)\n line = list(line)\n if line[1].find('(') > 0:\n type_ = line[1][0: line[1].find('(')]\n line[1] = type_\n data[ix] = line\n cursor.close()\n conn.close()\n return data\n\n def deal_class_name(self):\n class_name = ''\n for name in self.table_name.split('_'):\n class_name += name.capitalize()\n return class_name\n\n @staticmethod\n def deal_column_name(db_column_name):\n \"\"\"\n eg:\n user_name -> userName\n \"\"\"\n column_list = db_column_name.split('_')\n column_name_str = ''\n # 处理字段名称,采用驼峰式\n for column_name in column_list:\n if column_name != column_list[0]:\n column_name = column_name.capitalize()\n column_name_str += column_name\n return column_name_str\n\n @staticmethod\n def deal_type(data):\n \"\"\"返回jdbcType和java_type\"\"\"\n return eval('mt.MysqlType.{}.value[0]'.format(data)), eval('mt.MysqlType.{}.value[1]'.format(data))\n\n def generate_java(self):\n java_list = []\n for line in self.data:\n name = self.deal_column_name(line[0])\n types = self.deal_type(line[1])\n data = Data(name, line[0], types[1], types[0], line[-1])\n java_list.append(data)\n content = self.env.get_template(self.java_tp).render(\n cls_name=self.deal_class_name(), java_list=java_list, lombok=self.lombok)\n self.save(self.java_path, content)\n\n def generate_mapper(self):\n if self.mapper:\n cls_name = self.deal_class_name()\n # 多个主键的情况,mapper里的delete和select都应传入类,否则传主键\n param = ''\n key = ''\n have_update = True\n if len(self.primary) == len(self.data):\n have_update = False\n if len(self.primary) > 1:\n param = cls_name\n key = cls_name.lower()\n elif len(self.primary) == 1:\n param = self.deal_type(self.primary[0][1])[1]\n key = self.deal_column_name(self.primary[0][0])\n content = self.env.get_template(self.mapper_tp).render(\n cls_name=cls_name, param=param, key=key, haveUpdate=have_update)\n self.save(self.mapper_path, content)\n\n def generate_xml(self):\n # resultMap\n result_map = []\n # base_column_list\n columns = []\n params = []\n java_type = ''\n need_update = True\n # 生成base_column_list\n self.generate_base_col(columns)\n for line in self.data:\n column_name = line[0]\n name = self.deal_column_name(line[0])\n jdbc_type = self.deal_type(line[1])[0]\n java_type = self.deal_type(line[1])[0]\n data = Data(name, column_name, jdbc_type=jdbc_type, java_type=java_type)\n result_map.append(data)\n if len(self.primary) > 1:\n java_type = self.deal_class_name()\n elif len(self.primary) == 1:\n java_type = self.deal_type(self.primary[0][1])[1]\n if len(self.data) == len(self.primary):\n need_update = False\n for primary in self.primary:\n params.append(Data(self.deal_column_name(primary[0]), primary[0],\n self.deal_type(primary[1])[1], self.deal_type(primary[1])[0]))\n update_columns = result_map[:]\n for param in params:\n for result in update_columns:\n if param.column_name == result.column_name:\n update_columns.remove(result)\n continue\n content = self.env.get_template(self.xml_tp).render(\n result_map=result_map, columns=columns, table_name=self.table_name,\n params=params, java_type=java_type, need_update=need_update,\n update_columns=update_columns, mapper=self.mapper, any_column=self.exec_sql\n )\n self.save(self.xml_path, content)\n\n @staticmethod\n def save(path, content):\n with open(path, 'w+', encoding='utf-8')as f:\n f.write(content)\n print('生成的文件为' + path)\n\n def main(self):\n self.generate_java()\n self.generate_mapper()\n self.generate_xml()\n\n def generate_base_col(self, columns):\n col = 0\n i = 1\n for line in self.data:\n column_name = line[0]\n base_column = column_name + ', '\n if line == self.data[-1]:\n base_column = column_name\n else:\n # 对baseColumnList进行换行处理,控制每行字符数\n col += len(base_column)\n if col > i * 80:\n i += 1\n base_column = column_name + ', \\n\\t'\n columns.append(base_column)\n\n\nif __name__ == '__main__':\n try:\n tree = cElementTree.parse(os.path.join(os.path.abspath('.'), 'config.xml'))\n root = tree.getroot()\n host = root.find('database').find('host').text\n port = root.find('database').find('port').text\n user = root.find('database').find('user').text\n pwd = root.find('database').find('pwd').text\n db = root.find('database').find('db').text\n table_schema = root.find('generator').find('table_schema').text\n table_name = root.find('generator').find('table_name').text\n column = root.find('generator').find('column').text\n path = root.find('generator').find('path').text\n lombok = root.find('generator').find('lombok').text\n exec_sql = root.find('generator').find('exec_sql').text\n\n generator = MybatisGenerator(table_schema, table_name, column, path=path, lombok=lombok, exec_sql=exec_sql)\n generator.main()\n print(\"执行成功!五秒后退出\")\n time.sleep(5)\n except Exception as e:\n print(\"执行出错:=>\\n\\n{}\\n\\n按任意键退出\".format(e))\n input()\n","sub_path":"mybatis_generator.py","file_name":"mybatis_generator.py","file_ext":"py","file_size_in_byte":11426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"653114585","text":"from tfoosball.common_settings import * # NOQA\nimport os\nimport dj_database_url\n\n\nSECRET_KEY = os.environ['DJANGO_SECRET_KEY']\n\nDEBUG = os.environ.get('DJANGO_DEBUG', False)\nDEBUG = True if DEBUG == 'True' else DEBUG\n\nALLOWED_HOSTS = [\n 'tfoosball-api.herokuapp.com',\n 'tfoosball.herokuapp.com',\n]\n\nCSRF_TRUSTED_ORIGINS = ALLOWED_HOSTS\n\nDATABASES = {\n 'default': dj_database_url.config(conn_max_age=500)\n}\n\n# CORS\n# ------------------------------------------------------------------------------\n\nCORS_ORIGIN_WHITELIST = (\n 'tfoosball-api.herokuapp.com',\n 'tfoosball.herokuapp.com',\n)\n\nCSRF_COOKIE_SECURE = True\nSESSION_COOKIE_SECURE = True\nSTATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'\n\n# EMAIL SERVER CONFIG\n# ------------------------------------------------------------------------------\nEMAIL_HOST = 'smtp.sendgrid.net'\nEMAIL_HOST_USER = os.environ['SENDGRID_USERNAME']\nEMAIL_HOST_PASSWORD = os.environ['SENDGRID_PASSWORD']\nEMAIL_PORT = 587\nEMAIL_USE_TLS = True\n","sub_path":"tfoosball/production_settings.py","file_name":"production_settings.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"44684107","text":"from keras.layers import Conv2D, ZeroPadding2D, Activation, Input, concatenate\nfrom keras.layers.core import Lambda, Flatten, Dense\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.pooling import MaxPooling2D, AveragePooling2D\nfrom keras.models import Model\nfrom keras import backend as K\nimport pandas as pd\nimport numpy as np\nimport keras\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.preprocessing import *\nfrom keras.callbacks import *\nfrom keras.optimizers import *\nfrom tqdm import tqdm\nimport glob\nfrom keras.applications.resnet50 import preprocess_input, decode_predictions\n\n# from keras.applications.nasnet import preprocess_input, decode_predictions\n# from keras.applications.densenet import preprocess_input, decode_predictions\nfrom keras.preprocessing import image\n\nfrom sklearn.model_selection import train_test_split\n\nimport matplotlib.pyplot as plt\nimport utils\nfrom utils import LRN2D\n\nimport cv2\nfrom random import choice, sample\nimport datetime\nfrom sklearn.metrics import roc_auc_score\nfrom keras.callbacks import ReduceLROnPlateau, ModelCheckpoint, EarlyStopping\nimport threading\n\ndef auc(y_true, y_pred):\n return tf.py_func(roc_auc_score, (y_true, y_pred), tf.double)\n\n\nprint(\"start training.....................................\")\nprint(\"start training.....................................\")\n\nif os.path.exists(\"logs\"):\n pass\nelse:\n os.mkdir(\"logs\")\nlog_dir = \"/home/datumx/data_science_experiments/detect_kinship/logs/\"+\"kin_relation\" + \"_\" + str(datetime.datetime.now()).replace(\" \",\"-\").replace(\":\",\"-\").replace(\".\",\"\").replace(\"-\",\"_\")\nos.mkdir(log_dir)\n\nROOT = \"/home/datumx/data_science_experiments/detect_kinship/\"\n\n\ndef read_img(im_path):\n im1 = image.load_img(im_path, target_size=(96, 96))\n im1 = image.img_to_array(im1)\n im1 = np.expand_dims(im1, axis=0)\n im1 = preprocess_input(im1,mode='tf')\n return im1[0]\n\nfrom collections import defaultdict\n#keeps all photos path in a dictionary\nallPhotos = defaultdict(list)\nfor family in glob.glob(ROOT+\"train/*\"):\n for mem in glob.glob(family+'/*'):\n for photo in glob.glob(mem+'/*'):\n allPhotos[mem].append(photo)\n\n#list of all members with valid photo\nppl = list(allPhotos.keys())\nlen(ppl)\n\ndata = pd.read_csv(ROOT+'train_relationships.csv')\ndata.p1 = data.p1.apply( lambda x: ROOT+'train/'+x )\ndata.p2 = data.p2.apply( lambda x: ROOT+'train/'+x )\nprint(data.shape)\ndata.head()\n\ndata = data[ ( (data.p1.isin(ppl)) & (data.p2.isin(ppl)) ) ]\ndata = [ ( x[0], x[1] ) for x in data.values ]\nlen(data)\n\ntrain = [ x for x in data if 'F09' not in x[0] ]\nval = [ x for x in data if 'F09' in x[0] ]\nlen(train), len(val)\n\ndef getImages(p1,p2):\n p1 = read_img(choice(allPhotos[p1]))\n p2 = read_img(choice(allPhotos[p2]))\n return p1,p2\n\ndef getMiniBatch(batch_size=16, data=train):\n p1 = []; p2 = []; Y = []\n batch = sample(data, batch_size//2)\n for x in batch:\n _p1, _p2 = getImages(*x)\n p1.append(_p1);p2.append(_p2);Y.append(1)\n while len(Y) < batch_size:\n _p1,_p2 = tuple(np.random.choice(ppl,size=2, replace=False))\n if (_p1,_p2) not in train+val and (_p2,_p1) not in train+val:\n _p1,_p2 = getImages(_p1,_p2)\n p1.append(_p1);p2.append(_p2);Y.append(0) \n return [np.array(p1),np.array(p2)], np.array(Y)\n\ndef create_model():\n myInput = Input(shape=(96, 96, 3))\n\n x = ZeroPadding2D(padding=(3, 3), input_shape=(96, 96, 3))(myInput)\n x = Conv2D(64, (7, 7), strides=(2, 2), name='conv1')(x)\n x = BatchNormalization(axis=3, epsilon=0.00001, name='bn1')(x)\n x = Activation('relu')(x)\n x = ZeroPadding2D(padding=(1, 1))(x)\n x = MaxPooling2D(pool_size=3, strides=2)(x)\n x = Lambda(LRN2D, name='lrn_1')(x)\n x = Conv2D(64, (1, 1), name='conv2')(x)\n x = BatchNormalization(axis=3, epsilon=0.00001, name='bn2')(x)\n x = Activation('relu')(x)\n x = ZeroPadding2D(padding=(1, 1))(x)\n x = Conv2D(192, (3, 3), name='conv3')(x)\n x = BatchNormalization(axis=3, epsilon=0.00001, name='bn3')(x)\n x = Activation('relu')(x)\n x = Lambda(LRN2D, name='lrn_2')(x)\n x = ZeroPadding2D(padding=(1, 1))(x)\n x = MaxPooling2D(pool_size=3, strides=2)(x)\n\n # Inception3a\n inception_3a_3x3 = Conv2D(96, (1, 1), name='inception_3a_3x3_conv1')(x)\n inception_3a_3x3 = BatchNormalization(axis=3, epsilon=0.00001, name='inception_3a_3x3_bn1')(inception_3a_3x3)\n inception_3a_3x3 = Activation('relu')(inception_3a_3x3)\n inception_3a_3x3 = ZeroPadding2D(padding=(1, 1))(inception_3a_3x3)\n inception_3a_3x3 = Conv2D(128, (3, 3), name='inception_3a_3x3_conv2')(inception_3a_3x3)\n inception_3a_3x3 = BatchNormalization(axis=3, epsilon=0.00001, name='inception_3a_3x3_bn2')(inception_3a_3x3)\n inception_3a_3x3 = Activation('relu')(inception_3a_3x3)\n\n inception_3a_5x5 = Conv2D(16, (1, 1), name='inception_3a_5x5_conv1')(x)\n inception_3a_5x5 = BatchNormalization(axis=3, epsilon=0.00001, name='inception_3a_5x5_bn1')(inception_3a_5x5)\n inception_3a_5x5 = Activation('relu')(inception_3a_5x5)\n inception_3a_5x5 = ZeroPadding2D(padding=(2, 2))(inception_3a_5x5)\n inception_3a_5x5 = Conv2D(32, (5, 5), name='inception_3a_5x5_conv2')(inception_3a_5x5)\n inception_3a_5x5 = BatchNormalization(axis=3, epsilon=0.00001, name='inception_3a_5x5_bn2')(inception_3a_5x5)\n inception_3a_5x5 = Activation('relu')(inception_3a_5x5)\n\n inception_3a_pool = MaxPooling2D(pool_size=3, strides=2)(x)\n inception_3a_pool = Conv2D(32, (1, 1), name='inception_3a_pool_conv')(inception_3a_pool)\n inception_3a_pool = BatchNormalization(axis=3, epsilon=0.00001, name='inception_3a_pool_bn')(inception_3a_pool)\n inception_3a_pool = Activation('relu')(inception_3a_pool)\n inception_3a_pool = ZeroPadding2D(padding=((3, 4), (3, 4)))(inception_3a_pool)\n\n inception_3a_1x1 = Conv2D(64, (1, 1), name='inception_3a_1x1_conv')(x)\n inception_3a_1x1 = BatchNormalization(axis=3, epsilon=0.00001, name='inception_3a_1x1_bn')(inception_3a_1x1)\n inception_3a_1x1 = Activation('relu')(inception_3a_1x1)\n\n inception_3a = concatenate([inception_3a_3x3, inception_3a_5x5, inception_3a_pool, inception_3a_1x1], axis=3)\n\n # Inception3b\n inception_3b_3x3 = Conv2D(96, (1, 1), name='inception_3b_3x3_conv1')(inception_3a)\n inception_3b_3x3 = BatchNormalization(axis=3, epsilon=0.00001, name='inception_3b_3x3_bn1')(inception_3b_3x3)\n inception_3b_3x3 = Activation('relu')(inception_3b_3x3)\n inception_3b_3x3 = ZeroPadding2D(padding=(1, 1))(inception_3b_3x3)\n inception_3b_3x3 = Conv2D(128, (3, 3), name='inception_3b_3x3_conv2')(inception_3b_3x3)\n inception_3b_3x3 = BatchNormalization(axis=3, epsilon=0.00001, name='inception_3b_3x3_bn2')(inception_3b_3x3)\n inception_3b_3x3 = Activation('relu')(inception_3b_3x3)\n\n inception_3b_5x5 = Conv2D(32, (1, 1), name='inception_3b_5x5_conv1')(inception_3a)\n inception_3b_5x5 = BatchNormalization(axis=3, epsilon=0.00001, name='inception_3b_5x5_bn1')(inception_3b_5x5)\n inception_3b_5x5 = Activation('relu')(inception_3b_5x5)\n inception_3b_5x5 = ZeroPadding2D(padding=(2, 2))(inception_3b_5x5)\n inception_3b_5x5 = Conv2D(64, (5, 5), name='inception_3b_5x5_conv2')(inception_3b_5x5)\n inception_3b_5x5 = BatchNormalization(axis=3, epsilon=0.00001, name='inception_3b_5x5_bn2')(inception_3b_5x5)\n inception_3b_5x5 = Activation('relu')(inception_3b_5x5)\n\n inception_3b_pool = AveragePooling2D(pool_size=(3, 3), strides=(3, 3))(inception_3a)\n inception_3b_pool = Conv2D(64, (1, 1), name='inception_3b_pool_conv')(inception_3b_pool)\n inception_3b_pool = BatchNormalization(axis=3, epsilon=0.00001, name='inception_3b_pool_bn')(inception_3b_pool)\n inception_3b_pool = Activation('relu')(inception_3b_pool)\n inception_3b_pool = ZeroPadding2D(padding=(4, 4))(inception_3b_pool)\n\n inception_3b_1x1 = Conv2D(64, (1, 1), name='inception_3b_1x1_conv')(inception_3a)\n inception_3b_1x1 = BatchNormalization(axis=3, epsilon=0.00001, name='inception_3b_1x1_bn')(inception_3b_1x1)\n inception_3b_1x1 = Activation('relu')(inception_3b_1x1)\n\n inception_3b = concatenate([inception_3b_3x3, inception_3b_5x5, inception_3b_pool, inception_3b_1x1], axis=3)\n\n # Inception3c\n inception_3c_3x3 = utils.conv2d_bn(inception_3b,\n layer='inception_3c_3x3',\n cv1_out=128,\n cv1_filter=(1, 1),\n cv2_out=256,\n cv2_filter=(3, 3),\n cv2_strides=(2, 2),\n padding=(1, 1))\n\n inception_3c_5x5 = utils.conv2d_bn(inception_3b,\n layer='inception_3c_5x5',\n cv1_out=32,\n cv1_filter=(1, 1),\n cv2_out=64,\n cv2_filter=(5, 5),\n cv2_strides=(2, 2),\n padding=(2, 2))\n\n inception_3c_pool = MaxPooling2D(pool_size=3, strides=2)(inception_3b)\n inception_3c_pool = ZeroPadding2D(padding=((0, 1), (0, 1)))(inception_3c_pool)\n\n inception_3c = concatenate([inception_3c_3x3, inception_3c_5x5, inception_3c_pool], axis=3)\n\n #inception 4a\n inception_4a_3x3 = utils.conv2d_bn(inception_3c,\n layer='inception_4a_3x3',\n cv1_out=96,\n cv1_filter=(1, 1),\n cv2_out=192,\n cv2_filter=(3, 3),\n cv2_strides=(1, 1),\n padding=(1, 1))\n inception_4a_5x5 = utils.conv2d_bn(inception_3c,\n layer='inception_4a_5x5',\n cv1_out=32,\n cv1_filter=(1, 1),\n cv2_out=64,\n cv2_filter=(5, 5),\n cv2_strides=(1, 1),\n padding=(2, 2))\n\n inception_4a_pool = AveragePooling2D(pool_size=(3, 3), strides=(3, 3))(inception_3c)\n inception_4a_pool = utils.conv2d_bn(inception_4a_pool,\n layer='inception_4a_pool',\n cv1_out=128,\n cv1_filter=(1, 1),\n padding=(2, 2))\n inception_4a_1x1 = utils.conv2d_bn(inception_3c,\n layer='inception_4a_1x1',\n cv1_out=256,\n cv1_filter=(1, 1))\n inception_4a = concatenate([inception_4a_3x3, inception_4a_5x5, inception_4a_pool, inception_4a_1x1], axis=3)\n\n #inception4e\n inception_4e_3x3 = utils.conv2d_bn(inception_4a,\n layer='inception_4e_3x3',\n cv1_out=160,\n cv1_filter=(1, 1),\n cv2_out=256,\n cv2_filter=(3, 3),\n cv2_strides=(2, 2),\n padding=(1, 1))\n inception_4e_5x5 = utils.conv2d_bn(inception_4a,\n layer='inception_4e_5x5',\n cv1_out=64,\n cv1_filter=(1, 1),\n cv2_out=128,\n cv2_filter=(5, 5),\n cv2_strides=(2, 2),\n padding=(2, 2))\n inception_4e_pool = MaxPooling2D(pool_size=3, strides=2)(inception_4a)\n inception_4e_pool = ZeroPadding2D(padding=((0, 1), (0, 1)))(inception_4e_pool)\n\n inception_4e = concatenate([inception_4e_3x3, inception_4e_5x5, inception_4e_pool], axis=3)\n\n #inception5a\n inception_5a_3x3 = utils.conv2d_bn(inception_4e,\n layer='inception_5a_3x3',\n cv1_out=96,\n cv1_filter=(1, 1),\n cv2_out=384,\n cv2_filter=(3, 3),\n cv2_strides=(1, 1),\n padding=(1, 1))\n\n inception_5a_pool = AveragePooling2D(pool_size=(3, 3), strides=(3, 3))(inception_4e)\n inception_5a_pool = utils.conv2d_bn(inception_5a_pool,\n layer='inception_5a_pool',\n cv1_out=96,\n cv1_filter=(1, 1),\n padding=(1, 1))\n inception_5a_1x1 = utils.conv2d_bn(inception_4e,\n layer='inception_5a_1x1',\n cv1_out=256,\n cv1_filter=(1, 1))\n\n inception_5a = concatenate([inception_5a_3x3, inception_5a_pool, inception_5a_1x1], axis=3)\n\n #inception_5b\n inception_5b_3x3 = utils.conv2d_bn(inception_5a,\n layer='inception_5b_3x3',\n cv1_out=96,\n cv1_filter=(1, 1),\n cv2_out=384,\n cv2_filter=(3, 3),\n cv2_strides=(1, 1),\n padding=(1, 1))\n inception_5b_pool = MaxPooling2D(pool_size=3, strides=2)(inception_5a)\n inception_5b_pool = utils.conv2d_bn(inception_5b_pool,\n layer='inception_5b_pool',\n cv1_out=96,\n cv1_filter=(1, 1))\n inception_5b_pool = ZeroPadding2D(padding=(1, 1))(inception_5b_pool)\n\n inception_5b_1x1 = utils.conv2d_bn(inception_5a,\n layer='inception_5b_1x1',\n cv1_out=256,\n cv1_filter=(1, 1))\n inception_5b = concatenate([inception_5b_3x3, inception_5b_pool, inception_5b_1x1], axis=3)\n\n av_pool = AveragePooling2D(pool_size=(3, 3), strides=(1, 1))(inception_5b)\n reshape_layer = Flatten()(av_pool)\n dense_layer = Dense(128, name='dense_layer')(reshape_layer)\n norm_layer = Lambda(lambda x: K.l2_normalize(x, axis=1), name='norm_layer')(dense_layer)\n\n return Model(inputs=[myInput], outputs=norm_layer)\n\n\n\nmod = create_model()\nmod.load_weights('weights/nn4.small2.v1.h5')\n\n\n \ndef euclidean_distance(vects):\n x, y = vects\n sum_square = K.sum(K.square(x - y), axis=1, keepdims=True)\n return K.sqrt(K.maximum(sum_square, K.epsilon()))\n\n\ndef eucl_dist_output_shape(shapes):\n shape1, shape2 = shapes\n return (shape1[0], 1)\n\n\ndef contrastive_loss(y_true, y_pred):\n '''Contrastive loss from Hadsell-et-al.'06\n http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf\n '''\n margin = 1\n sqaure_pred = K.square(y_pred)\n margin_square = K.square(K.maximum(margin - y_pred, 0))\n return K.mean(y_true * sqaure_pred + (1 - y_true) * margin_square)\n\ndef create_base_network(input_shape):\n new_mod = Model(mod.input,mod.layers[-5].output)\n return new_mod\n\ndef compute_accuracy(y_true, y_pred):\n '''Compute classification accuracy with a fixed threshold on distances.\n '''\n pred = y_pred.ravel() < 0.5\n return np.mean(pred == y_true)\n\n\ndef accuracy(y_true, y_pred):\n '''Compute classification accuracy with a fixed threshold on distances.\n '''\n return K.mean(K.equal(y_true, K.cast(y_pred < 0.5, y_true.dtype)))\n\n\ncheckpoint_path = log_dir+ \"/siamese_\"+\"kins_detection\"+\"_{epoch:02d}-val_loss_{val_loss:.4f}-val_acc_{val_acc:.4f}.h5\"\n\ncallbacks = [keras.callbacks.EarlyStopping(monitor='val_loss',\n patience=8,\n verbose=1,\n min_delta=1e-4),\n keras.callbacks.ReduceLROnPlateau(monitor='val_loss',\n factor=0.1,\n patience=4,\n verbose=1,\n epsilon=1e-4),\n keras.callbacks.TensorBoard(log_dir=log_dir,\n histogram_freq=0, write_graph=True, write_images=False),\n keras.callbacks.ModelCheckpoint(checkpoint_path,\n verbose=0, save_weights_only=True),\n ]\n\n\n\ninput_shape = (96,96,3)\n\ninput_a = Input(shape=input_shape)\ninput_b = Input(shape=input_shape)\n\nbase_network = create_base_network(input_shape)\n\n# because we re-use the same instance `base_network`,\n# the weights of the network\n# will be shared across the two branches\nprocessed_a = base_network(input_a)\nprocessed_b = base_network(input_b)\n\nx1 = Concatenate(axis=-1)([GlobalMaxPool2D()(processed_a), GlobalAvgPool2D()(processed_a)])\nx2 = Concatenate(axis=-1)([GlobalMaxPool2D()(processed_b), GlobalAvgPool2D()(processed_b)])\n\nx3 = Subtract()([x1, x2])\nx3 = Multiply()([x3, x3])\n\nx = Multiply()([x1, x2])\n\nx = Concatenate(axis=-1)([x, x3])\n\n\nx = Dense(100, activation=\"relu\")(x)\nx = Dropout(0.01)(x)\nout = Dense(1, activation=\"sigmoid\")(x)\n\nmodel = Model([input_a, input_b], out)\n\nmodel.compile(loss=\"binary_crossentropy\", metrics=['acc',auc], optimizer=Adam(0.001))\n\n\n# model.load_weights(\"/home/datumx/data_science_experiments/detect_kinship/logs/kin_relation_2019_05_28_21_53_51966472/siamese_kins_detection_13-val_loss_0.4720-val_acc_0.7680.h5\")\n# train\n\n\nprint(model.summary())\n# train_batches =batch_generator(data_train,batch_size=8)\n# valid_batches =batch_generator(data_valid,batch_size=8)\n\ndef Generator(batch_size, data ):\n while True:\n yield getMiniBatch(batch_size=batch_size, data=data)\n\ntrain_gen = Generator(batch_size=16,data=train)\nval_gen = Generator(batch_size=16,data=val)\n\nmodel.fit_generator(train_gen,steps_per_epoch=200,use_multiprocessing=True,\n epochs=100,validation_data=val_gen,validation_steps=100,callbacks=callbacks)\n\n\n","sub_path":"train_version_files/train_4.py","file_name":"train_4.py","file_ext":"py","file_size_in_byte":18496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"610798594","text":"'''jupyterで\b実行している'''\n\n#%%\nfrom pyspark.ml.feature import OneHotEncoderEstimator\nfrom pyspark.ml.feature import StringIndexer\n\ndf = spark.createDataFrame([\n(0, \"a\"),\n(1, \"b\"),\n(2, \"c\"),\n(3, \"a\"),\n(4, \"a\"),\n(5, \"c\")\n], [\"id\", \"category\"])\n\nstringIndexer = StringIndexer(inputCol=\"category\", outputCol=\"categoryIndex\")\nmodel = stringIndexer.fit(df)\nindexed = model.transform(df)\n\n# デフォルトではdropLast=Falseであり多重線形性回避のため次元数が\bとり得る値-1になる\nencoder = OneHotEncoderEstimator(inputCols=[\"categoryIndex\"], outputCols=[\"categoryVec\"], dropLast=False)\nmodel = encoder.fit(indexed)\nencoded = model.transform(indexed)\nencoded.show()\n\n# 出力の意味\n# 0 => (0,0,1), 1 => (0,1,0), 2 => (0,0,1)\n# (3, [0], [1.0])は、長さ3のベクトルでインデックス0に値1という意味\n# スパース表現になっている","sub_path":"category_feature.py","file_name":"category_feature.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"142215006","text":"import torch\nimport torchsummaryX\nimport numpy as np\nfrom model.base_rnn import BaseRNN\n\n\nclass CondGRU(BaseRNN):\n def __init__(self, num_class, hid_size, hid_layers, drop_out_rate,\n embedding_size, cond_range, emb_cond_size,\n learning_rate, data_keys, writer_comment=\"cond_rnn\"):\n super(CondGRU, self).__init__(data_keys=data_keys, writer_comment=writer_comment)\n\n emb_cond_size1, emb_cond_size2, emb_cond_size3 = emb_cond_size\n cond_range1, cond_range2, cond_range3 = cond_range\n self.cond_emb1 = torch.nn.Embedding(cond_range1, emb_cond_size1)\n self.cond_emb2 = torch.nn.Embedding(cond_range2, emb_cond_size2)\n self.cond_emb3 = torch.nn.Embedding(cond_range3, emb_cond_size3)\n\n self.embedding = torch.nn.Embedding(num_class, embedding_size)\n self.gru = torch.nn.GRU(\n input_size=embedding_size + emb_cond_size1 + emb_cond_size2 + emb_cond_size3,\n hidden_size=hid_size,\n num_layers=hid_layers, dropout=drop_out_rate,\n bidirectional=False, bias=True,\n )\n self.dense = torch.nn.Linear(hid_size*1, num_class)\n self.log_softmax = torch.nn.LogSoftmax(dim=2)\n\n self.num_class = num_class\n\n self.optimizer = torch.optim.Adam(self.parameters(), lr=learning_rate)\n self.scheduler = torch.optim.lr_scheduler.ExponentialLR(self.optimizer, 0.99)\n self.criterion = torch.nn.NLLLoss(reduction=\"mean\")\n return\n\n def forward(self, input_data, condition, h0=None):\n seq_len = input_data.shape[0]\n\n cond1 = self.cond_emb1(condition[[0]])\n cond2 = self.cond_emb2(condition[[1]])\n cond3 = self.cond_emb3(condition[[2]])\n cond = torch.cat([cond1, cond2, cond3], dim=2)\n cond = cond.repeat(seq_len, 1, 1)\n embeded_data = self.embedding(input_data)\n concat_data = torch.cat([cond, embeded_data], dim=2)\n output, hn = self.gru(concat_data, h0)\n output = self.dense(output)\n output = self.log_softmax(output)\n return output, hn\n\n def forward_packed_data(self, batch_data, h0=None, teaching_ratio=0.):\n if teaching_ratio == 0.:\n input_data = batch_data[\"data\"]\n cond = batch_data[\"cond\"]\n pred_logits, hn = self.forward(input_data, cond, h0)\n return pred_logits, hn\n else:\n raise Exception(\"not implemented\")\n\n\n\n\n\n\n\n","sub_path":"model/cond_rnn_new.py","file_name":"cond_rnn_new.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"290707460","text":"# coding: utf8\n\nimport unittest\nimport logging\nfrom db.DataStore import sqlHelper\nfrom db.SqlHelper import AlchemyEncoder,ProxyHistory\nimport json\nimport pandas as pd\nimport itertools\n\nclass TestSqlHelper(unittest.TestCase):\n def test_update_proxy(self):\n sqlHelper.update({'ip':'42.81.58.199','port':80},{'score':1})\n\n def test_get_summary(self):\n proxys = sqlHelper.select(None, None)\n json_result = json.dumps(proxys,cls=AlchemyEncoder)\n \n df = pd.read_json(json_result)\n score_map = {0:u'普通',1:u'高速'}\n df['score'] = df['score'].map(score_map)\n df_score = df.groupby(by='score')['ip'].count()\n proxy_stats_by_socre = df_score.to_json()\n print(proxy_stats_by_socre)\n \n def test_get_hist_trends(self):\n ret = sqlHelper.get_stats_7days_history()\n df = pd.DataFrame(ret,columns=('updatetime','score','cnt'))\n df['score'] = df['score'].map({0:u'普通',1:u'高速'})\n df['updt'] = df['updatetime'].map(lambda x: x.strftime('%Y-%m-%d %H:%M:%S'))\n json_dict = []\n \n for cat,cat_data in df.groupby('score'):\n grp_dict = {}\n grp_dict['name'] = cat\n grp_dict['data'] = cat_data[['updt','cnt']].values.tolist()\n json_dict.append(grp_dict)\n \n print(json.dumps(json_dict))\n\n def test_delete_history(self):\n ret = sqlHelper.delete_history()\n print(ret)\n\nif __name__ == '__main__':\n unittest.main()\n ","sub_path":"test/testSqlHelper.py","file_name":"testSqlHelper.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"259854325","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 9 12:50:31 2017\n\n@author: K.Hwang\n\"\"\"\n\n\nfrom os import listdir\nfrom os.path import isfile, join\n\nmypath = r\".\\CLASS1\"\nonlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]\n\ns = {}\nfor f in onlyfiles:\n idf = f.split('_')\n fname = mypath + \"\\\\\" + f\n fin = open(fname)\n #fout = open(mypath + \"\\\\tab_\" + f, 'w')\n fout = open(fname, 'w')\n x = fin.readlines()\n for l in x:\n fout.write(l.replace(\" \", chr(9) ))\n","sub_path":"data/data_manipulation.py","file_name":"data_manipulation.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"243054712","text":"import random\nimport numpy as np\nfrom collections import deque\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\n\n\nclass DQNAgent:\n def __init__(self, input_size, output_size):\n self._input_size = input_size\n self._output_size = output_size\n self.memory = deque(maxlen=2000)\n self._parameters = {'gamma': 0.95, 'epsilon': 1.0, 'epsilon_min': 0.01,\n 'epsilon_decay': 0.995, 'learning_rate': 0.001}\n self._model = self._build_model()\n\n def _build_model(self):\n model = Sequential()\n model.add(Dense(24, input_dim=self._input_size, activation='relu'))\n model.add(Dense(24, activation='relu'))\n model.add(Dense(self._output_size, activation='linear'))\n model.compile(loss='mse', optimizer=Adam(lr=self._parameters['learning_rate']))\n return model\n\n def act(self, state):\n if np.random.rand() <= self._parameters['epsilon']:\n return random.randrange(self._output_size)\n action_value = self._model.predict(state)\n return np.argmax(action_value[0])\n\n def remember(self, state, action, reward, next_state, done):\n self.memory.append((state, action, reward, next_state, done))\n\n def replay(self, batch_size):\n minibatch = random.sample(self.memory, batch_size)\n for state, action, reward, next_state, done in minibatch:\n target = reward\n if not done:\n target = (reward + self._parameters['gamma'] *\n np.amax(self._model.predict(next_state)[0]))\n target_f = self._model.predict(state)\n target_f[0][action] = target\n self._model.fit(state, target_f, epochs=1, verbose=0)\n if self._parameters['epsilon'] > self._parameters['epsilon_min']:\n self._parameters['epsilon'] *= self._parameters['epsilon_decay']\n","sub_path":"microbial_ai/regulation/dqn/keras_dqn.py","file_name":"keras_dqn.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"466007428","text":"\nimport os\nimport re\nfrom pprint import pprint\nimport numpy as np\nfrom scipy import signal\nimport plotly.figure_factory as ff\nimport plotly.offline as py\nimport plotly.express as px\nimport plotly.tools as plotly_tools\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport time\nimport random\nimport colorsys\n\n\n \ndef TextReader(filepath):\n with open(filepath, 'r') as f:\n lines = f.readlines()\n lines = lines[:-1]\n dictCPU={}\n dictMEM={}\n dictTEMP={}\n for line in lines:\n # 时间 2019-07-31 04:24:08\n raw_time = line.split('][')[2].split(',')[0]\n\n # 资源类型 CPU% Mem% Core_temp\n resource_type = line.split('][')[3].split('] ')[0]\n\n # 节点 /decision_planning_node\n if line.split('][')[3].split('] ')[1].split(' ')[0][:5] == \"/rviz\":\n topic_node = line.split('][')[3].split('] ')[1].split(' ')[0] = \"/rviz\"\n elif line.split('][')[3].split('] ')[1].split(' ')[0][:9] == \"/rostopic\":\n topic_node = line.split('][')[3].split('] ')[1].split(' ')[0] = \"/rostopic\"\n elif line.split('][')[3].split('] ')[1].split(' ')[0][:5] == \"/play\":\n topic_node = line.split('][')[3].split('] ')[1].split(' ')[0] = \"/play\"\n elif line.split('][')[3].split('] ')[1].split(' ')[0][:16] == \"/rqt_gui_py_node\":\n topic_node = line.split('][')[3].split('] ')[1].split(' ')[0] = \"/rqt_gui_py_node\"\n elif line.split('][')[3].split('] ')[1].split(' ')[0][:7] == \"/record\":\n topic_node = line.split('][')[3].split('] ')[1].split(' ')[0] = \"/record\"\n else:\n topic_node = line.split('][')[3].split('] ')[1].split(' ')[0]\n # 占用率 0.87%\n occupancy = line.split('][')[3].split('] ')[1].split(' ')[1].strip('%\\n')\n\n if resource_type and resource_type == \"CPU%\":\n if dictCPU.get(topic_node):\n dictCPU[topic_node][raw_time] = float(occupancy)\n else:\n dictCPU[topic_node] = {raw_time:float(occupancy)}\n\n elif resource_type and resource_type == \"Mem%\":\n if dictMEM.get(topic_node):\n dictMEM[topic_node][raw_time] = occupancy\n else:\n dictMEM[topic_node] = {raw_time:occupancy}\n\n elif resource_type and resource_type == \"Core_temp\":\n if dictTEMP.get(topic_node):\n dictTEMP[topic_node][raw_time] = float(occupancy[:-2])\n else:\n dictTEMP[topic_node] = {raw_time:float(occupancy[:-2])}\n return dictCPU, dictMEM, dictTEMP\n\n\n\nif __name__ == \"__main__\":\n dictCPU,dictMEM,dictTEMP = TextReader(\"./system_monitor.log\")\n print(list(dictMEM.keys()))\n\n # ['/monitor', '/routing', '/rosout', '/ins', '/localization_dispatch_node',\n # '/control_node', '/rviz', '/system_monitor', '/decision_planning_node', \n # '/static_perception', '/canbus', '/localization', '/sensor_fusion', '/lidar_only_freespace']\n\n # for i in dictTEMP:\n # pprint(len(dictTEMP[i]))\n\n # Add histogram data\n x0 = list(dictTEMP[\"0\"].keys())\n x1 = list(dictTEMP[\"1\"].keys())\n y0 = list(dictTEMP[\"0\"].values())\n y1 = list(dictTEMP[\"1\"].values())\n pprint(x1)\n # Group data together\n\n y_temp =[ list(dictMEM[key].values()) for key in list(dictMEM.keys()) ]\n print(y_temp[0])\n x_temp = [ list(dictMEM[key].keys()) for key in list(dictMEM.keys()) ]\n print(x_temp[0])\n labels = list(dictMEM.keys())\n colors = ['rgb({},{},{})'.format(random.randint(0,255),\n random.randint(0,255),\n random.randint(0,255)) for i in range(100)]\n\n # hsv_tuples = [(1.0 * x / len(x_temp), 1., 1.) for x in range(len(x_temp))]\n # colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\n # colors = list(map(lambda x: 'rgb({},{},{})'.format(int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), colors))\n # random.seed(0)\n # random.shuffle(colors)\n # random.seed(None)\n\n print(len(x_temp))\n print(len(y_temp))\n\n\n fig = go.Figure()\n\n # for i in range(len(x_temp)):\n # fig.add_trace(go.Scatter(\n # x=x_temp[i],\n # y=y_temp[i],\n # name=\"{}\".format(labels[i]),\n # line=dict(color=colors[i], width=2)\n # )\n # )\n\n for i in range(len(x_temp)):\n fig.add_trace(go.Scatter(\n x=x_temp[i],\n y=y_temp[i],\n name=\"{}\".format(labels[i]),\n line=dict(width=2)\n )\n )\n\n\n # 6 5\n # fig.add_trace(go.Scatter(\n # x=x_temp[5],\n # y=y_temp[5],\n # name=\"{} {}\".format(labels[5],'cpu real time'),\n # line=dict(width=3)\n # ))\n\n # # 平均值\n # fig.add_trace(go.Scatter(\n # x=x_temp[5],\n # y=[np.mean(y_temp[5])] * len(x_temp[5]),\n # name=\"{} {}\".format(labels[5],'cpu average'),\n # line=dict(width=3, dash=\"dash\")\n # ))\n\n # fig.add_trace(go.Scatter(\n # x=x_temp[6],\n # y=y_temp[6],\n # name=\"{} {}\".format(labels[6],'cpu real time'),\n # line=dict(width=3)\n # ))\n\n # # 平均值\n # fig.add_trace(go.Scatter(\n # x=x_temp[6],\n # y=[np.mean(y_temp[6])] * len(x_temp[6]),\n # name=\"{} {}\".format(labels[6],'cpu average'),\n # line=dict(width=3, dash=\"dash\")\n # ))\n\n # fig.add_trace(go.Scatter(\n # x=x_temp[11],\n # y=y_temp[11],\n # name=\"{} {}\".format(labels[11],'cpu real time'),\n # line=dict(width=3)\n # ))\n\n # # 平均值\n # fig.add_trace(go.Scatter(\n # x=x_temp[11],\n # y=[np.mean(y_temp[11])] * len(x_temp[11]),\n # name=\"{} {}\".format(labels[11],'cpu average'),\n # line=dict(width=3, dash=\"dash\")\n # ))\n\n # fig.add_trace(go.Scatter(\n # x=x_temp[13],\n # y=y_temp[13],\n # name=\"{} {}\".format(labels[13],'cpu real time'),\n # line=dict(width=3)\n # ))\n\n # # 平均值\n # fig.add_trace(go.Scatter(\n # x=x_temp[13],\n # y=[np.mean(y_temp[13])] * len(x_temp[13]),\n # name=\"{} {}\".format(labels[13],'cpu average'),\n # line=dict(width=3, dash=\"dash\")\n # ))\n\n\n\n\n fig.update_layout(\n title=go.layout.Title(\n text=\"FT System Monitor\",\n font_size=30,\n xref=\"paper\",\n x=0\n ),\n xaxis=go.layout.XAxis(\n title=go.layout.xaxis.Title(\n text=\"x Axis\",\n font=dict(\n family=\"Courier New, monospace\",\n size=18,\n color=\"#7f7f7f\"\n )\n )\n ),\n yaxis=go.layout.YAxis(\n title=go.layout.yaxis.Title(\n text=\"y Axis\",\n font=dict(\n family=\"Courier New, monospace\",\n size=18,\n color=\"#7f7f7f\"\n )\n )\n )\n )\n\n\n\n fig.update_layout(\n height=1000,\n showlegend=True,\n legend=go.layout.Legend(\n font=dict(\n family=\"sans-serif\",\n size=24,\n color=\"black\"\n ),\n )\n )\n fig.show()\n py.plot(fig, filename = 'system_monitor_{}.html'.format(time.strftime(\"%Y-%m-%d\", time.localtime())), auto_open=False)","sub_path":"system_log/system_log_mem.py","file_name":"system_log_mem.py","file_ext":"py","file_size_in_byte":7519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"388724391","text":"from pynput.keyboard import Listener\nimport os\nimport logging\nfrom shutil import copyfile\n\nclear = lambda: os.system('cls')\nconsole_color = lambda: os.system('color a')\nconsole_color()\nclear()\n\nstart_program = input(\"---> Keylogger <---\\n\\nDo you wish to start the program? [y/n]\\n\")\n\nq1 = 0\nq2 = 0\n\nwhile q1 == 0:\n if start_program == \"y\":\n clear()\n break\n elif start_program == \"n\":\n clear()\n q2 += 1\n return_to_loader = input(\"Do you wish to return to the main loader? [y/n]\\n\")\n break\n else:\n clear()\n print(\"This is not a valid input, please try again\\n\")\n start_program = input(\"---> Keylogger <---\\n\\nDo you wish to start the program? [y/n]\\n\")\n\nwhile q2 == 1:\n if return_to_loader == \"y\":\n clear()\n exec(open(\"loader.py\").read())\n break\n elif return_to_loader == \"n\":\n clear()\n print(\"Exiting..\")\n exit()\n else:\n clear()\n print(\"This is not a valid input, please try again\")\n return_to_loader = input(\"Do you wish to return to the main loader? [y/n]\\n\")\n\nusername = os.getlogin()\n\n#copyfile('main.py', f'C:/Users/{username}/Appdata/Roaming/Microsoft/Start Menu/Startup/main.py') ---> Everytime you boot up the system it will automatically launch\n\nlogging_directory = f\"C:/Users/{username}/Desktop\"\n\nlogging.basicConfig(filename=f\"{logging_directory}/mylog.txt\", level=logging.DEBUG, format=\"%(asctime)s: %(message)s\")\n\ndef key_handler(key):\n logging.info(key)\n\nwith Listener(on_press=key_handler) as listener:\n listener.join()","sub_path":"Hack_app/apps/keylogger_app.py","file_name":"keylogger_app.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"28317057","text":"from django.contrib import admin\n\nfrom .models import Task\n\n\ndef cancel_task(modeladmin, request, queryset):\n queryset.update(status=\"CAN\")\n\n\ncancel_task.short_description = \"Cancel Selected Tasks\"\n\n\ndef complete_task(modeladmin, request, queryset):\n queryset.update(status=\"COM\")\n\n\ncomplete_task.short_description = \"Complete Selected Tasks\"\n\n\nclass TaskAdmin(admin.ModelAdmin):\n list_display = [\"text\", \"status\", \"due_date\", \"priority\", \"category\", \"occurrence\"]\n actions = [cancel_task, complete_task]\n date_hierarchy = \"create_ts\"\n # exclude = ('orig_text',)\n fields = (\n \"text\",\n (\"status\", \"category\", \"due_date\", \"priority\", \"assignee\"),\n (\"parent_id\", \"prereq_id\"),\n (\"occurrence\", \"occurrence_desc\"),\n (\"time_estimate_val\", \"time_estimate_metric\", \"time_actual_val\", \"time_actual_metric\"),\n (\"location\", \"percent_complete\"),\n )\n list_editable = (\"status\", \"category\", \"due_date\", \"priority\", \"occurrence\")\n list_filter = (\"status\", \"category\", \"priority\", \"assignee\", \"occurrence_descr\")\n list_per_page = 1000\n preserve_filters = True\n save_on_top = True\n search_fields = [\"text\", \"orig_text\"]\n\n\nadmin.site.register(Task, TaskAdmin)\n","sub_path":"todo/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"576220896","text":"\"\"\"\nBased on http://www.djangosnippets.org/snippets/595/\nby sopelkin\n\"\"\"\n\nfrom django import forms\nfrom django.forms import widgets\nfrom django.utils.html import conditional_escape\nfrom django.utils.safestring import mark_safe\nfrom django.utils.encoding import force_unicode\nfrom django_messages.utils import get_user_model\n\nUser = get_user_model()\n\n\nclass CommaSeparatedUserInput(widgets.HiddenInput):\n def render(self, name, value, attrs=None):\n if value is None:\n value = ''\n elif isinstance(value, (list, tuple)):\n value = (', '.join([str(user.pk) for user in value]))\n return super(CommaSeparatedUserInput, self).render(name, value, attrs)\n\n\nclass CommaSeparatedUserField(forms.Field):\n widget = CommaSeparatedUserInput\n \n def __init__(self, *args, **kwargs):\n recipient_filter = kwargs.pop('recipient_filter', None)\n self._recipient_filter = recipient_filter\n super(CommaSeparatedUserField, self).__init__(*args, **kwargs)\n \n def clean(self, value):\n super(CommaSeparatedUserField, self).clean(value)\n if not value:\n return ''\n if isinstance(value, (list, tuple)):\n return value\n \n ids = set(value.split(','))\n ids_set = set([uid.strip() for uid in ids if uid.strip()])\n users = list(User.objects.filter(pk__in=ids_set))\n unknown_ids = ids_set ^ set([str(user.pk) for user in users])\n \n recipient_filter = self._recipient_filter\n invalid_users = []\n if recipient_filter is not None:\n for r in users:\n if recipient_filter(r) is False:\n users.remove(r)\n invalid_users.append(r.pk)\n \n if unknown_ids or invalid_users:\n incorrect = [str(uid) for uid in list(unknown_ids)+invalid_users]\n raise forms.ValidationError(u\"The following user IDs are incorrect: %(users)s\" % {'users': ', '.join(incorrect)})\n \n return users\n\nclass PlainTextWidget(widgets.HiddenInput):\n is_hidden = False\n\n def render(self, name, value, attrs=None):\n if value is None:\n value = ''\n value = conditional_escape(force_unicode(value))\n return mark_safe(u'

%s

' % value)\n\nclass PlainHTMLWidget(widgets.HiddenInput):\n is_hidden = False\n\n def render(self, name, value, attrs=None):\n if value is None:\n value = ''\n return conditional_escape(force_unicode(value))\n\nclass ReadOnlyField(forms.Field):\n widget = PlainHTMLWidget\n\n def __init__(self, *args, **kwargs):\n kwargs['required'] = False\n return super(ReadOnlyField, self).__init__(*args, **kwargs)\n\n def bound_data(self, value, initial):\n return initial\n","sub_path":"django_messages/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"225059772","text":"import os\nfrom codecs import open as codecs_open\nfrom setuptools import setup, find_packages\n\n\nwith codecs_open('README.rst', encoding='utf-8') as f:\n long_description = f.read()\n\n\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\n\nsetup(name='fio-plugins',\n version='0.0.1',\n description=\"Fiona CLI plugin to calculate areas\",\n long_description=long_description,\n classifiers=[],\n keywords='fiona',\n author=u\"Damon Burgett\",\n author_email='damon@mapbox.com',\n url='https://github.com/mapbox/fio-area',\n license='BSD',\n packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),\n include_package_data=True,\n zip_safe=False,\n install_requires=read('requirements.txt').splitlines(),\n extras_require={\n 'test': ['pytest', 'pytest-cov', 'coveralls'],\n },\n entry_points=\"\"\"\n [fiona.fio_commands]\n area=fio_area.scripts.cli:area\n \"\"\")\n","sub_path":"pypi_install_script/fio-plugins-0.0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"411698086","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\n\nimport matplotlib as mpl\nimport numpy as np\n\nmpl.use(\"Qt4Agg\")\n\n\n# settings for latex\n# calculate optimal figsize with the golden ratio\ndef figsize(scale):\n fig_width_pt = 448.13095 # Get this from LaTeX using \\the\\textwidth\n inches_per_pt = 1.0 / 72.27 # Convert pt to inch\n golden_ratio = (np.sqrt(5.0) - 1.0) / 2.0 # Aesthetic ratio (you could change this)\n fig_width = fig_width_pt * inches_per_pt * scale # width in inches\n fig_height = fig_width * golden_ratio # height in inches\n fig_size = [fig_width, fig_height]\n return fig_size\n\nlatex_settings = { # setup matplotlib to use latex for output\n \"pgf.texsystem\": \"pdflatex\", # change this if using xetex or lautex\n \"text.usetex\": True, # use LaTeX to write all text\n \"font.family\": \"serif\",\n \"font.serif\": [], # blank entries should cause plots to inherit fonts from the document\n \"font.sans-serif\": [],\n \"font.monospace\": [],\n # \"text.fontsize\": 11,\n \"legend.fontsize\": 9, # Make the legend/label fonts a little smaller\n \"xtick.labelsize\": 9,\n \"ytick.labelsize\": 9,\n \"figure.figsize\": figsize(1), # default fig size of 1.0 textwidth\n \"lines.linewidth\": 0.5,\n \"axes.labelsize\": 11, # LaTeX default is 10pt font.\n \"axes.linewidth\": 0.5,\n \"axes.unicode_minus\": False,\n \"figure.subplot.left\": 0.1, # the left side of the subplots of the figure\n \"figure.subplot.right\": 0.95, # the right side of the subplots of the figure\n \"figure.subplot.bottom\": 0.125, # the bottom of the subplots of the figure\n \"figure.subplot.top\": 0.95, # the top of the subplots of the figure\n \"figure.subplot.wspace\": 0.4, # the amount of width reserved for blank space between subplots\n \"figure.subplot.hspace\": 0.4, # the amount of height reserved for white space between subplots\n \"patch.linewidth\": 0.5,\n # Patches are graphical objects that fill 2D space, like polygons or circles\n }\nmpl.rcParams.update(latex_settings)\n\nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nfrom matplotlib.lines import Line2D as Line\n\nfrom registry import register_processing_module\nfrom processing_core import PostProcessingModule, MetaProcessingModule\nfrom tools import sort_tree\n\n__author__ = 'stefan, christoph'\n\n\nclass StepResponse(PostProcessingModule):\n \"\"\"\n Postprocessor that creates diagrams for step response experiments.\n\n Various measures are taken, displayed in a diagram and saved to result files. The following list contains the\n measured/calculated entries and their explanations:\n - rise time (t_rise): time needed until the output reaches 90% of its desired value\n - correction time (t_corr): time needed until the output reaches the desired value for the first time\n - overshoot time (t_over): time of the greatest overshot\n - overshot: maximum error between is and desired while approaching the desired value\n - damping time (t_damp): time needed for the output to enter and remain in an epsilon region around\n the desired value\n \"\"\"\n line_color = '#aaaaaa'\n line_style = '-'\n font_size = 20\n spacing = 0.01\n counter = 0\n eps = 1e-3\n\n def __init__(self):\n PostProcessingModule.__init__(self)\n self.label_positions = None\n return\n\n def run(self, data):\n\n # dict for calculated values\n output = {}\n\n # reset counter\n self.counter = 0\n\n # calculate data sets\n t = data[\"results\"][\"time\"]\n y = data[\"results\"][\"Model\"][:, 0]\n yd = data[\"results\"][\"Trajectory\"][-1][0]\n\n self.label_positions = np.arange(np.min(y) + 0.1 * yd, yd, (yd - np.min(y)) / 4)\n\n # create plot\n fig = Figure()\n axes = fig.add_subplot(111)\n axes.set_title(r\"\\textbf{Sprungantwort}\")\n axes.plot(t, y, c='k')\n axes.set_xlim(left=0, right=t[-1])\n axes.set_xlabel(r\"\\textit{Zeit [s]}\")\n axes.set_ylabel(r\"\\textit{Systemausgang [m]}\")\n\n # create desired line\n desired_line = Line([0, t[-1]], [yd, yd], lw=1, ls=self.line_style, c='k')\n axes.add_line(desired_line)\n\n # calc rise-time (Anstiegszeit)\n try:\n t_rise = t[np.where(y > 0.9*yd)][0]\n self.create_time_line(axes, t, y, t_rise, r\"$T_r$\")\n output.update({\"t_rise\": t_rise})\n except IndexError:\n output.update({\"t_rise\": None})\n\n # calc correction-time (Anregelzeit)\n try:\n t_corr = t[np.where(y > yd)][0]\n self.create_time_line(axes, t, y, t_corr, r\"$T_{anr}$\")\n output.update({\"t_corr\": t_corr})\n except IndexError:\n output.update({\"t_corr\": None})\n\n # calc overshoot-time and overshoot in percent (Überschwingzeit und Überschwingen)\n if output[\"t_corr\"]:\n if yd > 0:\n y_max = np.max(y[np.where(t > output[\"t_corr\"])])\n else:\n y_max = np.min(y[np.where(t > output[\"t_corr\"])])\n\n t_over = t[np.where(y == y_max)][0]\n overshoot = y_max - yd\n overshoot_per = overshoot/yd * 100\n\n self.create_time_line(axes, t, y, t_over, r\"$T_o$\")\n output.update(dict(t_over=t_over, overshoot=overshoot, overshoot_percent=overshoot_per))\n else:\n output.update(dict(t_over=None, overshoot=None, overshoot_percent=None))\n\n # calc damping-time (Beruhigungszeit)\n try:\n enter_idx = -1\n for idx, val in enumerate(y):\n if enter_idx == -1:\n if abs(val - yd) < self.eps:\n enter_idx = idx\n else:\n if abs(val - yd) >= self.eps:\n enter_idx = -1\n\n t_damp = t[enter_idx]\n self.create_time_line(axes, t, y, t_damp, r\"$T_{\\epsilon}$\")\n output.update({\"t_damp\": t_damp})\n except IndexError:\n output.update({\"t_damp\": None})\n\n # create epsilon tube\n upper_bound_line = Line([0, t[-1]], [yd + self.eps, yd + self.eps], ls=\"--\", c=self.line_color)\n axes.add_line(upper_bound_line)\n lower_bound_line = Line([0, t[-1]], [yd - self.eps, yd - self.eps], ls=\"--\", c=self.line_color)\n axes.add_line(lower_bound_line)\n\n # calc stationary control deviation\n control_deviation = y[-1] - yd\n output.update({\"stationary_error\": control_deviation})\n\n self.calc_metrics(data, output)\n\n # check for sim success\n if not data[\"results\"][\"finished\"]:\n for key in output.keys():\n output[key] = None\n\n # add settings and metrics to dictionary results\n results = {}\n results.update({\"metrics\": output})\n results.update({\"modules\": data[\"modules\"]})\n\n canvas = FigureCanvas(fig)\n\n self.write_output_files(data[\"regime name\"], fig, results)\n\n return [dict(name='_'.join([data[\"regime name\"], self.name]), figure=canvas)]\n\n def create_time_line(self, axes, t, y, time_value, label):\n if time_value != t[-1]:\n time_line = Line([time_value, time_value],\n [np.min(y), y[np.where(t == time_value)][0]],\n ls=self.line_style,\n c=self.line_color)\n axes.add_line(time_line)\n axes.text(time_value + self.spacing, self.label_positions[self.counter],\n label, size=self.font_size)\n self.counter += 1\n\n def calc_metrics(self, data, output):\n \"\"\"\n calculate metrics for comparison\n :param output:\n :param data:\n \"\"\"\n # TODO check those they produce crap -> see output\n l1_norm_itae = self.calc_l1_norm_itae(*self.get_metric_values(data))\n l1_norm_abs = self.calc_l1_norm_abs(*self.get_metric_values(data))\n\n self._logger.info(\"calculated L1NormITAE: {}\".format(l1_norm_itae))\n self._logger.info(\"calculated L1NormAbs: {}\".format(l1_norm_abs))\n\n output.update({'L1NormITAE': l1_norm_itae, 'L1NormAbs': l1_norm_abs})\n\n @staticmethod\n def get_metric_values(data):\n \"\"\"\n helper function to extract data needed to calculate metrics for this postprocessor\n overload to fit custom model\n\n :param data: simulation data\n :return: tuple of (is_values, desired_values, step_width)\n \"\"\"\n metric_values = (data[\"results\"][\"Model\"],\n data[\"results\"][\"Trajectory\"],\n 1/data[\"modules\"][\"Solver\"][\"measure rate\"])\n\n return metric_values\n\n\nclass PlotAll(PostProcessingModule):\n \"\"\"\n plot diagrams of all system quantities\n \"\"\"\n def __init__(self):\n PostProcessingModule.__init__(self)\n return\n\n def run(self, data):\n\n # dict for calculated values\n output = {}\n return_list = []\n\n t = data[\"results\"][\"time\"]\n val = t # default\n\n for module_name, module_data in data[\"results\"].iteritems():\n if module_name in [\"time\", \"finished\", \"Simulation\"]:\n continue\n\n module_shape = module_data.shape\n for idx in range(module_shape[1]):\n if len(module_shape) == 3:\n val = module_data[:, idx, 0]\n if len(module_shape) == 2:\n val = module_data[:, idx]\n\n plot_name = '_'.join({data[\"regime name\"], self.name, module_name, str(idx)})\n fig = Figure()\n axes = fig.add_subplot(111)\n axes.set_title(r\"\\textbf{%s %d}\" % (module_name.replace(\"_\", \" \"), idx))\n axes.plot(t, val, c='k')\n axes.set_xlim(left=0, right=t[-1])\n axes.set_xlabel(r\"Zeit [s]\")\n axes.set_ylabel(r\"%s %s\" % (module_name.replace(\"_\", \" \"), str(idx)))\n axes.grid(True)\n canvas = FigureCanvas(fig)\n\n return_list.append({\"name\": plot_name, \"figure\": canvas})\n\n return return_list\n\n\nclass XYMetaProcessor(MetaProcessingModule):\n \"\"\"\n create XY-diagrams for the given key to be compared\n \"\"\"\n def __init__(self, sort_key, x_path, y_path):\n MetaProcessingModule.__init__(self)\n self.sort_key = sort_key\n self.x_path = x_path\n self.y_path = y_path\n\n self.fig = None\n self.axes = None\n\n return\n\n def process(self, post_results):\n # create tree with relevant data\n source = sort_tree(post_results, self.sort_key)\n\n # create plot\n self.fig = Figure()\n self.axes = self.fig.add_subplot(111)\n\n self.plot_family(source, self.x_path, self.y_path, \"line\")\n self.set_plot_labeling()\n\n # extract member_names (subtract common appendix like *Controller or *Feedforward)\n member_names = [x[:-len(self.x_path[1])] for x in source.keys()]\n\n canvas = FigureCanvas(self.fig)\n\n # write output files\n file_name = self.name + \"_\".join([self.x_path[1], \"(\"]) + \"\".join(member_names) + \")\"\n self.write_output_files(file_name, self.fig)\n\n return [{'figure': canvas, 'name': self.name}]\n\n\ndef construct_result_dict(data, output):\n # check for sim success\n if not data[\"results\"][\"finished\"]:\n for key in output.keys():\n output[key] = None\n\n # add settings and metrics to dictionary results\n results = {}\n results.update({'metrics': output})\n results.update({'modules': data['modules']})\n\n return results\n","sub_path":"pymoskito/generic_processing_modules.py","file_name":"generic_processing_modules.py","file_ext":"py","file_size_in_byte":12082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"445176761","text":"#!/usr/bin/env python\n# coding: utf-8\n# Import Splinter and BeautifulSoup\n# Import Splinter and BeautifulSoup and Pandas\nfrom splinter import Browser\nfrom bs4 import BeautifulSoup as soup\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport pandas as pd\nimport datetime as dt\nimport time \n\n\ndef scrape_all():\n # Set up Splinter initiate headless driver for deployment\n executable_path = {'executable_path': ChromeDriverManager().install()}\n browser = Browser('chrome', **executable_path, headless=True)\n \n news_title, news_paragraph = mars_news(browser)\n\n #Run all scraping functions and store results in dictionary\n data = {\n \"news_title\": news_title,\n \"news_paragraph\": news_paragraph,\n \"featured_image\": featured_image(browser),\n \"facts\": mars_facts(),\n \"hemispheres\": mars_hemispheres(),\n \"last_modified\": dt.datetime.now()\n }\n #stop webdriver and return data \n browser.quit()\n return data \n\ndef mars_news(browser):\n\n #Scrape Mars News\n # Visit the mars nasa news site\n url = 'https://data-class-mars.s3.amazonaws.com/Mars/index.html'\n browser.visit(url)\n\n # Optional delay for loading the page\n browser.is_element_present_by_css('div.list_text', wait_time=1)\n\n # Convert the browser html to a soup object then quit the browser\n html = browser.html\n news_soup = soup(html, 'html.parser')\n\n #Add try/except for error handling\n try: \n \n slide_elem = news_soup.select_one('div.list_text')\n # Use the parent element to find the first `a` tag and save it as `news_title`\n news_title = slide_elem.find('div', class_='content_title').get_text()\n # Use the parent element to find the paragraph text\n news_p = slide_elem.find('div', class_='article_teaser_body').get_text()\n \n except AttributeError:\n return None, None \n\n return news_title, news_p\n\n# ### JPL Space Images Featured Image\n\ndef featured_image(browser):\n # Visit URL\n url = 'https://data-class-jpl-space.s3.amazonaws.com/JPL_Space/index.html'\n browser.visit(url)\n\n # Find and click the full image button\n full_image_elem = browser.find_by_tag('button')[1]\n full_image_elem.click()\n\n # Parse the resulting html with soup\n html = browser.html\n img_soup = soup(html, 'html.parser')\n\n #create try/except clause\n try: \n # Find the relative image url\n img_url_rel = img_soup.find('img', class_='fancybox-image').get('src')\n\n except AttributeError:\n return None \n\n # Use the base URL to create an absolute URL\n img_url = f'https://data-class-jpl-space.s3.amazonaws.com/JPL_Space/{img_url_rel}'\n return img_url\n\n\n\n# ## Mars Facts \n\ndef mars_facts():\n #Add try/except for error handling\n try:\n #use 'read_html\" to scrape the facts table into a dataframe\n df = pd.read_html('https://data-class-mars-facts.s3.amazonaws.com/Mars_Facts/index.html')[0]\n except BaseException:\n return None\n\n #Assign columns and set index of dataframe\n df.columns=['Description', 'Mars', 'Earth']\n df.set_index('Description', inplace=True)\n\n #Convert dataframe into HTML format, add bootstrap\n return df.to_html(classes=\"table table-striped\")\n\n# # D1: Scrape High-Resolution Mars’ Hemisphere Images and Titles\n# \n# ### Hemispheres\n# \n\n# 1. Use browser to visit the URL \n\n\n\n# 2. Create a list to hold the images and titles.\nhemisphere_image_urls = []\n\n# 3. Write code to retrieve the image urls and titles for each hemisphere.\ndef mars_hemispheres():\n executable_path = {'executable_path': ChromeDriverManager().install()}\n browser = Browser('chrome', **executable_path, headless=False)\n url1 = 'https://marshemispheres.com/'\n browser.visit(url1)\n for i in range(0,4):\n hemispheres = {}\n try:\n browser.find_by_css('a.product-item img')[i].click()\n title=browser.find_by_css('h2.title')\n #print(title.text)\n time.sleep(2)\n img_url = browser.find_by_text('Sample')\n #imgs = browser.find_by_text('Sample')\n #print(img_url['href'])\n time.sleep(2)\n hemispheres[\"title\"]=title.text\n hemispheres[\"img_url\"]=img_url['href']\n #hemispheres[\"imgs\"]=imgs['href']\n hemisphere_image_urls.append(hemispheres)\n browser.back()\n \n except Exception as e:\n print(e)\n\n return(hemisphere_image_urls)\n # 4. Print the list that holds the dictionary of each image url and title.\n\n\n hemisphere_image_urls\n # 5. Quit the browser\n browser.quit()\n\n\n# 4. Print the list that holds the dictionary of each image url and title.\n\n\n\n\n\n","sub_path":"Mission_to_Mars_Challenge.py","file_name":"Mission_to_Mars_Challenge.py","file_ext":"py","file_size_in_byte":4735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"459071731","text":"# from bs4 import BeautifulSoup\n# import requests\n#\n#\n# website_url='https://www.amazon.in/'\n# context=requests.get(website_url)\n# soup=BeautifulSoup(context.text,'lxml')\n# for link in soup.find_all('a'):\n# print(link.get('href'))\n\n\nfrom bs4 import BeautifulSoup\nimport requests\n\n\na=input('enter a webpage url : ')\npage = requests.get(a)\nsoup = BeautifulSoup(page.content, 'html.parser')\n\n\ndef retrieve_all_products():\n d={}\n aa=[]\n a=(soup.find_all('a'))\n print('qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq',a)\n html=''\n try:\n html = a.replace('
', '\\n')\n except:\n pass\n html = html.split()\n oo=''\n pp=''\n rr=''\n print(html)\n for i in html:\n if i.startswith('href='):\n o=i.find('/p')\n oo=i[7:o]\n if i.startswith('-->'):\n p=(i[3:])\n pp=p\n if i.startswith('class=\"_1vC4OE\">₹'):\n r=i.replace('class=\"_1vC4OE\">₹','')\n rr=r\n b = {'name':oo,'Real-price':pp,'offer-price':rr}\n if oo and pp:\n if b not in aa:\n aa.append(b)\n for i in aa:\n print(i)\n\n\n\nif __name__ == '__main__':\n retrieve_all_products()","sub_path":"beati.py","file_name":"beati.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"452827388","text":"# -*- coding: utf-8 -*-\n# __author__ = 'XingHuan'\n# 10/1/2018\n\n# Copyright 2018 XingHuan\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport os\nfrom sins.module.sqt import *\nfrom sins.utils.res import resource\nfrom sins.utils.path.file import get_dirs, get_detail_of_path, get_files, get_sequences\nfrom sins.ui.utils.color import get_text_color\nfrom sins.utils.const import VIDEO_EXT, MODEL_EXT\n\n\nclass FileTreeItem(QTreeWidgetItem):\n def __init__(self, detailDict, parent=None):\n super(FileTreeItem, self).__init__(parent)\n\n self.name = detailDict[\"name\"]\n self.type = detailDict[\"type\"]\n self.size = detailDict[\"size\"]\n self.modified_date = detailDict[\"modified date\"]\n self.filePath = detailDict[\"file path\"]\n self.ext = os.path.splitext(self.filePath)[1]\n self.is_seq = detailDict.get(\"is_sequence\")\n self.frame_range = detailDict.get(\"frame range\")\n self.is_file = not self.type == 'folder'\n\n self.setText(0, self.name)\n self.setText(1, self.type)\n self.setText(2, self.size)\n self.setText(3, self.modified_date)\n\n if self.is_seq:\n self.setText(0, self.name + \" \" + self.frame_range)\n self.setText(1, self.type + \" sequence\")\n\n # icon\n current_text_color = get_text_color()\n is_dark = current_text_color.lightness() > 150\n\n icon = None\n if is_dark:\n subfix = \"_gray.png\"\n else:\n subfix = \"_darkgray.png\"\n if self.type == \"folder\":\n icon = 'folder1' + subfix\n elif self.is_seq:\n icon = 'file_sequence' + subfix\n elif self.ext in MODEL_EXT:\n icon = 'file_model' + subfix\n elif self.ext in VIDEO_EXT:\n icon = 'file_video' + subfix\n\n if icon is not None:\n self.setIcon(0, resource.get_qicon(\"icon\", icon))\n\n def real_path(self, add_frame=False):\n if add_frame and self.frame_range is not None:\n return self.filePath + ' ' + self.frame_range\n else:\n return self.filePath\n\n\nclass FileTree(QTreeWidget):\n def __init__(self,\n folder_color=None,\n folder_height=None,\n file_color=None,\n file_height=None,\n *args, **kwargs\n ):\n super(FileTree, self).__init__(*args, **kwargs)\n\n self.root_path = None\n self.show_seq = True\n self.keep_ext = None\n self.except_ext = None\n self.folder_color = folder_color\n self.folder_height = folder_height\n self.file_color = file_color\n self.file_height = file_height\n\n self.setHeaderLabels([\"name\", \"type\", \"size\", \"modified date\"])\n self.setSelectionMode(QAbstractItemView.ExtendedSelection)\n self.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)\n self.setSortingEnabled(True)\n self.sortByColumn(3, Qt.DescendingOrder)\n self.setColumnWidth(0, 200)\n self.setAnimated(True)\n\n def set_dir(self, dir_path):\n self.root_path = dir_path\n\n def set_show_seq(self, show):\n self.show_seq = show\n\n def set_keep(self, value):\n self.keep_ext = []\n value = value if isinstance(value, list) else [value]\n self.keep_ext.extend(value)\n if 'folder' not in self.keep_ext:\n self.keep_ext.append('folder')\n\n def set_except(self, value):\n self.except_ext = value if isinstance(value, list) else [value]\n\n def refresh_tree(self):\n self.clear()\n if os.path.isdir(self.root_path):\n self.add_folder(self.root_path, parent_item=self)\n self.expandAll()\n\n def add_folder(self, path, parent_item):\n allFiles = []\n for i in get_dirs(path):\n allFiles.append(get_detail_of_path(i))\n allFileDetail = []\n if not self.show_seq:\n for i in get_files(path):\n allFileDetail.append(get_detail_of_path(i))\n else:\n for i in get_sequences(path):\n allFileDetail.append(get_detail_of_path(i))\n\n for detail in allFileDetail:\n allFiles.append(detail)\n\n for detail in allFiles:\n type = detail['type']\n if (self.keep_ext is not None and type in self.keep_ext) or \\\n (self.except_ext is not None and type not in self.except_ext) or \\\n (self.keep_ext is None and self.except_ext is None):\n self.add_item(detail, parent_item)\n # else:\n # self.add_item(detail, parent_item)\n\n def add_item(self, detail, parent_item):\n type = detail['type']\n fileItem = FileTreeItem(detail)\n if parent_item is self:\n self.addTopLevelItem(fileItem)\n else:\n parent_item.addChild(fileItem)\n\n if type == 'folder':\n self.add_folder(detail['file path'], parent_item=fileItem)\n color = self.folder_color\n height = self.folder_height\n else:\n color = self.file_color\n height = self.file_height\n\n if color is not None:\n for i in range(self.columnCount()):\n fileItem.setBackground(i, color)\n if height is not None:\n fileItem.setSizeHint(0, QSize(20, height))\n\n\n\n\n\nif __name__ == \"__main__\":\n import sys\n app = QApplication(sys.argv)\n panel = FileTree()\n panel.set_dir('F:/Temp/pycharm/Sins_project/Sins/sins/resource')\n panel.set_keep('css')\n # panel.set_dir('F:/Projects/show/HHD/shot/seq01/shot01/ani/work/ani01/maya/images')\n panel.refresh_tree()\n panel.show()\n app.exec_()\n","sub_path":"sins/ui/widgets/file_browser/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":6203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"164044642","text":"import math\r\nimport openpmd_api as io\r\nimport numpy as np\r\nfrom numpy import random\r\nfrom scipy import constants\r\n\r\nn = 1000000\r\nbeam_density = 3.\r\nplasma_density = 2.8239587008591567e23\r\nbeam_position_mean = [0, 0, 0]\r\nbeam_position_std = [0.3, 0.3, 1.41]\r\nbeam_u_mean = [0, 0, 2000]\r\nbeam_u_std = [0, 0, 0]\r\n\r\nkp_inv = constants.c / constants.e * math.sqrt(constants.epsilon_0 * constants.m_e / plasma_density)\r\n\r\nsingle_charge = (beam_density * beam_position_std[0] * beam_position_std[1] *\r\n beam_position_std[2] * np.sqrt(2. * math.pi)**3 / n)\r\n\r\nnp.random.seed(0)\r\ndata = np.zeros([6,n],dtype=np.float64)\r\n\r\nfor i in [0,1,2]:\r\n data[i]=random.normal(beam_position_mean[i],beam_position_std[i],n)\r\n data[i+3]=random.normal(beam_u_mean[i],beam_u_std[i],n)\r\n\r\nseries = io.Series(\"beam_%05T.h5\", io.Access.create)\r\n\r\ni = series.iterations[0]\r\n\r\nparticle = i.particles[\"Electrons\"]\r\n\r\nparticle.set_attribute(\"HiPACE++_Plasma_Density\", plasma_density)\r\n\r\ndataset = io.Dataset(data[0].dtype,data[0].shape)\r\n\r\nparticle[\"r\"].unit_dimension = {\r\n io.Unit_Dimension.L: 1,\r\n}\r\n\r\nparticle[\"u\"].unit_dimension = {\r\n io.Unit_Dimension.L: 1,\r\n io.Unit_Dimension.T: -1,\r\n}\r\n\r\nparticle[\"q\"].unit_dimension = {\r\n io.Unit_Dimension.I: 1,\r\n io.Unit_Dimension.T: 1,\r\n}\r\n\r\nparticle[\"m\"].unit_dimension = {\r\n io.Unit_Dimension.M: 1,\r\n}\r\n\r\nfor k,m in [[\"x\",0],[\"y\",1],[\"z\",2]]:\r\n particle[\"r\"][k].reset_dataset(dataset)\r\n particle[\"r\"][k].store_chunk(data[m])\r\n particle[\"r\"][k].unit_SI = kp_inv\r\n\r\nfor k,m in [[\"x\",3],[\"y\",4],[\"z\",5]]:\r\n particle[\"u\"][k].reset_dataset(dataset)\r\n particle[\"u\"][k].store_chunk(data[m])\r\n particle[\"u\"][k].unit_SI = 1\r\n\r\nparticle[\"q\"][\"q\"].reset_dataset(dataset)\r\nparticle[\"q\"][\"q\"].make_constant(single_charge)\r\nparticle[\"q\"][\"q\"].unit_SI = constants.e * plasma_density * kp_inv**3\r\n\r\nparticle[\"m\"][\"m\"].reset_dataset(dataset)\r\nparticle[\"m\"][\"m\"].make_constant(single_charge)\r\nparticle[\"m\"][\"m\"].unit_SI = constants.m_e * plasma_density * kp_inv**3\r\n\r\nseries.flush()\r\n\r\ndel series\r\n","sub_path":"tools/write_beam.py","file_name":"write_beam.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"153033203","text":"# ----------------------------------------------------------------------------\n# copyright 2016 Nervana Systems Inc.\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 numpy as np\nimport pytest\nfrom contextlib import closing\nfrom ngraph.testing import ExecutorFactory\nfrom orderedset import OrderedSet\nfrom test_hetr_passes import check_device_assign_pass, check_communication_pass\nimport ngraph as ng\nimport ngraph.transformers as ngt\nfrom ngraph.transformers.hetr.mpilauncher import MPILauncher\nfrom multiprocessing import active_children\nimport time\nimport os\nimport subprocess\nimport tempfile\n\n\npytestmark = pytest.mark.hetr_only\nSTARTUP_TIME = 3\n\n\ndef test_distributed_graph_plus_one():\n H = ng.make_axis(length=4, name='height')\n W = ng.make_axis(length=6, name='width')\n x = ng.placeholder(axes=[H, W])\n with ng.metadata(device_id=('0', '1'), parallel=W):\n x_plus_one = x + 1\n\n np_x = np.random.randint(100, size=[H.length, W.length])\n with ExecutorFactory() as ex:\n computation = ex.executor(x_plus_one, x)\n res = computation(np_x)\n np.testing.assert_array_equal(res, np_x + 1)\n\n\ndef test_distributed_dot_parallel_first_axis():\n H = ng.make_axis(length=4, name='height')\n N = ng.make_axis(length=8, name='batch')\n weight = ng.make_axis(length=2, name='weight')\n x = ng.placeholder(axes=[N, H])\n w = ng.placeholder(axes=[H, weight])\n with ng.metadata(device_id=('0', '1'), parallel=N):\n dot = ng.dot(x, w)\n\n np_x = np.random.randint(100, size=[N.length, H.length])\n np_weight = np.random.randint(100, size=[H.length, weight.length])\n with ExecutorFactory() as ex:\n computation = ex.executor(dot, x, w)\n res = computation(np_x, np_weight)\n np.testing.assert_array_equal(res, np.dot(np_x, np_weight))\n\n\ndef test_distributed_dot_parallel_second_axis():\n pytest.xfail(\"'parallel' for not first axis isn't supported yet\")\n\n H = ng.make_axis(length=4, name='height')\n N = ng.make_axis(length=8, name='batch')\n weight = ng.make_axis(length=2, name='weight')\n x = ng.placeholder(axes=[H, N])\n w = ng.placeholder(axes=[weight, H])\n with ng.metadata(device_id=('0', '1'), parallel=N):\n dot = ng.dot(w, x)\n\n np_x = np.random.randint(100, size=[H.length, N.length])\n np_weight = np.random.randint(100, size=[weight.length, H.length])\n with ExecutorFactory() as ex:\n computation = ex.executor(dot, x, w)\n res = computation(np_x, np_weight)\n np.testing.assert_array_equal(res, np.dot(np_weight, np_x))\n\n\ndef test_distributed_graph_plus_two():\n W = ng.make_axis(length=6, name='width')\n H = ng.make_axis(length=4, name='height')\n x = ng.placeholder(axes=[W, H])\n with ng.metadata(device_id=('0', '1'), parallel=W):\n x_plus_one = x + 1\n x_plus_two = x_plus_one + 1\n\n np_x = np.random.randint(100, size=[W.length, H.length])\n with ExecutorFactory() as ex:\n computation = ex.executor(x_plus_two, x)\n res = computation(np_x)\n np.testing.assert_array_equal(res, np_x + 2)\n\n\ndef test_singleton_device_id():\n with ng.metadata(device_id=(['1'])):\n x = ng.placeholder(())\n graph_ops = OrderedSet([x])\n\n graph_op_metadata = {op: list() for op in graph_ops}\n graph_op_metadata[x] = [\"cpu\", '1']\n\n check_device_assign_pass(\"cpu\", \"0\", graph_op_metadata, graph_ops)\n\n\ndef test_from_device():\n with ng.metadata(device_id='1'):\n x = ng.placeholder(())\n x_plus_one = x + 1\n\n with ExecutorFactory() as ex:\n computation = ex.executor(x_plus_one, x)\n for i in [10, 20, 30]:\n assert computation(i) == i + 1\n\n\ndef test_to_device():\n x = ng.placeholder(())\n with ng.metadata(device_id='1'):\n x_plus_one = x + 1\n\n with ExecutorFactory() as ex:\n computation = ex.executor(x_plus_one, x)\n for i in [10, 20, 30]:\n assert computation(i) == i + 1\n\n\ndef test_to_and_from_device():\n x = ng.placeholder(())\n with ng.metadata(device_id='1'):\n x_plus_one = x + 1\n x_plus_two = x_plus_one + 1\n\n with ExecutorFactory() as ex:\n computation = ex.executor(x_plus_two, x)\n for i in [10, 20, 30]:\n assert computation(i) == i + 2\n\n\ndef test_computation_return_list():\n with ng.metadata(device_id='1'):\n x = ng.placeholder(())\n x_plus_one = x + 1\n x_plus_two = x + 2\n x_mul_three = x * 3\n\n with ExecutorFactory() as ex:\n computation = ex.executor([x_plus_one, x_plus_two, x_mul_three], x)\n for i in [10, 20, 30]:\n assert computation(i) == (i + 1, i + 2, i * 3)\n\n\ndef test_scatter_gather_graph():\n # Build the graph\n W = ng.make_axis(length=6, name='width')\n\n with ng.metadata(device_id='0'):\n x = ng.placeholder(())\n z = ng.placeholder(())\n\n with ng.metadata(device_id=('1', '2'), parallel=W):\n y = ng.placeholder(())\n\n x_plus_z = x + z # Does not create a recv node\n x_plus_y = x + y # creates a gather recv node\n\n # Build the graph metadata\n graph_ops = OrderedSet([x, y, z, x_plus_z, x_plus_y])\n\n graph_op_metadata = {op: list() for op in graph_ops}\n graph_op_metadata[x] = [\"cpu\", '0']\n graph_op_metadata[z] = [\"cpu\", '0']\n graph_op_metadata[y] = [\"cpu\", ('1', '2')]\n graph_op_metadata[x_plus_z] = [\"cpu\", '0']\n graph_op_metadata[x_plus_y] = [\"cpu\", '0']\n\n check_device_assign_pass(\"cpu\", \"0\", graph_op_metadata, graph_ops)\n\n check_communication_pass(\n ops_to_transform=graph_ops,\n expected_recv_nodes=[x_plus_y])\n\n\n@pytest.mark.hetr_gpu_only\ndef test_gpu_send_and_recv():\n pytest.xfail(\"GitHub issue: #2007, Unknown error - investigation is needed\")\n # put x+1 on cpu numpy\n with ng.metadata(device='cpu'):\n x = ng.placeholder(())\n x_plus_one = x + 1\n # put x+2 on gpu numpy\n with ng.metadata(device='gpu'):\n x_plus_two = x_plus_one + 1\n\n with ExecutorFactory() as ex:\n computation = ex.executor(x_plus_two, x)\n for i in [10, 20, 30]:\n assert computation(i) == i + 2\n\n # put x+1 on gpu numpy\n with ng.metadata(device='gpu'):\n x = ng.placeholder(())\n x_plus_one = x + 1\n # put x+2 on cpu numpy\n with ng.metadata(device='cpu'):\n x_plus_two = x_plus_one + 1\n\n with ExecutorFactory() as ex:\n computation = ex.executor(x_plus_two, x)\n for i in [10, 20, 30]:\n assert computation(i) == i + 2\n\n\ndef test_recvop_axes_using_dot():\n x_value = np.array([[1],\n [2]])\n w_value = np.array([[-1, 1]])\n\n A1 = ng.make_axis(length=1)\n A2 = ng.make_axis(length=2)\n A3 = ng.make_axis(length=2)\n\n x = ng.placeholder([A2, A1])\n w = ng.variable([A1, A3], initial_value=w_value)\n\n with ng.metadata(device_id='1'):\n result = ng.dot(x, w)\n\n with ExecutorFactory() as ex:\n computation = ex.executor(result, x, w)\n val_ng = computation(x_value, w_value)\n val_np = np.dot(x_value, w_value)\n ng.testing.assert_allclose(val_ng, val_np)\n\n\ndef test_recvop_tensorupdate():\n \"\"\"\n The tensor (RecvOp_#_#) associated with the following conv op has two views:\n 1) Non-flat view (e.g. RecvOp_#_#_1_1_1_1_4.shape=(1,1,1,1,4))\n 2) Flat view (e.g. RecvOp_#_#_1_4.shape = (1,4))\n This test ensures that inside RecvOp code generation, the generated code\n should make sure both views get updated (e.g. by using update_RecvOp_#_# API)\n In this test, ng.dot operation tends to use the flat view (i.e. RecvOp_#_#_1_4)\n And previously RecvOp with RecvOp_#_#_1_1_1_1_4 = recv_from_send(send_id) failed\n to update both two views (i.e. flat and non-flat view of the same buffer/tensor)\n \"\"\"\n class ConvParams(object):\n\n def __init__(self, C=1, N=1, K=1, D=1, H=1, W=1, T=1, R=1, S=1,\n pad_d=0, pad_h=0, pad_w=0,\n str_d=1, str_h=1, str_w=1):\n\n from ngraph.frontends.common.utils import conv_output_dim\n M = conv_output_dim(D, T, pad_d, str_d)\n P = conv_output_dim(H, R, pad_h, str_h)\n Q = conv_output_dim(W, S, pad_w, str_w)\n\n self.dimO = (K, M, P, Q, N)\n self.dimI = (C, D, H, W, N)\n self.dimF = (C, T, R, S, K)\n\n self.conv_params = dict(\n pad_d=pad_d, pad_h=pad_h, pad_w=pad_w,\n str_d=str_d, str_h=str_h, str_w=str_w,\n dil_d=1, dil_h=1, dil_w=1\n )\n\n self.batch_axis = ng.make_axis(name='N', length=N)\n\n self.ax_i = ng.make_axes([\n ng.make_axis(name='C', length=C),\n ng.make_axis(name='D', length=D),\n ng.make_axis(name='H', length=H),\n ng.make_axis(name='W', length=W),\n self.batch_axis\n ])\n\n self.ax_f = ng.make_axes([\n ng.make_axis(name='C', length=C),\n ng.make_axis(name='D', length=T),\n ng.make_axis(name='H', length=R),\n ng.make_axis(name='W', length=S),\n ng.make_axis(name='K', length=K),\n ])\n\n self.ax_o = ng.make_axes([\n ng.make_axis(name='C', length=K),\n ng.make_axis(name='D', length=M),\n ng.make_axis(name='H', length=P),\n ng.make_axis(name='W', length=Q),\n self.batch_axis\n ])\n\n # Layer 1, using convolutation introduces multi/flatten view of tensors\n cf = ConvParams(C=2, N=4, K=1, H=2, W=2, R=2, S=2)\n\n inputs = ng.placeholder(axes=cf.ax_i)\n filters = ng.placeholder(axes=cf.ax_f)\n\n # randomly initialize\n from ngraph.testing import RandomTensorGenerator\n rng = RandomTensorGenerator(0, np.float32)\n # put value 1 into inputs/filters for conv\n input_value = rng.uniform(1, 1, cf.ax_i)\n filter_value = rng.uniform(1, 1, cf.ax_f)\n\n conv = ng.convolution(cf.conv_params, inputs, filters, axes=cf.ax_o)\n\n # Layer 2, using dot to ensure recv_op.axes == send_op.axes\n from ngraph.frontends.neon import UniformInit\n # put value 1 into weights for dot\n init_uni = UniformInit(1, 1)\n W_A = ng.make_axis(length=2)\n w_axes = ng.make_axes(W_A) + conv.axes.feature_axes()\n w = ng.variable(axes=w_axes, initial_value=init_uni)\n\n with ng.metadata(device_id='1'):\n dot = ng.dot(w, conv)\n\n with ExecutorFactory() as ex:\n dot_comp = ex.executor(dot, filters, inputs)\n dot_val = dot_comp(filter_value, input_value)\n\n np.testing.assert_array_equal(dot_val, [[8., 8., 8., 8.],\n [8., 8., 8., 8.]])\n\n\ndef test_terminate_op():\n\n class TerminateOp(ng.Op):\n\n def __init__(self, **kwargs):\n super(TerminateOp, self).__init__(**kwargs)\n\n @property\n def has_side_effects(self):\n return True\n\n baseline = active_children()\n termOp = TerminateOp()\n assert len(baseline) == 0\n with ExecutorFactory() as ex:\n with pytest.raises(RuntimeError) as excinfo:\n ex.executor(termOp)\n assert 'Cannot find op_type of TerminateOp in any ngraph.op_graph modules' \\\n in str(excinfo.value)\n assert len(active_children()) == 0\n assert len(active_children()) == len(baseline)\n\n\ndef test_process_leak():\n baseline = active_children()\n with ng.metadata(device_id=('0')):\n x = ng.constant(2)\n assert len(active_children()) == 0\n with ExecutorFactory() as ex:\n comp = ex.executor(x)\n assert len(active_children()) == 0\n comp()\n assert len(active_children()) == 0\n assert len(active_children()) == len(baseline)\n\n\nax_A = ng.make_axis(4)\nax_B = ng.make_axis(6)\nax_C = ng.make_axis(12)\nax_D = ng.make_axis(24)\n\n\n@pytest.mark.hetr_gpu_only\n@pytest.mark.parametrize('config', [\n {\n 'axes': ng.make_axes([ax_A]),\n 'device_id': ('0'),\n 'parallel_axis': ax_A,\n },\n {\n 'axes': ng.make_axes([ax_A]),\n 'device_id': ('0', '1'),\n 'parallel_axis': ax_A,\n },\n {\n 'axes': ng.make_axes([ax_A, ax_B]),\n 'device_id': ('0', '1'),\n 'parallel_axis': ax_A,\n },\n {\n 'axes': ng.make_axes([ax_A, ax_B]),\n 'device_id': ('0', '1'),\n 'parallel_axis': ax_B,\n },\n {\n 'axes': ng.make_axes([ax_A, ax_B, ax_C]),\n 'device_id': ('0', '1'),\n 'parallel_axis': ax_A,\n },\n {\n 'axes': ng.make_axes([ax_A, ax_B, ax_C]),\n 'device_id': ('0', '1'),\n 'parallel_axis': ax_B,\n },\n {\n 'axes': ng.make_axes([ax_A, ax_B, ax_C]),\n 'device_id': ('0', '1'),\n 'parallel_axis': ax_C,\n },\n {\n 'axes': ng.make_axes([ax_A, ax_B, ax_C, ax_D]),\n 'device_id': ('0', '1'),\n 'parallel_axis': ax_B,\n },\n {\n 'axes': ng.make_axes([ax_A, ax_B, ax_C, ax_D]),\n 'device_id': ('0', '1', '2'),\n 'parallel_axis': ax_C,\n },\n {\n 'axes': ng.make_axes([ax_A, ax_B, ax_C, ax_D]),\n 'device_id': ('0', '1', '2'),\n 'parallel_axis': ax_D,\n },\n])\ndef test_gpu_graph(config):\n pytest.xfail(\"Multi-GPU testing not enabled yet\")\n\n if 'gpu' not in ngt.transformer_choices():\n pytest.skip('GPUTransformer not available!')\n\n t = config\n with ng.metadata(device='gpu'):\n x = ng.placeholder(axes=t['axes'])\n\n with ng.metadata(device='gpu', device_id=t['device_id'], parallel=t['parallel_axis']):\n x_plus_one = x + 1\n\n with ng.metadata(device='gpu'):\n x_plus_two = x_plus_one + 1\n\n os.environ[\"HETR_SERVER_NUM\"] = str(len(t['device_id']))\n\n np_x = np.random.randint(100, size=t['axes'].full_lengths)\n with closing(ngt.make_transformer_factory('hetr')()) as transformer:\n computation = transformer.computation(x_plus_two, x)\n res = computation(np_x)\n np.testing.assert_array_equal(res, np_x + 2)\n\n\nclass ClosingHetrServers():\n def __init__(self, ports):\n self.tmpfile = tempfile.NamedTemporaryFile(dir=os.path.dirname(os.path.realpath(__file__)),\n delete=True)\n self.processes = []\n for p in ports:\n hetr_server = os.path.dirname(os.path.realpath(__file__)) +\\\n \"/../../ngraph/transformers/hetr/hetr_server.py\"\n command = [\"python\", hetr_server, \"-tf\", self.tmpfile.name, \"-p\", p]\n try:\n proc = subprocess.Popen(command)\n self.processes.append(proc)\n except Exception as e:\n print(e)\n time.sleep(STARTUP_TIME)\n\n def close(self):\n for p in self.processes:\n p.terminate()\n for p in self.processes:\n p.kill()\n for p in self.processes:\n p.wait()\n self.tmpfile.close()\n\n\ndef test_rpc_transformer():\n from ngraph.transformers.hetr.rpc_client import RPCTransformerClient\n rpc_client_list = list()\n port_list = ['50111', '50112']\n num_procs = len(port_list)\n\n with closing(ClosingHetrServers(port_list)):\n for p in range(num_procs):\n rpc_client_list.append(RPCTransformerClient('cpu' + str(p),\n 'localhost:' + port_list[p]))\n np.testing.assert_equal(rpc_client_list[p].is_trans_built, False)\n np.testing.assert_equal(rpc_client_list[p].transformer_type, 'cpu' + str(p))\n np.testing.assert_equal(rpc_client_list[p].server_address, 'localhost:' + port_list[p])\n for p in range(num_procs):\n rpc_client_list[p].build_transformer()\n np.testing.assert_equal(rpc_client_list[p].is_trans_built, True)\n for p in range(num_procs):\n rpc_client_list[p].close_transformer()\n for p in range(num_procs):\n rpc_client_list[p].close()\n np.testing.assert_equal(rpc_client_list[p].is_trans_built, False)\n\n\ndef test_mpilauncher():\n os.environ[\"HETR_SERVER_PORTS\"] = \"51111, 51112\"\n mpilauncher = MPILauncher()\n mpilauncher.launch(2)\n\n # Check if process has launched\n assert mpilauncher.mpirun_proc.poll() is None\n\n mpilauncher.close()\n\n # Check if process has completed\n assert mpilauncher.mpirun_proc is None\n","sub_path":"tests/hetr_tests/test_hetr_integration.py","file_name":"test_hetr_integration.py","file_ext":"py","file_size_in_byte":16853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"565111394","text":"from django.core.management.base import BaseCommand\nfrom django.utils.translation import ugettext as _\n\nimport dsmr_consumption.services\nimport dsmr_stats.services\nfrom dsmr_datalogger.models.reading import DsmrReading\n\n\nclass Command(BaseCommand):\n help = _(\n 'Deletes all aggregated data generated. Such as consumption and (day/hour) statistics. '\n 'This command does NOT affect any readings stored. In fact, you should NEVER run this, unless you still have '\n 'each and EVERY reading stored, as the application will attempt to recalculate all aggregated data deleted '\n 'retroactively, using each reading stored.')\n\n def handle(self, **options):\n print(' - Clearing consumption data')\n dsmr_consumption.services.clear_consumption()\n\n print(' - Clearing statistics')\n dsmr_stats.services.clear_statistics()\n\n print(' - Resetting state of all readings for processing (might take a while)')\n DsmrReading.objects.all().update(processed=False)\n\n self.stdout.write('Command completed.')\n","sub_path":"dsmr_backend/management/commands/dsmr_backend_delete_aggregated_data.py","file_name":"dsmr_backend_delete_aggregated_data.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"434322991","text":"# show lmdb in videos\n# ref link: https://github.com/weiliu89/caffe/issues/190\n\n\nlmdb_file = \"D:/image_datasets/CityScapes/CityScapes2016/lmdb/CityScapes2016_train_lmdb/\"\nlmdb_env = lmdb.open(lmdb_file)\nlmdb_txn = lmdb_env.begin()\nlmdb_cursor = lmdb_txn.cursor()\ndatum = caffe_pb2.AnnotatedDatum()\n\nfourcc = cv2.VideoWriter_fourcc('M','P','E','G')\nwriter = cv2.VideoWriter('D:/dumped_lmdb.avi', fourcc, 30, (2048,1024),isColor=True)\nfor key, value in lmdb_cursor:\n datum.ParseFromString(value)\n data = datum.datum\n grp = datum.annotation_group\n\n arr = np.frombuffer(data.data, dtype='uint8')\n img = cv2.imdecode(arr, cv2.IMREAD_COLOR)\n width = img.shape[1]\n height = img.shape[0]\n for annotation in grp:\n for bbox in annotation.annotation:\n cv2.rectangle(img, (int(bbox.bbox.xmin * width), int(bbox.bbox.ymin*height)), (int(bbox.bbox.xmax*width), int(bbox.bbox.ymax*height)), (0,255,0))\n cv2.imshow('decoded image', img)\n cv2.waitKey(1)\n writer.write(img)\nwriter.release()\n","sub_path":"showlmdb_vid.py","file_name":"showlmdb_vid.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"445692269","text":"import numpy as np\nimport math\nimport os\nimport argparse\nfrom PIL import Image, ImageOps\n\ndef img_to_square(img):\n w, h = img.size\n padding_right = 0\n padding_bottom = 0\n if w % 32 != 0:\n new_w = math.ceil(w /32) * 32\n padding_right = new_w - w\n padding_bottom = new_w - h\n else:\n padding_bottom = w - h\n\n border = (0, 0, padding_right, padding_bottom)\n new_img = ImageOps.expand(img, border=border,fill='black')\n return new_img\n\ndef img_to_32_multiplier(img):\n \n w, h= img.size\n padding_right = 0\n padding_bottom = 0\n if w % 32 != 0:\n new_w = math.ceil(w /32) * 32\n padding_right = new_w - w\n if h % 32 != 0:\n new_h = math.ceil(h /32) * 32\n padding_bottom = new_h - h\n border = (0, 0, padding_right, padding_bottom)\n new_img = ImageOps.expand(img, border=border,fill='black')\n return new_img\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--method', '-m', type=str, default='m32', help='resize method m32/squared')\n parser.add_argument('--src_path', '-sp', type=str, help='folder path to source images')\n parser.add_argument('--output_path', '-op', type=str, default='.', help='folder path to output images')\n opt = parser.parse_args()\n\n if not os.path.isdir(opt.output_path):\n os.mkdir(opt.output_path)\n\n included_extention = ('jpg', 'bmp', 'png', 'gif')\n img_list = [ img for img in os.listdir(opt.src_path) if img.endswith(included_extention)]\n\n for img_name in img_list:\n img = Image.open(os.path.join(opt.src_path, img_name))\n if opt.method == \"m32\":\n new_path = os.path.join(opt.output_path,img_name.split(\".\")[0] + \"_m32.jpg\")\n new_img = img_to_32_multiplier(img)\n new_img.save(new_path)\n print(\"Save images to {}\".format(new_path))\n else:\n new_path = os.path.join(opt.output_path,img_name.split(\".\")[0] + \"_squared.jpg\")\n new_img = img_to_square(img)\n new_img.save(new_path)\n print(\"Save images to {}\".format(new_path))\n","sub_path":"misc/resize.py","file_name":"resize.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"457948252","text":"import RPi.GPIO as GPIO \r\nfrom gpiozero import Motor\r\nimport time\r\n\r\n#set the GPIO pins of raspberry pi.\r\nGPIO.setmode (GPIO.BCM)\r\nGPIO.setwarnings (False)\r\n#enable\r\nGPIO.setup(16, GPIO.OUT)\r\nGPIO.setup(20, GPIO.OUT)\r\n#setting the GPIO pin as Output\r\nGPIO.setup (24, GPIO.OUT)\r\nGPIO.setup (23, GPIO.OUT)\r\nGPIO.setup (27, GPIO.OUT)\r\nGPIO.setup (22, GPIO.OUT)\r\n#GPIO.PWM( pin, frequency ) it generates software PWM\r\nPWMR = GPIO.PWM (24, 100)\r\nPWMR1 = GPIO.PWM (23, 100)\r\nPWML = GPIO.PWM (27, 100)\r\nPWML1 = GPIO.PWM (22, 100)\r\n#Starts PWM at 0% dutycycle\r\nPWMR.start (0)\r\nPWMR1.start (0)\r\nPWML.start (0)\r\nPWML1.start (0)\r\n#enable pins of the motor\r\nGPIO.output(16, GPIO.HIGH)\r\nGPIO.output(20, GPIO.HIGH)\r\n\r\nmotor1 = Motor(24, 23)\r\nmotor2 = Motor(27, 22)\r\n\r\n\r\n#GPIO Mode (BOARD / BCM)\r\nGPIO.setmode(GPIO.BCM)\r\n \r\n#set GPIO Pins\r\nGPIO_TRIGGER = 18\r\nGPIO_ECHO = 25\r\n \r\n#set GPIO direction (IN / OUT)\r\nGPIO.setup(GPIO_TRIGGER, GPIO.OUT)\r\nGPIO.setup(GPIO_ECHO, GPIO.IN)\r\n\r\n\r\n\r\n\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\ndef distance():\r\n # set Trigger to HIGH\r\n GPIO.output(GPIO_TRIGGER, True)\r\n \r\n # set Trigger after 0.01ms to LOW\r\n time.sleep(0.00001)\r\n GPIO.output(GPIO_TRIGGER, False)\r\n \r\n StartTime = time.time()\r\n StopTime = time.time()\r\n \r\n # save StartTime\r\n while GPIO.input(GPIO_ECHO) == 0:\r\n StartTime = time.time()\r\n \r\n # save time of arrival\r\n while GPIO.input(GPIO_ECHO) == 1:\r\n StopTime = time.time()\r\n \r\n # time difference between start and arrival\r\n TimeElapsed = StopTime - StartTime\r\n # multiply with the sonic speed (34300 cm/s)\r\n # and divide by 2, because there and back\r\n distance = (TimeElapsed * 34300) / 2\r\n \r\n return distance\r\n\r\n\r\ncapture = cv2.VideoCapture(0) #read the video\r\ncapture.set(3,320.0) #set the size\r\ncapture.set(4,240.0) #set the size\r\ncapture.set(5,15) #set the frame rate\r\n\r\nfor i in range(0,2):\r\n flag, trash = capture.read() #starting unwanted null value\r\n\r\nwhile cv2.waitKey(1) != 27:\r\n dist = distance()\r\n frame=capture.g\r\n \r\n flag, frame = capture.read() #read the video in frames\r\n \r\n lower = [0, 0, 0]\r\n upper = [70, 70, 70]\r\n \r\n lower_red = [17, 15, 100]\r\n upper_red = [50, 56, 200]\r\n\r\n # create NumPy arrays from the boundaries\r\n lower = np.array(lower, dtype=\"uint8\")\r\n upper = np.array(upper, dtype=\"uint8\")\r\n lower_red = np.array(lower_red, dtype=\"uint8\")\r\n upper_red = np.array(upper_red, dtype=\"uint8\")\r\n\r\n # find the colors within the specified boundaries and apply\r\n # the mask\r\n mask = cv2.inRange(frame, lower, upper)\r\n mask_red = cv2.inRange(frame, lower_red, upper_red)\r\n output = cv2.bitwise_and(frame, frame, mask=mask)\r\n\r\n ret, th1 = cv2.threshold(mask, 40, 255, 0)\r\n ret, th2 = cv2.threshold(mask_red, 40, 255, 0)\r\n _, contours, hierarchy = cv2.findContours(th1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\r\n _, contours_red, hierarchy = cv2.findContours(th2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\r\n for cnt_red in contours_red:\r\n if cnt_red is None:\r\n break\r\n if cnt_red is not None:\r\n area = cv2.contourArea(cnt_red)# find the area of contour\r\n if area>=300 :\r\n cv2.drawContours(frame, cnt_red, -1, (255, 0, 0), 3)\r\n cv2.imshow('frame', frame)\r\n M = cv2.moments(cnt_red)\r\n cx = int(M['m10']/M['m00'])\r\n cy = int(M['m01']/M['m00'])\r\n if cx>130 and cx<190:\r\n print(\"Destination Reached- Put U Turn\")\r\n motor2.forward(0.9)\r\n motor1.backward(0.9)\r\n time.sleep(1.2)\r\n \r\n for cnt in contours:\r\n #if cnt is None:\r\n #break\r\n if cnt is not None:\r\n area = cv2.contourArea(cnt)# find the area of contour\r\n if area>=1000 :\r\n cv2.drawContours(frame, cnt, -1, (0, 255, 0), 3)\r\n cv2.imshow('frame', frame) # show video\r\n # find moment and centroid\r\n M = cv2.moments(cnt)\r\n cx = int(M['m10']/M['m00'])\r\n\r\n cy = int(M['m01']/M['m00'])\r\n \r\n if dist <= 15:\r\n print (\"Stop\")\r\n print (\"Measured Distance = %.1f cm\" % dist)\r\n motor1.forward(0)\r\n motor2.forward(0)\r\n time.sleep(0.08)\r\n \r\n elif cx<=145:\r\n print(\"left\")\r\n #l=(cx*100/160)\r\n motor1.forward(0.3)\r\n motor2.backward(0.25)\r\n time.sleep(.03)\r\n \r\n elif cx>=175 and cx<190:\r\n print(\"right\")\r\n #r=((320-cx)*100/160)\r\n motor2.forward(0.3)\r\n motor1.backward(0.25)\r\n time.sleep(.03)\r\n \r\n elif cx>=190 :\r\n print(\"right Turn\")\r\n motor1.forward(0)\r\n motor2.forward(0)\r\n time.sleep(0.08)\r\n motor2.forward(0.5)\r\n motor1.forward(0.5)\r\n time.sleep(3.75)\r\n motor2.forward(0.5)\r\n motor1.backward(0.5)\r\n time.sleep(3.1)\r\n \r\n \r\n \r\n elif cx>145 and cx<175:\r\n print(\"straight\")\r\n motor1.forward(0.5)\r\n motor2.forward(0.5)\r\n time.sleep(0.1)\r\n \r\n else:\r\n motor1.forward(0.5)\r\n motor2.forward(0.5)\r\n time.sleep(.08)\r\n \r\n \r\n \r\n motor1.stop()\r\n motor2.stop()\r\n key = cv2.waitKey(1) & 0xFF\r\n if key == ord(\"q\"):\r\n break\r\n","sub_path":"Algorithm/Segment and Road Follow/RPi_LineFollow.py","file_name":"RPi_LineFollow.py","file_ext":"py","file_size_in_byte":5894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"597062884","text":"# -*- coding: utf-8 -*-\n##########################################################################\n# Copyright (C) 2005-2013 UC Mobile Limited. All Rights Reserved\n# File : uc_tools.fileutils\n# \n# Creation : 2013-10-31\n# Author : huangjj@ucweb.com\n###########################################################################\n\nimport os\nimport stat\nimport errors\nimport shutil\nimport zipfile\n \n\"\"\"\n封装了常用的目录或者文件的创建、删除、复制、移动、压缩、解压的方法\n\"\"\"\n\ndef delete(path):\n \"\"\" 删除目录或者文件\n\n :param path: 需要删除的目录或者文件的路径\n :type path: string\n\n :raise error.MsgException: 当文件夹不存在的时候,抛出该异常\n \"\"\"\n exist = os.path.exists(path)\n if not exist:\n raise errors.MsgException(\"<%s> is not exists!\")\n \n if os.path.isfile(path):\n try:\n os.remove(path)\n except:\n pass\n elif os.path.isdir(path):\n for item in os.listdir(path):\n itemsrc=os.path.join(path,item)\n delete(itemsrc) \n try:\n os.rmdir(path)\n except:\n pass\n \ndef createFolder(path):\n \"\"\" 创建文件夹,例如我想在 ``/home/uc/`` 目录下创建一个 ``tech`` 目录,则传入 ``path=\"/home/uc/tech\"`` 即可\n 如果文件夹本身就存在,则不再去重新创建。\n\n :param path: 需要创建的文件夹的路径\n :type path: string\n \"\"\"\n ex = os.path.exists(path)\n\n if(not ex):\n os.makedirs(path)\n \ndef createFile(path, content=\"\",mode=\"w\"):\n \"\"\" 创建文件\n\n :param path: 文件的路径,具体到该文件的名字\n :type path: string\n\n :param content: 如果 ``mode`` 不是只读,将会把content的内容写进去\n :type content: string\n\n :param mode: 文件创建的模式\n :type mode: string\n \"\"\"\n ex = os.path.exists(path)\n\n if(not ex):\n f=open(path, mode)\n if mode != \"r\":\n f.write(content)\n f.close()\n \ndef copy(src, dst):\n \"\"\" 复制文件\n\n :param src: 需要复制的文件路径\n :type src: string\n\n :param dst: 需要将文件复制到的指定目录的路径\n :type dst: string\n\n :raise errors.MsgException: 文件复制失败\n \"\"\"\n if os.path.isdir(src):\n names = os.listdir(src)\n elif os.path.isfile(src):\n shutil.copy2(src, dst)\n return\n\n if not os.path.exists(dst):\n os.mkdir(dst)\n for name in names:\n srcname = os.path.join(src, name)\n dstname = os.path.join(dst, name)\n try:\n if os.path.isdir(srcname): \n copy(srcname, dstname)\n else:\n if (not os.path.exists(dstname)\n or ((os.path.exists(dstname))\n and (os.path.getsize(dstname) != os.path.getsize(srcname)))):\n# print dstname\n shutil.copy2(srcname, dst)\n except:\n raise errors.MsgException(\"folder and file copy failure\")\n\ndef extract(zip_file_name, unzip_to_dir):\n \"\"\" 解压文件\n\n :param zip_file_name: 需要解压的文件的路径\n :type zip_file_name: string\n\n :param unzip_to_dir: 存放解压文件的路径\n :type unzip_to_dir: string\n\n .. note:: 当前仅支持解压zip格式的压缩包\n \"\"\"\n f_zip = zipfile.ZipFile(zip_file_name, 'r')\n\n # extra all file to the unzip_to_dir\n f_zip.extractall(unzip_to_dir)\n f_zip.close()\n # extra each file to the unzip_to_dir\n # for f in f_zip.namelist():\n # f_zip.extract(f, unzip_to_dir)\n \ndef compress(path, zip_file_name):\n \"\"\" 压缩文件为zip格式\n\n .. warning:: 该目录下的子文件夹的名字不能跟当前文件夹的名字一样\n\n :param path: 需要压缩的文件或者目录的路径\n :type path: string\n\n :param zip_file_name: 压缩后的文件的名字\n :type zip_file_name: string\n \"\"\"\n zip_file = zip_file_name.split(os.sep)\n zip_file = zip_file[len(zip_file) - 1]\n # print zip_file\n if not os.path.exists(path): \n raise errors.MsgException(\"function compress:not exists file or dir(%s)\" % (path)) \n \n f = zipfile.ZipFile(zip_file_name,'w',zipfile.ZIP_DEFLATED)\n \n if os.path.isfile(path):\n f.write(path,os.path.split(path)[1])\n elif os.path.isdir(path):\n startdir = path\n for dirpath, dirnames, filenames in os.walk(startdir):\n for filename in filenames:\n abs_path = os.path.join(os.path.join(dirpath, filename))\n rel_path = os.path.relpath(abs_path, os.path.dirname(startdir))\n f.write(os.path.join(dirpath,filename), rel_path)\n f.close()\n\n if os.path.exists(zip_file_name):\n os.chmod(zip_file_name, stat.S_IRWXU|stat.S_IRGRP|stat.S_IROTH) # mode:744)\n\ndef getUCToolsLocation():\n \"\"\" 获取基类所在的路径\n\n :returns: 基类所在的父文件夹\n :rtype: string\n \"\"\"\n path = os.path.split(os.path.realpath(__file__))[0]\n path = os.path.join(path,os.path.pardir)\n path = os.path.abspath(path)\n return path\n\n# def createPath(path, folders):\n# \"\"\" 进行路径的拼接\n\n# :param path: 需要拼接的路径\n# :type path: string\n\n# :param folders: 文件路径字典\n# :type folders: list\n\n# :returns: 拼接后的字符串路径\n# :rtype: string\n# \"\"\"\n# for folder in folders:\n# path = os.path.join(path, folder)\n # return path\n\ndef createPath(folders):\n \"\"\" 进行路径的拼接\n\n :param folders: 文件路径字典\n :type folders: list\n\n :returns: 拼接后的字符串路径\n :rtype: string\n \"\"\"\n if not len(folders):\n return \"\"\n\n path = folders[0]\n\n for i in range(1, len(folders)):\n path = os.path.join(path, folders[i])\n return path\n ","sub_path":"uc_tools/fileutils.py","file_name":"fileutils.py","file_ext":"py","file_size_in_byte":5909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"240839036","text":"from typing import List\n\n\nclass Solution:\n def findErrorNums(self, nums: List[int]) -> List[int]:\n from collections import Counter\n c = Counter(nums)\n\n n = len(nums)\n ret = [0, 0]\n for i in range(1, n + 1):\n if i in c and c[i] == 2:\n ret[0] = i\n elif not i in c:\n ret[1] = i\n\n return ret\n\n\nif __name__ == '__main__':\n s = Solution()\n nums = [1, 2, 2, 4]\n print(s.findErrorNums(nums))\n","sub_path":"leetcode/easy/set-mismatch.py","file_name":"set-mismatch.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"526869949","text":"import pygame\nimport random\nimport numpy\n\nscreenWidth = 1200\nscreenHeight = 800\nclock = pygame.time.Clock()\nlength = 21\n\n\nclass Toothpick:\n def __init__(self, center_x, center_y, dir):\n self.x = center_x\n self.y = center_y\n self.dir = dir\n self.new = True\n if self.dir == 1:\n self.ax, self.ay = self.x - (length / 2), self.y\n self.bx, self.by = self.x + (length / 2), self.y\n else:\n self.ax, self.ay = self.x, self.y - (length / 2)\n self.bx, self.by = self.x, self.y + (length / 2)\n\n def draw(self, win):\n if self.new:\n pygame.draw.line(win, (0, 0, 255),\n (self.ax, self.ay),\n (self.bx, self.by), 4)\n else:\n pygame.draw.line(win, (0, 0, 0),\n (self.ax, self.ay),\n (self.bx, self.by), 1)\n\n def intersects(self, x, y):\n if self.ax == x and self.ay == y:\n return True\n elif self.bx == x and self.by == y:\n return True\n else:\n return False\n\n def createA(self, arr):\n available = True\n for pick in arr:\n if pick != self and pick.intersects(self.ax, self.ay):\n available = False\n if available:\n return Toothpick(self.ax,self.ay,self.dir*-1)\n\n def createB(self, arr):\n available = True\n for pick in arr:\n if pick != self and pick.intersects(self.bx, self.by):\n available = False\n if available:\n return Toothpick(self.bx,self.by,self.dir*-1)\n\n\nclass Display:\n def __init__(self):\n pygame.init()\n self.win = pygame.display.set_mode((screenWidth, screenHeight))\n self.clock = pygame.time.Clock()\n pygame.display.set_caption(\"Toothpickanimation\")\n self.stop = False\n self.picks = []\n t = Toothpick(screenWidth / 2, screenHeight / 2, 1)\n self.picks.append(t)\n\n def drawWindow(self):\n for i in self.picks:\n i.draw(self.win)\n\n def run(self):\n\n while not self.stop:\n nextpicks = []\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.stop = True\n self.win.fill((255, 255, 255))\n\n # keys = pygame.key.get_pressed()\n # if keys[pygame.K_SPACE]:\n for pick in self.picks:\n if pick.new:\n A = pick.createA(self.picks)\n B = pick.createB(self.picks)\n if A is not None:\n nextpicks.append(A)\n if B is not None:\n nextpicks.append(B)\n pick.new = False\n self.picks += nextpicks\n\n self.drawWindow()\n\n pygame.display.update()\n\n\nprogram = Display()\nprogram.run()\n","sub_path":"toothpickpattern.py","file_name":"toothpickpattern.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"310800941","text":"class Solution:\n def topKFrequent(self, nums, K):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n freq = {}\n for num in nums:\n try:\n freq[num] += 1\n except KeyError:\n freq[num] = 1\n \n heap = []\n for k, v in freq.items():\n heapq.heappush(heap, (-v, k))\n \n sol = [k for v, k in heapq.nsmallest(K, heap)]\n return sol\n","sub_path":"347. Top K Frequent Elements/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"410315997","text":"import pygame\npygame.init()\nsize = (800, 600)\nscreen = pygame.display.set_mode(size)\ngameon = True\nwhile gameon:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n gameon = False\n print(pygame.time.get_ticks()/1000)\n pygame.display.update()","sub_path":"c3.py","file_name":"c3.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"376261247","text":"a = 5\nb = 5\nif a>b:\n print(\"this is false\")\nelif a[\\w-]+)$', PostDetailAPIView.as_view(),\n name='PostDetailAPIView' ),\n url(r'^/(?P[\\w-]+)/like/add$', like_create_api,\n name='like_create_api'),\n url(r'^/(?P[\\w-]+)/like/delete$', like_delete_api,\n name='like_delete_api'),\n url(r'^/(?P[\\w-]+)/report$', ReportCreateAPIView.as_view(),\n name='ReportCreateAPIView'),\n]\n","sub_path":"ShelfiePost/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"317264767","text":"#coding=utf8\nimport hashlib\nimport os\n\n\ndef md5_for_file(orig_data):\n md5 = hashlib.md5()\n block_size=2**20\n f = open(orig_data, 'rb')\n while True:\n data = f.read(block_size)\n if not data:\n break\n md5.update(data)\n f.close()\n return md5.hexdigest()\n\n\ndef md5_for_str(s):\n md5 = hashlib.md5()\n md5.update(s.encode('utf-8'))\n return md5.hexdigest()\n\n\ndef md5sum_of_path(paths, extensions = None):\n \"\"\"计算指定路径下所有文件的 文件名和内容的md5sum\n\n 只有所有文件的内容和文件名都一致时, 得出的md5才会相同\n \"\"\"\n if type(paths) == str or type(paths) is str:\n paths = [paths]\n md5_str = \"\"\n img_list = []\n for fORd in paths:\n if not os.path.exists(fORd):\n # raise Exception(fORd + \" not exist\") \n print((\"md5sum_of_path path not exist: \"+fORd))\n\n if os.path.isfile(fORd):\n img_list.append(fORd)\n else:\n for rt, dirs, files in os.walk(fORd):\n for f in files:\n suffix = os.path.splitext(f)[1]\n if extensions == None or suffix in extensions:\n img_list.append(os.path.join(rt,f))\n\n if len(img_list) == 0:\n return None\n\n img_list.sort()\n for img in img_list:\n md5_str += os.path.basename(img)\n md5_str += md5_for_file(img)\n return md5_for_str(md5_str)\n\ndef md5sum_of_dir(dir_path,extensions=None):\n \"\"\"\n 计算指定目录下(不包括子目录)的文件名和内容的md5\n 用于资源处理时标记目录是否发生改变\n \"\"\"\n md5_str=\"\"\n file_list = []\n if not os.path.exists(dir_path):\n print((\"dir_path not exists \"+dir_path))\n if not os.path.isdir(dir_path):\n print((\"dir_path is not dir \"+dir_path))\n list_dir = os.listdir(dir_path)\n for item in list_dir:\n path = os.path.join(dir_path,item) \n if os.path.isfile(path):\n ext = os.path.splitext(path)[1]\n if extensions==None or ext in extensions:\n file_list.append(path)\n if len(file_list) == 0:\n print((\"no file in \"+dir_path))\n file_list.sort()\n for file_path in file_list:\n md5_str += os.path.basename(file_path)\n md5_str += md5_for_file(file_path)\n return md5_for_str(md5_str)\n pass\n\ndef uni_id_for_res(config,action):\n res_cfg_id = md5_for_str(action+str(config['options']))\n input_dir_list = config.get('input-dir')\n input_dir_root = config.get('inputroot')\n res_input_id = \"\"\n for rel_input_dir in input_dir_list:\n input_dir_path = os.path.join(input_dir_root,rel_input_dir)\n res_input_id += rel_input_dir\n res_input_id += md5sum_of_dir(input_dir_path) \n output_id = md5_for_str(res_cfg_id+res_input_id)\n return output_id\n\n\ndef md5sum_of_IOpath(input_file_list,options,paths, extensions = None):\n \"\"\"\n 加入输入文件列表的文件名一起计算,这样输入或输出资源发生变动时都能反应在md5值上\n \"\"\"\n if type(paths) == str:\n paths = [paths]\n md5_str = \"\"\n img_list = []\n for fORd in paths:\n if not os.path.exists(fORd):\n if os.path.isfile(fORd):\n img_list.append(fORd)\n else:\n for rt, dirs, files in os.walk(fORd):\n for f in files:\n suffix = os.path.splitext(f)[1]\n if extensions == None or suffix in extensions:\n img_list.append(os.path.join(rt,f))\n\n if len(img_list) == 0:\n md5_str = \"nooutput\"\n if input_file_list:\n for img_path in input_file_list:\n md5_str+= md5_for_file(img_path)\n else:\n img_list.sort()\n for img in img_list:\n md5_str += os.path.basename(img)\n md5_str += md5_for_file(img)\n if input_file_list:\n for img_path in input_file_list:\n md5_str += md5_for_file(img_path)\n md5_str += str(options)\n return md5_for_str(md5_str)\n\nif __name__ == '__main__':\n print((md5sum_of_path('/data/work/walle/kof/asset/Assets/anim/UI特效/p爬塔/F波动画',['.png'])))\n print((md5sum_of_path('/data/work/walle/kof/asset/Assets/anim/UI特效/p爬塔/F波动画',['.plist'])))\n print((md5sum_of_path('/data/work/walle/kof/asset/Assets/anim/UI特效/p爬塔/F波动画')))\n\n","sub_path":"rtool/pcutils/md5sum_of_path.py","file_name":"md5sum_of_path.py","file_ext":"py","file_size_in_byte":4484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"498802792","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\eve\\client\\script\\ui\\services\\eveDevice.py\nimport uicontrols\nimport blue\nimport trinity\nfrom trinity import _singletons\nfrom carbonui.services.device import DeviceMgr\nimport localization\nimport uthread\nimport evegraphics.settings as gfxsettings\nNVIDIA_VENDORID = 4318\n\nclass EveDeviceMgr(DeviceMgr):\n __guid__ = 'svc.eveDevice'\n __replaceservice__ = 'device'\n\n def AppRun(self):\n if not settings.public.generic.Get('resourceUnloading', 1):\n trinity.SetEveSpaceObjectResourceUnloadingEnabled(0)\n self.defaultPresentationInterval = trinity.PRESENT_INTERVAL.ONE\n gfx = gfxsettings.GraphicsSettings.GetGlobal()\n gfx.InitializeSettingsGroup(gfxsettings.SETTINGS_GROUP_DEVICE, settings.public.device)\n if gfxsettings.Get(gfxsettings.GFX_INTERIOR_SHADER_QUALITY) != 0:\n trinity.AddGlobalSituationFlags(['OPT_INTERIOR_SM_HIGH'])\n else:\n trinity.RemoveGlobalSituationFlags(['OPT_INTERIOR_SM_HIGH'])\n blue.classes.maxPendingDeletes = 20000\n blue.classes.maxTimeForPendingDeletes = 4.0\n blue.classes.pendingDeletesEnabled = True\n self.deviceCreated = False\n if blue.sysinfo.isTransgaming:\n self.cider = sm.GetService('cider')\n self.ciderFullscreenLast = False\n self.ciderFullscreenBackup = False\n\n def Initialize(self):\n DeviceMgr.Initialize(self)\n self.msaaTypes = {}\n gfxsettings.ValidateSettings()\n aaQuality = gfxsettings.Get(gfxsettings.GFX_ANTI_ALIASING)\n msaaQuality = gfxsettings.GetMSAAQuality(aaQuality)\n msaaType = self.GetMSAATypeFromQuality(aaQuality)\n if msaaQuality > 0 and msaaType == 0:\n gfxsettings.Set(gfxsettings.GFX_ANTI_ALIASING, gfxsettings.AA_QUALITY_DISABLED, pending=False)\n brightness = gfxsettings.Get(gfxsettings.GFX_BRIGHTNESS)\n trinity.settings.SetValue('eveSpaceSceneGammaBrightness', brightness)\n\n def CreateDevice(self):\n DeviceMgr.CreateDevice(self)\n if blue.sysinfo.isTransgaming:\n tgToggleEventHandler = blue.BlueEventToPython()\n tgToggleEventHandler.handler = self.ToggleWindowedTransGaming\n trinity.app.tgToggleEventListener = tgToggleEventHandler\n\n def GetMSAATypeFromQuality(self, quality):\n key = self.GetMSAAQualityFromAAQuality(quality)\n return self.msaaTypes.get(key, 0)\n\n def GetMSAAQualityFromAAQuality(self, quality):\n if quality == 0:\n return 0\n if len(self.msaaTypes) < 1:\n set = self.GetSettings()\n formats = [(set.BackBufferFormat, True), (set.AutoDepthStencilFormat, False), (trinity.PIXEL_FORMAT.R16G16B16A16_FLOAT, True)]\n self.RefreshSupportedAATypes(set, formats)\n if quality not in self.aaTypes:\n quality = gfxsettings.AA_QUALITY_DISABLED\n return gfxsettings.GetMSAAQuality(quality)\n\n def GetShaderModel(self, val):\n if val == 3:\n if not trinity.renderJobUtils.DeviceSupportsIntZ():\n return 'SM_3_0_HI'\n else:\n return 'SM_3_0_DEPTH'\n elif val == 2:\n return 'SM_3_0_HI'\n return 'SM_3_0_LO'\n\n def GetWindowModes(self):\n self.LogInfo('GetWindowModes')\n adapter = self.CurrentAdapter()\n if adapter.format not in self.validFormats:\n return [(localization.GetByLabel('/Carbon/UI/Service/Device/FullScreen'), 0)]\n elif blue.sysinfo.isTransgaming:\n return [(localization.GetByLabel('/Carbon/UI/Service/Device/WindowMode'), 1),\n (localization.GetByLabel('/Carbon/UI/Service/Device/FullScreen'),\n 0)]\n else:\n return [(localization.GetByLabel('/Carbon/UI/Service/Device/WindowMode'), 1), (localization.GetByLabel('/Carbon/UI/Service/Device/FullScreen'), 0), (localization.GetByLabel('/Carbon/UI/Service/Device/FixedWindowMode'), 2)]\n\n def GetAppShaderModel(self):\n shaderQuality = gfxsettings.Get(gfxsettings.GFX_SHADER_QUALITY)\n return self.GetShaderModel(shaderQuality)\n\n def GetAppSettings(self):\n appSettings = {}\n lodQuality = gfxsettings.Get(gfxsettings.GFX_LOD_QUALITY)\n if lodQuality == 1:\n appSettings = {'eveSpaceSceneVisibilityThreshold': 15.0,'eveSpaceSceneLowDetailThreshold': 140.0,'eveSpaceSceneMediumDetailThreshold': 480.0}\n elif lodQuality == 2:\n appSettings = {'eveSpaceSceneVisibilityThreshold': 6,'eveSpaceSceneLowDetailThreshold': 70,'eveSpaceSceneMediumDetailThreshold': 240}\n elif lodQuality == 3:\n appSettings = {'eveSpaceSceneVisibilityThreshold': 3.0,'eveSpaceSceneLowDetailThreshold': 35.0,'eveSpaceSceneMediumDetailThreshold': 120.0}\n return appSettings\n\n def GetAppMipLevelSkipExclusionDirectories(self):\n return [\n 'res:/Texture/IntroScene', 'res:/UI/Texture']\n\n def IsWindowed(self, settings=None):\n if settings is None:\n settings = self.GetSettings()\n if blue.sysinfo.isTransgaming:\n return not self.cider.GetFullscreen()\n else:\n return settings.Windowed\n\n def SetToSafeMode(self):\n gfxsettings.Set(gfxsettings.GFX_TEXTURE_QUALITY, 2, pending=False)\n gfxsettings.Set(gfxsettings.GFX_SHADER_QUALITY, 1, pending=False)\n gfxsettings.Set(gfxsettings.GFX_HDR_ENABLED, False, pending=False)\n gfxsettings.Set(gfxsettings.GFX_POST_PROCESSING_QUALITY, 0, pending=False)\n gfxsettings.Set(gfxsettings.GFX_SHADOW_QUALITY, 0, pending=False)\n gfxsettings.Set(gfxsettings.MISC_RESOURCE_CACHE_ENABLED, 0, pending=False)\n\n def SetDeviceCiderStartup(self, *args, **kwds):\n devSettings = args[0]\n settingsCopy = devSettings.copy()\n devSettings.BackBufferWidth, devSettings.BackBufferHeight = self.GetPreferedResolution(False)\n self.cider.SetFullscreen(True)\n DeviceMgr.SetDevice(self, devSettings, **kwds)\n self.cider.SetFullscreen(False)\n self.ciderFullscreenLast = False\n DeviceMgr.SetDevice(self, settingsCopy, **kwds)\n\n def SetDeviceCiderFullscreen(self, *args, **kwds):\n DeviceMgr.SetDevice(self, *args, **kwds)\n self.cider.SetFullscreen(True)\n\n def SetDeviceCiderWindowed(self, *args, **kwds):\n self.cider.SetFullscreen(False)\n DeviceMgr.SetDevice(self, *args, **kwds)\n\n def SetDevice(self, *args, **kwds):\n if blue.sysinfo.isTransgaming:\n ciderFullscreen = self.cider.GetFullscreen()\n self.ciderFullscreenLast = self.cider.GetFullscreen(apiCheck=True)\n if not self.deviceCreated and not ciderFullscreen:\n self.SetDeviceCiderStartup(*args, **kwds)\n elif ciderFullscreen:\n self.SetDeviceCiderFullscreen(*args, **kwds)\n else:\n self.SetDeviceCiderWindowed(*args, **kwds)\n self.deviceCreated = True\n return True\n else:\n return DeviceMgr.SetDevice(self, *args, **kwds)\n\n def BackupSettings(self):\n DeviceMgr.BackupSettings(self)\n if blue.sysinfo.isTransgaming:\n self.ciderFullscreenBackup = self.ciderFullscreenLast\n\n def DiscardChanges(self, *args):\n if self.settingsBackup:\n if blue.sysinfo.isTransgaming:\n self.cider.SetFullscreen(self.ciderFullscreenBackup, setAPI=False)\n self.SetDevice(self.settingsBackup)\n\n def ToggleWindowedTransGaming(self, *args):\n self.LogInfo('ToggleWindowedTransGaming')\n windowed = not self.cider.GetFullscreen(apiCheck=True)\n self.cider.SetFullscreen(not windowed)\n if windowed:\n wr = trinity.app.GetWindowRect()\n self.preFullScreenPosition = (wr.left, wr.top)\n devSettings = self.GetSettings()\n devSettings.BackBufferWidth, devSettings.BackBufferHeight = self.GetPreferedResolution(windowed)\n uthread.new(self.SetDevice, devSettings, hideTitle=True)\n\n def RefreshSupportedAATypes(self, deviceSettings=None, formats=None, shaderModel=None):\n self.msaaTypes = {gfxsettings.AA_QUALITY_DISABLED: 0}\n self.aaTypes = [gfxsettings.AA_QUALITY_DISABLED]\n\n def Supported(msType):\n supported = True\n for format in formats:\n if format[1]:\n qualityLevels = trinity.adapters.GetRenderTargetMsaaSupport(deviceSettings.Adapter, format[0], deviceSettings.Windowed, msType)\n else:\n qualityLevels = trinity.adapters.GetDepthStencilMsaaSupport(deviceSettings.Adapter, format[0], deviceSettings.Windowed, msType)\n supported = supported and qualityLevels\n\n return supported\n\n if Supported(2):\n self.aaTypes.append(gfxsettings.AA_QUALITY_MSAA_LOW)\n self.msaaTypes[gfxsettings.AA_QUALITY_MSAA_LOW] = 2\n if Supported(4):\n self.aaTypes.append(gfxsettings.AA_QUALITY_MSAA_MEDIUM)\n self.msaaTypes[gfxsettings.AA_QUALITY_MSAA_MEDIUM] = 4\n if shaderModel is None:\n shaderModel = gfxsettings.GetPendingOrCurrent(gfxsettings.GFX_SHADER_QUALITY)\n if _singletons.platform == 'dx11' and shaderModel == gfxsettings.SHADER_MODEL_HIGH:\n self.aaTypes.append(gfxsettings.AA_QUALITY_TAA_HIGH)\n for each in self.aaTypes:\n if each in gfxsettings.AA_TO_MSAA and gfxsettings.AA_TO_MSAA[each] in self.msaaTypes:\n self.msaaTypes[each] = self.msaaTypes[gfxsettings.AA_TO_MSAA[each]]\n\n return\n\n def GetAntiAliasingLabel(self, aaQuality):\n aaLabels = {gfxsettings.AA_QUALITY_DISABLED: localization.GetByLabel('/Carbon/UI/Common/Disabled'),gfxsettings.AA_QUALITY_MSAA_LOW: localization.GetByLabel('UI/SystemMenu/DisplayAndGraphics/Common/LowQuality'),gfxsettings.AA_QUALITY_MSAA_MEDIUM: localization.GetByLabel('UI/SystemMenu/DisplayAndGraphics/Common/MediumQuality'),gfxsettings.AA_QUALITY_TAA_HIGH: localization.GetByLabel('UI/SystemMenu/DisplayAndGraphics/Common/HighQuality')}\n return aaLabels[aaQuality]\n\n def GetAntiAliasingOptions(self, deviceSettings=None, formats=None, shaderModel=None):\n if deviceSettings is None:\n deviceSettings = self.GetSettings()\n if formats is None:\n formats = [(deviceSettings.BackBufferFormat, True), (deviceSettings.AutoDepthStencilFormat, False)]\n self.RefreshSupportedAATypes(deviceSettings, formats, shaderModel)\n aaOptions = []\n for each in self.aaTypes:\n aaOptions.append((self.GetAntiAliasingLabel(each), each))\n\n return aaOptions\n\n def EnforceDeviceSettings(self, devSettings):\n devSettings.BackBufferFormat = self.GetBackbufferFormats()[0]\n devSettings.AutoDepthStencilFormat = self.GetStencilFormats()[0]\n devSettings.MultiSampleType = 0\n devSettings.MultiSampleQuality = 0\n return devSettings\n\n def GetAdapterResolutionsAndRefreshRates(self, set=None):\n options, resoptions = DeviceMgr.GetAdapterResolutionsAndRefreshRates(self, set)\n if set.Windowed:\n maxWidth = trinity.app.GetVirtualScreenWidth()\n maxHeight = trinity.app.GetVirtualScreenHeight()\n maxLabel = localization.GetByLabel('/Carbon/UI/Service/Device/ScreenSize', width=maxWidth, height=maxHeight)\n maxOp = (maxLabel, (maxWidth, maxHeight))\n if maxOp not in options:\n options.append(maxOp)\n elif blue.sysinfo.isTransgaming and self.IsWindowed(set):\n width = trinity.app.GetVirtualScreenWidth()\n height = trinity.app.GetVirtualScreenHeight() - 44\n if height < trinity.app.minimumHeight:\n height = trinity.app.minimumHeight\n label = localization.GetByLabel('/Carbon/UI/Service/Device/ScreenSize', width=width, height=height)\n op = (label, (width, height))\n if op not in options:\n options.append(op)\n width = width / 2\n if width < trinity.app.minimumWidth:\n width = trinity.app.minimumWidth\n label = localization.GetByLabel('/Carbon/UI/Service/Device/ScreenSize', width=width, height=height)\n op = (label, (width, height))\n if op not in options:\n options.append(op)\n return (options, resoptions)\n\n def GetAppFeatureState(self, featureName, featureDefaultState):\n interiorGraphicsQuality = gfxsettings.Get(gfxsettings.GFX_INTERIOR_GRAPHICS_QUALITY)\n postProcessingQuality = gfxsettings.Get(gfxsettings.GFX_POST_PROCESSING_QUALITY)\n shaderQuality = gfxsettings.Get(gfxsettings.GFX_SHADER_QUALITY)\n shadowQuality = gfxsettings.Get(gfxsettings.GFX_SHADOW_QUALITY)\n interiorShaderQuality = gfxsettings.Get(gfxsettings.GFX_INTERIOR_SHADER_QUALITY)\n if featureName == 'Interior.ParticlesEnabled':\n return interiorGraphicsQuality == 2\n elif featureName == 'Interior.LensflaresEnabled':\n return interiorGraphicsQuality >= 1\n elif featureName == 'Interior.lowSpecMaterialsEnabled':\n return interiorGraphicsQuality == 0\n elif featureName == 'Interior.ssaoEnbaled':\n identifier = self.cachedAdapterIdentifiers[0]\n if identifier is not None:\n vendorID = identifier.vendorID\n if vendorID != 4318:\n return False\n return postProcessingQuality != 0 and shaderQuality > 1\n elif featureName == 'Interior.dynamicShadows':\n return shadowQuality > 1\n elif featureName == 'Interior.lightPerformanceLevel':\n return interiorGraphicsQuality\n elif featureName == 'Interior.clothSimulation':\n identifier = self.cachedAdapterIdentifiers[0]\n if identifier is None:\n return featureDefaultState\n vendorID = identifier.vendorID\n return vendorID == NVIDIA_VENDORID and gfxsettings.Get(gfxsettings.GFX_CHAR_CLOTH_SIMULATION) and interiorGraphicsQuality == 2 and not blue.sysinfo.isTransgaming\n elif featureName == 'CharacterCreation.clothSimulation':\n return gfxsettings.Get(gfxsettings.GFX_CHAR_CLOTH_SIMULATION)\n elif featureName == 'Interior.useSHLighting':\n return interiorShaderQuality > 0\n else:\n return featureDefaultState\n return\n\n def GetUIScalingOptions(self, height=None):\n if height:\n desktopHeight = height\n else:\n desktopHeight = uicore.desktop.height\n options = [(localization.GetByLabel('UI/Common/Formatting/Percentage', percentage=90), 0.9), (localization.GetByLabel('UI/Common/Formatting/Percentage', percentage=100), 1.0)]\n if desktopHeight >= 900:\n options.append((localization.GetByLabel('UI/Common/Formatting/Percentage', percentage=110), 1.1))\n if desktopHeight >= 960:\n options.append((localization.GetByLabel('UI/Common/Formatting/Percentage', percentage=125), 1.25))\n if desktopHeight >= 1200:\n options.append((localization.GetByLabel('UI/Common/Formatting/Percentage', percentage=150), 1.5))\n return options\n\n def GetChange(self, scaleValue):\n oldHeight = int(trinity.device.height / uicore.desktop.dpiScaling)\n oldWidth = int(trinity.device.width / uicore.desktop.dpiScaling)\n newHeight = int(trinity.device.height / scaleValue)\n newWidth = int(trinity.device.width / scaleValue)\n changeDict = {}\n changeDict['ScalingWidth'] = (oldWidth, newWidth)\n changeDict['ScalingHeight'] = (oldHeight, newHeight)\n return changeDict\n\n def CapUIScaleValue(self, checkValue):\n desktopHeight = trinity.device.height\n minScale = 0.9\n if desktopHeight < 900:\n maxScale = 1.0\n elif desktopHeight < 960:\n maxScale = 1.1\n elif desktopHeight < 1200:\n maxScale = 1.25\n else:\n maxScale = 1.5\n return max(minScale, min(maxScale, checkValue))\n\n def SetupUIScaling(self):\n if not uicore.desktop:\n return\n windowed = self.IsWindowed()\n self.SetUIScaleValue(self.GetUIScaleValue(windowed), windowed)\n\n def SetUIScaleValue(self, scaleValue, windowed):\n self.LogInfo('SetUIScaleValue', scaleValue, 'windowed', windowed)\n capValue = self.CapUIScaleValue(scaleValue)\n if windowed:\n gfxsettings.Set(gfxsettings.GFX_UI_SCALE_WINDOWED, capValue, pending=False)\n else:\n gfxsettings.Set(gfxsettings.GFX_UI_SCALE_FULLSCREEN, capValue, pending=False)\n if capValue != uicore.desktop.dpiScaling:\n PreUIScaleChange_DesktopLayout = uicontrols.Window.GetDesktopWindowLayout()\n oldValue = uicore.desktop.dpiScaling\n uicore.desktop.dpiScaling = capValue\n uicore.desktop.UpdateSize()\n self.LogInfo('SetUIScaleValue capValue', capValue)\n sm.ScatterEvent('OnUIScalingChange', (oldValue, capValue))\n uicontrols.Window.LoadDesktopWindowLayout(PreUIScaleChange_DesktopLayout)\n else:\n self.LogInfo('SetUIScaleValue No Change')\n\n def GetUIScaleValue(self, windowed):\n if windowed:\n scaleValue = gfxsettings.Get(gfxsettings.GFX_UI_SCALE_WINDOWED)\n else:\n scaleValue = gfxsettings.Get(gfxsettings.GFX_UI_SCALE_FULLSCREEN)\n return scaleValue\n\n def ApplyTrinityUserSettings(self):\n effectsEnabled = gfxsettings.Get(gfxsettings.UI_EFFECTS_ENABLED)\n trailsEnabled = effectsEnabled and gfxsettings.Get(gfxsettings.UI_TRAILS_ENABLED)\n trinity.settings.SetValue('eveSpaceObjectTrailsEnabled', trailsEnabled)","sub_path":"client/eve/client/script/ui/services/eveDevice.py","file_name":"eveDevice.py","file_ext":"py","file_size_in_byte":17957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"423136707","text":"from sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn import datasets\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score, f1_score, jaccard_score\nfrom sklearn.ensemble import VotingClassifier\n\n\n# Checking dataset\n#dataset = datasets.load_breast_cancer()\n# print(dataset)\n\n# Loading dataset\nX, y = datasets.load_breast_cancer(return_X_y=True)\n\n# Splitting data\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.3, random_state=4)\n\nprint(f'Shape of X_train: {X_train.shape}')\nprint(f'Shape of y_train: {y_train.shape}')\n\n\n# Creating Logistic Regression\nLR = LogisticRegression(solver='liblinear')\n\n\n# Creating Decision Tree with the best number of depth\nbest_score_DT = 0.0\nfor depth in range(1, 10):\n DT = DecisionTreeClassifier(criterion='gini',\n max_depth=depth,\n min_samples_leaf=0.2)\n scores = cross_val_score(DT, X_test, y_test, cv=10)\n score = scores.mean()\n\n if score > best_score_DT:\n best_score_DT = score\n best_DT = DT\n best_depth = depth\n\nDT = best_DT\n\n\n# Creating KNeighbors Classifier with the best number of neighbors\nbest_score = 0.0\nfor k in range(3, 13):\n KNN = KNeighborsClassifier(n_neighbors=k,\n algorithm='auto')\n scores = cross_val_score(KNN, X_test, y_test, cv=10)\n score = scores.mean()\n\n if score > best_score:\n best_score = score\n best_KNN = KNN\n best_k = k\n\nKNN = best_KNN\n\n\n# Creating Support Vector Machine\nSVM = SVC(max_iter=1000)\n\n\n# List of models to iterate over\nmodels = [('Logistic Regression', LR),\n ('KNeighbors', KNN),\n ('Decision Tree', DT),\n ('Support Vector Machine', SVM)]\n\n# for model in models:\n# print(model)\n\n\n# Dictionary to save results\naccuracy_per_model = {}\n\n\n# Getting accuracy results\nfor name, model in models:\n model.fit(X_train, y_train)\n y_pred = model.predict(X_test)\n acc = accuracy_score(y_test, y_pred)\n accuracy_per_model[name] = round(acc, 3)\n\n\nprint(accuracy_per_model)\n\n\n# Voting is one of the simplest way of combining the predictions from multiple machine learning algorithms\nVC = VotingClassifier(estimators=models, voting='hard')\nVC.fit(X_train, y_train)\ny_pred = VC.predict(X_test)\nacc = accuracy_score(y_test, y_pred)\nprint('Voting Classifier Accuracy:', round(acc, 3))\n","sub_path":"votingClassifier.py","file_name":"votingClassifier.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"74667776","text":"import datetime\nfrom io import BytesIO\n\nfrom django.contrib.auth import get_user_model\nfrom django.test import TestCase\nfrom django.utils import timezone\n\nfrom sorl.thumbnail import get_thumbnail\n\nfrom ..models import Post\n\nfrom .factories import PostFactory, PicFactory\n\n\nUser = get_user_model()\n\n\nclass PostTests(TestCase):\n def test_create(self):\n post = PostFactory()\n self.assertTrue(post.draft)\n self.assertTrue(post.published_at)\n self.assertTrue(post.updated_at)\n\n def test_str(self):\n self.assertEqual(str(PostFactory()), 'A Test Post')\n\n def test_get_absolute_url(self):\n post = PostFactory.build()\n self.assertRegexpMatches(\n post.get_absolute_url(),\n r'^/post/[\\w\\-]+/preview/$',\n )\n\n def test_get_url(self):\n post = PostFactory.build()\n self.assertRegexpMatches(\n post.get_url(),\n r'^/post/[\\w\\-]+/$',\n )\n\n def test_get_absolute_uri(self):\n post = PostFactory.build()\n self.assertRegexpMatches(\n post.get_absolute_uri(),\n r'^https?://[\\w\\.]+/post/[\\w\\-]+/$',\n )\n\n def test_render_content(self):\n self.assertEqual(\n PostFactory().render_content(),\n '

Some test content

'\n )\n\n def test_manager_published(self):\n post = PostFactory()\n # Post is marked as a draft\n self.assertNotIn(post, Post.objects.published())\n\n # Post not marked as draft\n post.draft = False\n post.save()\n self.assertIn(post, Post.objects.published())\n\n # Post is published in the future.\n post.published_at = timezone.now() + datetime.timedelta(30)\n post.save()\n self.assertNotIn(post, Post.objects.published())\n\n def test_identifier(self):\n post = PostFactory(id=1, old_url='http://example.com/some/post/')\n self.assertEqual(post.identifier, 'http://example.com/some/post/')\n del post.__dict__['identifier']\n post.old_url = ''\n self.assertEqual(post.identifier, '4q2VolejRejNmGQB')\n\n def test_qr(self):\n post = PostFactory.create()\n self.assertIsInstance(post.qr, BytesIO)\n self.assertTrue(post.qr.read())\n\n\nclass PicTests(TestCase):\n def test_create(self):\n pic = PicFactory()\n self.assertTrue(pic.created_at)\n self.assertTrue(pic.updated_at)\n self.assertFalse(pic.alt_text)\n\n def test_str(self):\n self.assertEqual(str(PicFactory.build()), 'My Pic')\n\n def test_render(self):\n pic = PicFactory.build()\n self.assertEqual(\n pic.render(),\n '\"\"'.format(pic.image.url)\n )\n\n def test_render_with_alt_text(self):\n pic = PicFactory.build(alt_text='Test')\n self.assertEqual(\n pic.render(),\n '\"Test\"'.format(pic.image.url),\n )\n\n def test_render_with_geometry(self):\n pic = PicFactory.build()\n url100 = get_thumbnail(pic.image, '100x100').url\n url100c = get_thumbnail(pic.image, '100x100', crop='center').url\n\n r100 = pic.render('100x100')\n r100c = pic.render('100x100', crop='center')\n\n self.assertNotEqual(r100, r100c)\n self.assertEqual(r100, '\"\"'.format(url100))\n self.assertEqual(r100c, '\"\"'.format(url100c))\n\n def test_render_small(self):\n pic = PicFactory.build()\n self.assertRegexpMatches(\n pic.render_small(),\n r'\\',\n )\n","sub_path":"rickvause/apps/blog/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":3612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"346558877","text":"import pickle\nimport os\nimport re\nfrom datetime import datetime\nimport logging\n\n# Get an instance of a logger\nlogger = logging.getLogger(__name__)\n\nimport requests.exceptions\nfrom bs4 import BeautifulSoup\n\nfrom contracts.crawler import AbstractCrawler\n\n\ndef safe_pickle_load(file_name):\n \"\"\"\n Given a file name, returns the unpickled content of the file or None if any exception.\n \"\"\"\n try:\n f = open(file_name, \"r\")\n try:\n data = pickle.load(f)\n except EOFError:\n data = None\n finally:\n f.close()\n except IOError:\n data = None\n\n return data\n\n\ndef clean_legislature(string):\n \"\"\"\n Parses a string into a legislature (integer) and dates (beginning and end).\n \"\"\"\n\n roman_numerals = {\n 'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5,\n 'VI': 6, 'VII': 7, 'VIII': 8, 'IX': 9, 'X': 10,\n 'XI': 11, 'XII': 12, 'XIII': 13, 'XIV': 14, 'XV': 15,\n 'XVI': 16, 'XVII': 17, 'XVIII': 18, 'XIX': 19, 'XX': 20,\n 'XXI': 21, 'XXII': 22, 'XXIII': 23, 'XXIV': 24, 'XXV': 25,\n }\n\n string = string.replace(' ', '')\n number, dates = string.split('[')\n number = roman_numerals[number.strip()]\n dates = dates.strip(' ]')\n if len(dates.split(' a ')) == 2:\n start, end = dates.split(' a ')\n else:\n start = dates.split(' a ')[0]\n end = ''\n if start.endswith(' a'):\n start = start.replace(' a', '')\n return number, start, end\n\n\nclass DeputiesCrawler(AbstractCrawler):\n def __init__(self):\n super(DeputiesCrawler, self).__init__()\n\n self._deputy_url_formatter = 'http://www.parlamento.pt/DeputadoGP/Paginas/Biografia.aspx?BID=%d'\n\n self._html_prefix = 'ctl00_ctl13_g_8035397e_bdf3_4dc3_b9fb_8732bb699c12_ctl00_'\n\n self._html_mapping = {'name': 'ucNome_rptContent_ctl01_lblText',\n 'short': 'lblNomeDeputado',\n 'birthday': 'ucDOB_rptContent_ctl01_lblText',\n 'party': 'lblPartido',\n 'occupation': 'pnlProf',\n 'education': 'pnlHabilitacoes',\n 'current_jobs': 'pnlCargosDesempenha',\n 'jobs': 'pnlCargosExercidos',\n 'awards': 'pnlCondecoracoes',\n 'commissions': 'pnlComissoes',\n 'mandates': 'gvTabLegs'}\n\n self._html_element = {'name': 'span',\n 'short': 'span',\n 'birthday': 'span',\n 'party': 'span',\n 'occupation': 'div',\n 'education': 'div',\n 'current_jobs': 'div',\n 'jobs': 'div',\n 'awards': 'div',\n 'commissions': 'div',\n 'mandates': 'table'}\n\n self.data_directory = '../deputies_data/'\n\n def crawl_deputy(self, bid):\n url = self._deputy_url_formatter % bid\n soup = BeautifulSoup(self.goToPage(url))\n\n tester_key = 'name'\n # if name doesn't exist, we exit\n if not soup.find(self._html_element[tester_key], dict(id=self._html_prefix + self._html_mapping[tester_key])):\n return {}\n\n # we populate \"entry\" with each datum\n entry = {}\n for key in self._html_mapping:\n entry[key] = soup.find(self._html_element[key],\n dict(id=self._html_prefix + self._html_mapping[key])) or None\n entry['name'] = entry['name'].text\n\n # and we clean and validate it in place:\n entry['id'] = bid\n entry['retrieval_date'] = datetime.utcnow().isoformat()\n\n if entry['short'] is not None:\n entry['short'] = entry['short'].text\n if entry['birthday'] is not None:\n entry['birthday'] = datetime.strptime(entry['birthday'].text, \"%Y-%m-%d\").date()\n if entry['party'] is not None:\n entry['party'] = entry['party'].text\n\n if entry['education'] is not None:\n entries = []\n for each in entry['education'].findAll('tr')[1:]:\n text = each.find('span').text\n entries.append(text)\n entry['education'] = entries\n else:\n entry['education'] = []\n\n if entry['occupation'] is not None:\n entries = []\n for each in entry['occupation'].findAll('tr')[1:]:\n entries.append(each.text)\n entry['occupation'] = entries\n else:\n entry['occupation'] = []\n\n if entry['jobs']:\n entries = []\n for each in entry['jobs'].findAll('tr')[1:]:\n if '\\n' in each.text:\n for j in each.text.split('\\n'):\n if j:\n entries.append(j.rstrip(' .;'))\n else:\n entries.append(each.text)\n entry['jobs'] = entries\n else:\n entry['jobs'] = []\n\n if entry['current_jobs'] is not None:\n entries = []\n for each in entry['current_jobs'].findAll('tr')[1:]:\n if '\\n' in each.text:\n for j in each.text.split('\\n'):\n if j:\n entries.append(j.rstrip(' .;'))\n else:\n entries.append(each.text.rstrip(' ;.'))\n entry['current_jobs'] = entries\n else:\n entry['current_jobs'] = []\n\n if entry['commissions'] is not None:\n entries = []\n for each in entry['commissions'].findAll('tr')[1:]:\n entries.append(each.text)\n entry['commissions'] = entries\n else:\n entry['commissions'] = []\n\n if entry['awards']:\n entries = []\n for each in entry['awards'].findAll('tr')[1:]:\n if '\\n' in each.text:\n for j in each.text.split('\\n'):\n if j:\n entries.append(j.rstrip(' .;'))\n else:\n entries.append(each.text.rstrip(' ;.'))\n entry['awards'] = entries\n else:\n entry['awards'] = []\n\n if entry['mandates']:\n entries = []\n for each in entry['mandates'].findAll('tr')[1:]:\n leg = each.findAll('td')\n l = leg[0].text\n number, start_date, end_date = clean_legislature(l)\n\n entries.append({'legislature': number,\n 'start_date': start_date,\n 'end_date': end_date,\n 'constituency': leg[3].text,\n 'party': leg[4].text})\n entry['mandates'] = entries\n else:\n entry['mandates'] = []\n\n return entry\n\n def get_deputy(self, bid, flush_cache=False):\n logger.info('retrieving bid %d', bid)\n file_name = self.data_directory + 'deputy_%d.dat' % bid\n data = safe_pickle_load(file_name)\n\n if data is None or flush_cache:\n try:\n data = self.crawl_deputy(bid)\n except:\n logger.exception('Not able to retrieve bid %d', bid)\n raise\n\n f = open(file_name, \"w\")\n pickle.dump(data, f)\n f.close()\n return data\n\n def get_last_bid(self):\n regex = re.compile(r\"deputy_(\\d+).dat\")\n files = [int(re.findall(regex, f)[0]) for f in os.listdir('%s' % self.data_directory) if re.match(regex, f)]\n files = sorted(files, key=lambda x: int(x), reverse=True)\n if len(files):\n return files[0]\n else:\n return 0\n\n def get_deputies(self, flush_cache=False):\n \"\"\"\n Returns an iterable of deputies data. If flush_cache is True,\n cached data is updated.\n \"\"\"\n bid = 0\n while True:\n entry = self.get_deputy(bid, flush_cache)\n if entry != {}:\n yield entry\n bid += 1\n\n def get_deputies_list(self, bid_list):\n \"\"\"\n Returns an iterable of deputies data from the bid list.\n Used to update entries.\n \"\"\"\n for bid in bid_list:\n entry = self.get_deputy(bid, flush_cache=True)\n yield entry\n\n def get_new_deputies(self):\n bid = self.get_last_bid()\n while True:\n try:\n entry = self.get_deputy(bid, True)\n except requests.exceptions.ConnectionError:\n if 'User-agent' in self.request_headers:\n logger.warning(\"removed header\")\n self.request_headers['User-agent'].pop()\n else:\n logger.warning(\"added header\")\n self.request_headers['User-agent'] = self.user_agent\n entry = self.get_deputy(bid, True)\n if entry != {}:\n yield entry\n bid += 1\n","sub_path":"deputies/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":9209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"36338322","text":"def comma_code(arg):\n result = ''\n for i in range(len(arg) - 1):\n result += arg[i] + \", \"\n result += \"and \" + arg[-1]\n return result\n\n\ndef main():\n spam = ['apples', 'bananas', 'tofu', 'cats']\n print(comma_code(spam))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"students/kulon_aleksander/lesson_05/comma_code.py","file_name":"comma_code.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"370602021","text":"import numpy as np\nimport copy\nclass Board():\n def __init__(self, a=None, b=None):\n self.whitePieces = []\n self.blackPieces = []\n self.score = 0\n self.a = a\n self.b = b\n self.MoveCount = 0\n\n def GetAllPieces(self):\n return self.whitePieces + self.blackPieces\n\n def Length(self):\n return len(self.GetAllPieces())\n\n def Represent(self):\n rep = np.zeros((8,8))\n pieces = self.GetAllPieces()\n for p in pieces:\n if p.color == \"W\":\n rep[p.position[1]][p.position[0]] = p.value\n else:\n rep[p.position[1]][p.position[0]] = -p.value\n print (rep)\n print(\"-----\")\n\n def Clear(self):\n self.whitePieces = []\n self.blackPieces = []\n self.allPieces = []\n self.score = 0\n\n def GetScore(self):\n rep = np.zeros((8, 8))\n pieces = self.GetAllPieces()\n for p in pieces:\n if p.color == \"W\":\n rep[p.position[1]][p.position[0]] = p.value\n else:\n rep[p.position[1]][p.position[0]] = -p.value\n self.score = rep.sum()\n return rep.sum()\n\n def CopyState(self,board):\n self.Clear()\n for p in board.whitePieces:\n self.whitePieces.append(copy.deepcopy(p))\n for p in board.blackPieces:\n self.blackPieces.append(copy.deepcopy(p))\n\n def IsOccupied(self,pos):\n for p in self.GetAllPieces():\n if tuple(p.position) == tuple(pos):\n return True\n else:\n return False\n\n\n def Occupier(self,pos):\n for p in self.GetAllPieces():\n if tuple(p.position) == tuple(pos):\n return p\n","sub_path":"Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"150993519","text":"import numpy\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import Dropout\nfrom keras.layers import LSTM\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.utils import np_utils\nfrom re import sub\nimport sys\n\n# Ввод данных\nprint(\"Введите количество символов для генерации текста:\")\nwhile True:\n try:\n chars_for_gen = int(input())\n except ValueError:\n print(\"Неверный ввод. Введите число!\")\n else:\n break\n\n# Загрузка текста и перевод его символовв нижний регистр\nfilename = 'sherlock.txt'\nraw_text = open(filename).read().lower()\n\n# Удаление пунктуации\nraw_text = sub('[ .,!?:;\\\"\\'`~@#$%^&*()\\\\\\[\\]/]+', ' ', raw_text)\n\n# Выбор уникальных символов и ассоциация их с числами\nchars = sorted(list(set(raw_text)))\nchar_to_integers = dict((c, i) for i, c in enumerate(chars))\n\n# Подсчет кол-ва символов и уникальных символов\nn_chars = len(raw_text)\nn_vocab = len(chars)\nprint(\"Всего символов: \", n_chars)\nprint(\"Всего уникальных символов: \", n_vocab)\n\n# Подготовка данных для обучения\nseq_length = 100\ndataX = []\ndataY = []\nfor i in range(0, n_chars - seq_length, 1):\n #\n seq_in = raw_text[i:i + seq_length]\n seq_out = raw_text[i + seq_length]\n dataX.append([char_to_integers[char] for char in seq_in])\n dataY.append(char_to_integers[seq_out])\nn_patterns = len(dataX)\nprint(\"Выделено шаблонов: \", n_patterns)\n\n# X к виду [samples, time steps, features]\nX = numpy.array(dataX)\nprint(X.shape)\nX = X.reshape((n_patterns, seq_length, 1))\nprint(X.shape)\n# нормализация X\nX = X / float(n_vocab)\n# кодирование выходной переменной\ny = np_utils.to_categorical(dataY)\n\n# Определение модели LSTM\nmodel = Sequential()\nmodel.add(LSTM(256, input_shape=(X.shape[1], X.shape[2])))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(y.shape[1], activation='softmax'))\n\n\"\"\"model.compile(loss='categorical_crossentropy', optimizer='adam')\n\n# Определение чек-пойнтов\n# define the checkpoint\nfilepath=\"weights-improvement-{epoch:02d}-{loss:.4f}.hdf5\"\ncheckpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')\ncallbacks_list = [checkpoint]\n\n# Обучение сети\nmodel.fit(X, y, epochs=100, batch_size=128, callbacks=callbacks_list)\"\"\"\n\n# Разобраться с этого момента!!!!!\n# load the network weights\nfilename = \"weights-improvement-64-1.6889.hdf5\"\nmodel.load_weights(filename)\nmodel.compile(loss='categorical_crossentropy', optimizer='adam')\n\nint_to_char = dict((i, c) for i, c in enumerate(chars))\n\n# pick a random seed\nstart = numpy.random.randint(0, len(dataX)-1)\n#start = 40\npattern = dataX[start]\nprint(\"Источник:\")\nprint(\"\\\"\", ''.join([int_to_char[value] for value in pattern]), \"\\\"\")\nprint(\"Сгенерированный текст:\")\n# generate characters\nfor i in range(chars_for_gen):\n x = numpy.reshape(pattern, (1, len(pattern), 1))\n x = x / float(n_vocab)\n prediction = model.predict(x, verbose=0)\n index = numpy.argmax(prediction)\n result = int_to_char[index]\n seq_in = [int_to_char[value] for value in pattern]\n sys.stdout.write(result)\n pattern.append(index)\n pattern = pattern[1:len(pattern)]\n\nprint(\"\\nКонец.\")","sub_path":"lpo6.py","file_name":"lpo6.py","file_ext":"py","file_size_in_byte":3575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"262445358","text":"#!/usr/bin/env python\n#coding: utf-8\n\nimport os\nimport sys\nfrom os import listdir\n\nfilelist = listdir(\"/fcsata/xiongy/swiss_model/repository_2/filter_structure\")\nifile = open(\"filter_structure.out\",\"r\")\nofile = open(\"filter_structure_add_info.out\",\"w\")\n\nfor line in ifile:\n line = line.rstrip(\"\\n\")\n l = line.split(\"\\t\")\n filename = l[0]+\"_\"+\"_\".join(l[3:6])+\"_\"+l[2]+\".pdb\"\n if l[2] == \"swissmodel\":\n ifile1 = open(\"./filter_structure/\"+filename,\"r\")\n pdb_content = ifile1.readlines()\n pdb_content = [i.rstrip(\"\\n\").split() for i in pdb_content]\n pdb_content = [i for i in pdb_content if len(i) >= 4 and i[0] == \"REMARK\"]\n for line1 in pdb_content:\n if line1[2] == \"GMQE\":\n gmqe = line1[3]\n elif line1[2] == \"QMN4\":\n qmn4 = line1[3]\n elif line1[2] == \"MTHD\":\n method = \" \".join(line1[3:])\n elif line1[2] == \"SIM\":\n similarity = line1[3]\n elif line1[2] == \"SID\":\n sid = line1[3]\n info = [gmqe,qmn4,method,similarity,sid]\n ifile1.close()\n print >> ofile,line+\"\\t\"+\"\\t\".join(info)\n else:\n print >> ofile,line+5*\"\\t\"\n\nifile.close() \nofile.close()\n","sub_path":"add_info.py","file_name":"add_info.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"105988108","text":"from __future__ import print_function\nimport numpy as np\nimport keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D, Activation\nfrom keras import backend as K\nfrom keras.callbacks import ModelCheckpoint\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn import manifold\nimport gzip\nfrom time import time\nfrom sklearn.metrics import log_loss\nimport pickle\nimport os\n\nos.environ['CUDA_VISIBLE_DEVICES'] = \"1\"\n\nbatch_size = 128\nnum_classes = 10\nepochs = 1000\n\n# input image dimensions\nimg_rows, img_cols = 32,32\n\ndef unpickle(file):\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\ntrain_labels, train_data = [], []\n\nfor batch_num in range(1, 6):\n\tbatch_dict = unpickle('/home/balerion/Downloads/cifar-10-batches-py/data_batch_'+str(batch_num))\n\n\tbatch_labels = np.array(batch_dict[b'labels'])\n\ttrain_labels.append(batch_labels)\n\n\tbatch_data = np.array(batch_dict[b'data'])\n\tbatch_data = batch_data.reshape(-1, img_rows, img_cols, 3, order='F')\n\tbatch_data = np.swapaxes(batch_data, 1, 2)\n\ttrain_data.append(batch_data)\n\nx_train, y_train = np.array(train_data).reshape(50000, 32, 32, 3), np.array(train_labels).reshape(50000)\n\nbatch_dict = unpickle('/home/balerion/Downloads/cifar-10-batches-py/test_batch')\n\ny_test_original = np.array(batch_dict[b'labels'])\n\nbatch_data = np.array(batch_dict[b'data'])\nbatch_data = batch_data.reshape(-1, img_rows, img_cols, 3, order='F')\nx_test = np.swapaxes(batch_data, 1, 2)\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\n\n# convert class vectors to binary class matrices\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test_original, num_classes)\n\ninput_shape = (img_rows, img_cols, 3)\n\nmodel = Sequential()\n\nmodel.add(Conv2D(64, (3, 3), padding='same',\n input_shape=x_train.shape[1:]))\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(64, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(128, (3, 3), padding='same'))\nmodel.add(Activation('relu'))\nmodel.add(Conv2D(128, (3, 3)))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(512))\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(num_classes))\nmodel.add(Activation('softmax'))\n\n# initiate RMSprop optimizer\nopt = keras.optimizers.rmsprop(lr=0.0001, decay=1e-6)\n\n# Let's train the model using RMSprop\nmodel.compile(loss='categorical_crossentropy',\n optimizer=opt,\n metrics=['accuracy'])\n\n'''for epoch_num in range(epochs):\n checkpoint = ModelCheckpoint('cifar10_model.hdf5', monitor='val_loss', verbose=0, save_best_only=True)\n model.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=1,\n verbose=1,\n validation_data=(x_test, y_test),\n callbacks = [checkpoint])\n score = model.evaluate(x_test, y_test, verbose=0)\n print('Test loss:', score[0])\n print('Test accuracy:', score[1])'''\n\nmodel.load_weights('cifar10_model.hdf5')\nprint(model.summary())\nN_samples = 10000\n\nper_sample_logloss_list = []\nencoded_input_list = []\n\nintermediate_layer_model = keras.models.Model(inputs=model.input,\n outputs=model.get_layer(index=15).output)\n\nfor i in range(N_samples):\n per_sample_logloss_list.append(log_loss(y_test[i:i+1], model.predict(x_test[i:i+1]), normalize=False))\n encoded_input_list.append(intermediate_layer_model.predict(x_test[i:i+1])[0])\n\nencoded_input_list = np.array(encoded_input_list)\n\nper_sample_logloss_list /= np.max(per_sample_logloss_list)\nper_sample_logloss_list = per_sample_logloss_list**0.5\nprint(np.mean(per_sample_logloss_list), np.std(per_sample_logloss_list))\nprint(np.min(per_sample_logloss_list), np.max(per_sample_logloss_list))\n\ndef plot_embedding(X, Y, color_dict):\n x_min, x_max = np.min(X, 0), np.max(X, 0)\n X = (X - x_min) / (x_max - x_min)\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n\n for i in range(X.shape[0]):\n ax.scatter(X[i, 0], X[i, 1], c=color_dict[Y[i]], s=max(10, 100*per_sample_logloss_list[i]))\n\ntsne = manifold.TSNE(n_components=2, init='pca', random_state=0)\nX_tsne = tsne.fit_transform(encoded_input_list)\n\ncolor_dict = {0:'yellow', 1:'blue', 2:'red', 3:'green', 4:'brown',\n 5:'tan', 6:'black', 7:'orange', 8:'orchid', 9:'darkturquoise'}\n\nplot_embedding(X_tsne, y_test_original[:N_samples], color_dict)\n\nplt.show()\nplt.close()\n\n\n","sub_path":"cifar10_tsne.py","file_name":"cifar10_tsne.py","file_ext":"py","file_size_in_byte":4821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"285151778","text":"import sys\nimport create_contact_features\nimport numpy as np\nimport glob\nimport pickle\nfrom threading import Thread\nfrom subprocess import call\nimport os\n\n\n\nfor i in range(48):\n print(i)\n data = pickle.load(open(\"data\" + str(i) + \".pkl\", 'rb'))\n X_i = data['X']\n y_i = data['y']\n peptides_i = data['peptides']\n alleles_i = data['alleles']\n\n if i == 0:\n X = X_i\n y = y_i\n peptides = peptides_i\n alleles = alleles_i\n else:\n X = np.concatenate((X, X_i), axis=0)\n y = np.concatenate((y, y_i), axis=0)\n peptides = np.concatenate((peptides, peptides_i), axis=0)\n alleles = np.concatenate((alleles, alleles_i), axis=0)\n\n\n #call([\"rm -r \" + fol], shell=True)\n\nX = np.array(X)\ny = np.array(y)\n\nprint(X.shape, y.shape, peptides.shape, alleles.shape)\n\ndata = {'X':X, 'y':y, 'peptides':peptides, 'alleles':alleles}\n\nf = open(\"data_ensemble.pkl\", 'wb')\npickle.dump(data, f)\nf.close()\n","sub_path":"featurization/combine_data_ensemble_parts.py","file_name":"combine_data_ensemble_parts.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"158608862","text":"import requests\r\nimport bs4\r\n\r\n\r\ndict = {}\r\nplayers_list = []\r\n\r\nvisit = 100 # payment for participation\r\nrate = 125 # payment for each game victory\r\nposition_1 = 200\r\nposition_2 = 150\r\nposition_3 = 100\r\n\r\n\r\ndef main():\r\n\r\n print_the_header()\r\n\r\n link = input('Enter the result link (01.03.2018/1/) >>> ')\r\n\r\n html = get_html_from_web(link)\r\n\r\n table_dict = get_dictionary_from_html(html)\r\n\r\n get_result_from_tabledict(table_dict)\r\n\r\n\r\ndef print_the_header():\r\n print('-----------------------------------------')\r\n print(' TT CUP ')\r\n print('-----------------------------------------')\r\n print()\r\n\r\ndef get_html_from_web(link_arg):\r\n url = 'http://tt-cup.com/results/{}'.format(link_arg)\r\n response = requests.get(url)\r\n\r\n return response.text\r\n\r\ndef get_dictionary_from_html(html):\r\n\r\n soup = bs4.BeautifulSoup(html, 'html.parser')\r\n\r\n place_list = []\r\n place_temp = []\r\n\r\n player = soup.find_all('table')[0].find_all('a')\r\n for player_item in player:\r\n players_list.append(str((player_item.get_text())))\r\n\r\n place = soup.find_all('table')[0].find_all('span')\r\n\r\n for place_item in place:\r\n place_temp.append((place_item.get_text()).strip()[:--1])\r\n\r\n count = 0\r\n total_scores = len(players_list) * 8\r\n\r\n while count < total_scores:\r\n place_list.append(place_temp[count][:--1])\r\n count += 1\r\n\r\n place_list = [place_list[x:x+8] for x in range(0, len(place_list), 8)]\r\n\r\n i = 0\r\n\r\n while i < len(players_list):\r\n dict[players_list[i]] = [place_list[i][x:x+6] for x in range(0, len(place_list[0]), 7)]\r\n i += 1\r\n\r\n return dict\r\n\r\ndef get_result_from_tabledict(table):\r\n\r\n def calc_wins(arg):\r\n count = 0\r\n for x in arg:\r\n if x == '3':\r\n count += 1\r\n return count\r\n\r\n i = 0\r\n while i < 6:\r\n\r\n player_scores = table[players_list[i]][0]\r\n player_position = table[players_list[i]][1]\r\n\r\n fee = calc_wins(player_scores) * rate + visit\r\n\r\n if player_position[0] == '1':\r\n fee += position_1\r\n elif player_position[0] == '2':\r\n fee += position_2\r\n elif player_position[0] == '3':\r\n fee += position_3\r\n else:\r\n fee = fee\r\n\r\n print('{} {}, к оплате {}грн.'.format(i + 1, players_list[i], fee))\r\n i += 1\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n","sub_path":"tt_cup_by_tournire_table_1_1.py","file_name":"tt_cup_by_tournire_table_1_1.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"593633551","text":"# coding=utf-8\n# Copyright 2019 The SEED Authors\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\"\"\"Environment wrappers.\"\"\"\n\nfrom absl import flags\n\nimport gym\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nFLAGS = flags.FLAGS\n\n\nclass TFAgents2GymWrapper(gym.Env):\n \"\"\"Transform TFAgents environment into an OpenAI Gym environment.\"\"\"\n\n def __init__(self, env):\n self.env = env\n self.observation_space = env.observation_space\n self.action_space = env.action_space\n\n def step(self, action):\n assert self.action_space.contains(action)\n env_output = self.env.step(action)\n reward = env_output.reward\n done = env_output.is_last()\n return env_output.observation, reward, done, None\n\n def reset(self):\n return self.env.reset().observation\n\n def render(self):\n frame = self.env.render()\n plt.figure(1)\n plt.clf()\n plt.imshow(frame)\n plt.pause(0.001)\n\n\nclass UniformBoundActionSpaceWrapper(gym.Env):\n \"\"\"Rescale actions so that action space bounds are [-1, 1].\"\"\"\n\n def __init__(self, env):\n \"\"\"Initialize the wrapper.\n\n Args:\n env: Environment to be wrapped. It must have an action space of type\n gym.spaces.Box and the action bounds have to be symmetric w.r.t. 0, i.e.\n (env.action_space.low == -env.action_space.high).all().\n \"\"\"\n self.env = env\n self.observation_space = env.observation_space\n assert isinstance(env.action_space, gym.spaces.Box)\n n_action_dim = env.action_space.shape[0]\n self.high = env.action_space.high\n assert (env.action_space.low == -self.high).all(), (\n 'UniformBoundActionSpaceWrapper only supports action spaces with '\n 'symmetric bounds.')\n self.action_space = gym.spaces.Box(low=-np.ones(n_action_dim),\n high=np.ones(n_action_dim),\n dtype=np.float32)\n\n def step(self, action):\n assert np.abs(action).max() < 1.00001\n action = np.clip(action, -1, 1)\n assert self.action_space.contains(action)\n action *= self.high\n assert self.env.action_space.contains(action)\n obs, rew, done, info = self.env.step(action)\n return obs, rew, done, info\n\n def reset(self):\n return self.env.reset()\n\n def render(self, *args, **kwargs):\n return self.env.render(*args, **kwargs)\n\n\nclass DiscretizeEnvWrapper(gym.Env):\n \"\"\"Wrapper for discretizing actions.\"\"\"\n\n def __init__(self, env, n_actions_per_dim, discretization='lin',\n action_ratio=None):\n \"\"\"\"Discretize actions.\n\n Args:\n env: Environment to be wrapped.\n n_actions_per_dim: The number of buckets per action dimension.\n discretization: Discretization mode, can be 'lin' or 'log',\n 'lin' spaces buckets linearly between low and high while 'log'\n spaces them logarithmically.\n action_ratio: The ratio of the highest and lowest positive action\n for logarithim discretization.\n \"\"\"\n\n self.env = env\n assert len(env.action_space.shape) == 1\n dim_action = env.action_space.shape[0]\n self.action_space = gym.spaces.MultiDiscrete([n_actions_per_dim] *\n dim_action)\n self.observation_space = env.observation_space\n high = env.action_space.high\n if isinstance(high, float):\n assert env.action_space.low == -high\n else:\n high = high[0]\n assert (env.action_space.high == [high] * dim_action).all()\n assert (env.action_space.low == -env.action_space.high).all()\n if discretization == 'log':\n assert n_actions_per_dim % 2 == 1, (\n 'The number of actions per dimension '\n 'has to be odd for logarithmic discretization.')\n assert action_ratio is not None\n log_range = np.linspace(np.log(high / action_ratio),\n np.log(high),\n n_actions_per_dim // 2)\n self.action_set = np.concatenate([-np.exp(np.flip(log_range)),\n [0.],\n np.exp(log_range)])\n elif discretization == 'lin':\n self.action_set = np.linspace(-high, high, n_actions_per_dim)\n\n def step(self, action):\n assert self.action_space.contains(action)\n action = np.take(self.action_set, action)\n assert self.env.action_space.contains(action)\n obs, rew, done, info = self.env.step(action)\n return obs, rew, done, info\n\n def reset(self):\n return self.env.reset()\n\n def render(self, *args, **kwargs):\n return self.env.render(*args, **kwargs)\n","sub_path":"common/env_wrappers.py","file_name":"env_wrappers.py","file_ext":"py","file_size_in_byte":5028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"416579225","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Long Short Term Memory Network Model Implementation\n# \n# This notebook implements two variants of a LSTM network to predict the next 24 hour ahead energy demand. Predictions are made at the end of each day for the maximum demand for each hour in the day ahead.\n# \n# #### Data Structure\n# Two model variants are tested. A univariate case that uses only past energy demand to make the prediction. And a multivariate case that uses past energy demand, weather features (temperature, humidity, wind speed, rain, etc), and day of the week as predictors.\n# \n# Data structure for the univarate case is described by the following diagram. In this case we are predicting hour-by-hour using previous data from the same hour. In this way each hour becomes a dataset on its own. We can combine these multiple sets into one single block of data with the shape:\n# - INPUT(samples, lags, hour slices)\n# - OUTPUT (samples, hour slices)\n# \n# \n# \n# Data structure for the multivariate case is described as follows. In this case we add features to the lags as a flattened 2D vector of the form (lags, features).\n# - INPUT (samples, lags & features, hourly slices)\n# - OUTPUT (samples, hourly slices)\n# \n# \n# \n# #### Lagged Features\n# This workbook uses between 2 and 9 cross validations on small samples (1-3 years) in while maniuplating the number and composition of the lagged features. The default lags are the previous 7 days. First sequence of variants on this are the last 14, 30, 180, and 365 days. The second variant is to use the previous 7 days, and only multiples of 7 of the target day up to a maximum. I.e. A lag structure of a 30 day maxium lookback would be looksbacks of 1, 2, 3, 4, 5, 6, 7, 14, 21, 28. This was done because the autocorrelation between the target day and days at multiples of 7 is highest.\n# \n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('dark')\n\nimport json\nimport codecs\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport keras\nimport tensorflow\nfrom keras.metrics import mean_squared_error\n\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import TimeSeriesSplit\n\nfrom model_persistence import get_persistence_dataset, train_test_split, calculate_errors, plot_error\nfrom features_preprocessing import make_shifted_features, transform_to_windows\n\n\n\n\n# ### HELPER FUNCTIONS\n# ###### Define a function to calculate and capture the mae\n# \n# This could be done in keras directly with the model.evaluate feature. However that will return the scaled values. We are interested in comparing our results with other models and therefore choose to use the model.predict.\n\n# In[2]:\n\n\ndef normalize_df(data):\n \n #normalize the dataset for working with the lstm nn\n scaler = MinMaxScaler().fit(data.values)\n data_normd = scaler.transform(data.values)\n\n data = pd.DataFrame(data_normd, index=data.index, columns=data.columns)\n \n return data, scaler\n\n\n# In[3]:\n\n\ndef sample_mape(actual, predicted):\n \n #calcualtes the mean absolute percent error per cross validated sample\n #returns as a percentage\n \n return np.mean(np.abs((actual - predicted) / actual)) * 100\n\n\n# In[4]:\n\n\n#define a function to calcualte and capture the mae\n\ndef get_sample_total_mae(actual, predicted):\n #list to save scores\n maes = []\n mapes = []\n\n #loop through each crossvalidation sample\n for i in range(actual.shape[0]):\n \n #calcualte the mae and save to list\n mae = mean_absolute_error(actual[i], predicted[i])\n mape = sample_mape(actual[i], predicted[i])\n \n maes.append(mae)\n mapes.append(mape)\n print('Sample {} total MAE {:.2f}, MAPE {:.2f}%'.format(i,mae, mape))\n \n maes_total = np.mean(maes)\n mape_total = np.mean(mapes)\n \n print('Mean crossvalidation MAE {:.2f} MAPE {:.2f}%'. format(maes_total, mape_total))\n \n return maes, mapes\n\n\n# In[5]:\n\n\ndef inspect_cv_predictions(actuals, predictions):\n\n #the number of cross validation sets\n plots = predictions.shape[0]\n \n #the first day, middle day, and last days of the validation set\n days = [1, int(predictions.shape[1]/2), predictions.shape[1]-1]\n \n #set figure\n fig, axs = plt.subplots(plots,3, figsize=(15,20))\n\n #loop through the samples then loop through the days\n for i, axe in zip(range(plots), axs):\n for day, ax in zip(days, axe):\n \n #plot the predictions\n ax.plot(predictions[i][day], label='predicted')\n #plot actual values\n ax.plot(actuals[i][day], label='actual')\n ax.set_title('Cross val set {}, sample day {}'.format(i,day))\n\n #position the legend in the top left position of the top left chart.\n axs[0][0].legend(loc=2)\n plt.subplots_adjust(hspace=0.3)\n\n\n# In[100]:\n\n\ndef cv_week_predictions(actuals, predictions, num_days=7, shift=0):\n\n #the number of cross validation sets\n plots = predictions.shape[0]\n \n #the first day, middle day, and last days of the validation set\n \n days = [x+shift for x in range(num_days)]\n #days = [1, int(predictions.shape[1]/2), predictions.shape[1]-1]\n \n #set figure\n fig, axs = plt.subplots(plots,1, figsize=(15,20))\n\n #loop through the samples then loop through the days\n for i, ax in zip(range(plots), axs):\n #for day, ax in zip(days, axe):\n \n #plot the predictions\n ax.plot(predictions[i][days].flatten(), label='predicted')\n #plot actual values\n ax.plot(actuals[i][days].flatten(), label='actual')\n ax.set_title('Cross val set {}'.format(i))\n ax.set_xlabel('Hours')\n ax.set_ylabel('MW')\n\n #position the legend in the top left position of the top left chart.\n axs[i].legend(loc='lower right')\n plt.subplots_adjust(hspace=0.3)\n\n\n# In[44]:\n\n\ndef split_sequences(sequences, n_steps, extra_lag=False, long_lag_step=7, max_step=30, idx=0, multivar=False):\n \"\"\"\n Function modified for use from Deep learning time series forecasting by Jason Brownlee\n \"\"\"\n \n #if not adding extra lag features adjust max_step and n_steps to aling\n if not extra_lag:\n max_step=n_steps\n n_steps+=1\n \n \n X, y = list(), list()\n for i in range(len(sequences)):\n \n # find the end of this pattern\n #end_ix = i + n_steps\n end_ix = i + max_step\n \n #create a list with the indexes we want to include in each sample\n slices = [x for x in range(end_ix-1,end_ix-n_steps, -1)] + [y for y in range(end_ix-n_steps, i, -long_lag_step)]\n \n #reverse the slice indexes\n slices = list(reversed(slices))\n \n # check if we are beyond the dataset\n if end_ix > len(sequences)-1:\n break\n\n\n # gather input and output parts of the pattern\n seq_x = sequences[slices, :]\n seq_y = sequences[end_ix, :]\n\n X.append(seq_x)\n y.append(seq_y)\n \n X = np.array(X)\n y = np.array(y)\n \n if multivar:\n #unstack the 3rd dimension and select the first element(energy load)\n y = y[:,idx]\n \n return X, y\n\n\n# # Multivariable - Multiple Parallel Output LSTM\n\n# In[7]:\n\n\n###define an LSTM model\n#takes in parallel inputs and outputs an equal number of parallel outputs\ndef lstm_multi_in_parallel_out(n_lags, n_hours, cells=50, learning_rate=5e-3):\n \n #define the model\n model = keras.models.Sequential()\n model.add(keras.layers.LSTM(cells, activation='relu', return_sequences=True, input_shape=(n_lags, n_hours)))\n model.add(keras.layers.LSTM(int(cells/2), activation='relu'))\n model.add(keras.layers.Dense(n_hours))\n \n #define the learning rate\n optimizer = keras.optimizers.Adam(lr=learning_rate)\n \n #compile model\n model.compile(optimizer=optimizer, loss='mae')\n \n return model\n\n\n\ndef get_lstm_multivariable_data_3d(start='2015-01-01', stop='2015-01-05', n_lags=2, extra_lag=False, long_lag_step=7, max_lookback=30):\n\n #load in the prepared dataset\n all_data = pd.read_csv('./data/lstm/nn_dataset_2015_2018.csv', parse_dates=True, index_col=0)\n\n #select data time slice\n data = all_data[start: stop].copy()\n \n #reshape the energy load columns to prepare for minmax scaling\n energy = data['actual_load'].values.reshape(-1,1)\n \n #minmax scale the energy column\n scaler = MinMaxScaler().fit(energy)\n data_normd = scaler.transform(energy)\n \n #reset the energy column to the actual loads\n data['actual_load'] = data_normd.copy()\n \n #create single columns with time features\n data.loc[:,'year'] = data.index.year\n data.loc[:,'month'] = data.index.month\n data.loc[:,'day'] = data.index.day\n data.loc[:,'hours'] = data.index.hour\n \n hours_tup = [] \n\n #for each unique hour isolate the features and dates\n for h in data.hours.unique():\n \n #boolean mask for each hour of the day\n hour = data[data.hours==h].copy()\n #drop the unneeded columns\n hour.drop(['year', 'month', 'day', 'hours'], axis=1, inplace=True)\n #reshape 2D into a 3D matrix for stacking\n hour = np.reshape(hour.values, (hour.shape[0], hour.shape[1], 1))\n #append each 3d slice into list\n hours_tup.append(hour)\n \n \n tup = tuple(hours_tup)\n \n #stack all the 3D arraysinto 1 single 3D array\n hours_stacked = np.dstack(tup)\n \n #make samples from hours stacked. result is 4D and 2D\n X_4d, y = split_sequences(hours_stacked, \n n_lags, \n extra_lag=extra_lag, \n long_lag_step=long_lag_step, \n max_step=max_lookback, \n idx=0, \n multivar=True)\n #X_4d, y = split_sequences(hours_stacked, n_lags, idx=0, multivar=True)\n \n \n X = []\n\n #flatten the 2nd and 3rd dimensions together to have a final array of samples, lags & features, hours\n for j in range(len(X_4d)):\n #reshape the inner dimensions\n n = X_4d[j].reshape(-1, hours_stacked.shape[-1])\n X.append(n)\n \n X = np.array(X)\n \n \n return X, y, scaler\n\n# In[47]:\n\n\ndef run_multi_var_lstm_pipe(n_lags=2, n_crossvals=2, epochs=5, lr = 1e-3, extra_lag=False, long_lag_step=7, max_lookback=30, show_verbose=False, period_start = '2017-01-01', period_end = '2017-12-31'):\n\n \n n_hours = 24\n\n\n #load the inital data\n X_multi, y_multi, scaler_multi = get_lstm_multivariable_data_3d(start=period_start, \n stop=period_end, \n n_lags=n_lags, \n extra_lag=extra_lag, \n long_lag_step=long_lag_step, \n max_lookback=max_lookback)\n\n\n n_features = X_multi.shape[1]\n\n\n if show_verbose:\n verbose = 1\n else:\n verbose = 0\n\n\n print('Crossvalidation run congifuration:')\n print('Number of crossvalidations: {}' .format(n_crossvals))\n print('Number of total feature vectors: {}' .format(n_features))\n #print('Date range from {} to {}'.format(period_start, period_end))\n\n\n print('Input shape {}'.format(X_multi.shape))\n print('Output shape {}'.format(y_multi.shape))\n\n\n #creates set sequences of the time series to cross validate on. \n tscv = TimeSeriesSplit(n_splits=n_crossvals)\n\n # #initalize lists to capture the output\n predictions = []\n actuals = []\n\n\n #run the LSTM model on each of the time series splits\n for train, test in tscv.split(X_multi, y_multi):\n\n lstm_multi = lstm_multi_in_parallel_out(n_features, n_hours, learning_rate=lr)\n\n\n lstm_multi.fit(X_multi[train], y_multi[train], epochs=epochs, verbose=verbose, shuffle=False)\n\n predict = lstm_multi.predict(X_multi[test], verbose=True)\n\n\n #inverse transform the predictions and actual values\n prediction = scaler_multi.inverse_transform(predict)\n actual = scaler_multi.inverse_transform(y_multi[test].copy())\n\n #save the results in a list\n predictions.append(prediction)\n actuals.append(actual)\n\n\n #convert results to numpy array for easy manipulation\n predictions = np.array(predictions)\n actuals = np.array(actuals)\n\n print(predictions.shape)\n print(actuals.shape)\n #calculate and display the crossvalidated mean average errors \n mae = get_sample_total_mae(actuals, predictions)\n\n #print a selection of the cross validated predictions. See how the sample predictions evolved.\n inspect_cv_predictions(actuals, predictions)\n\n return predictions, actuals\n\n\n\n########### RUN THE MODEL ON CALL OF THIS FILE\nstart_date = '2017-01-01'\nstop_date = '2017-12-31'\nmax_lookback=30\nlong_lag_step=7\nn_lags = 7\nepochs=50\n\nprint('Running Crossvalidation LSTM example with the following parmaters')\nprint('Type: Univariate')\nprint('Inital lag {}'.format(n_lags))\nprint('Long lag step interval of {} days to a maximum of {} days'.format(long_lag_step, max_lookback))\nprint('Crossvalidation interval start {} and stop {}'.format(start_date, stop_date))\nprint('Training model on {} epochs'.format(epochs))\n\n\npredictions, actuals = run_multi_var_lstm_pipe(n_lags=n_lags, \n n_crossvals=3, \n epochs=50, \n lr = 1e-3, \n extra_lag=True, \n long_lag_step=long_lag_step, \n max_lookback=max_lookback, \n show_verbose=False, \n period_start = '2017-01-01', \n period_end = '2017-12-31')\n\nprint('Saving outputs...')\n\n\nprediction_list = predictions.tolist()\nactual_list = actuals.tolist()\n\njson_preds = \"./results/lstm/multivariate/prediction.json\" \njson_actual = \"./results/lstm/multivariate/actuals.json\"\n\njson.dump(prediction_list, codecs.open(json_preds, 'w', encoding='utf-8'), sort_keys=True, indent=4)\njson.dump(actual_list, codecs.open(json_actual, 'w', encoding='utf-8'), sort_keys=True, indent=4)\n\nprint('Saved at {}'.format(json_preds))\n\n\n#cv_week_predictions(actuals, predictions, num_days=7, shift=0)\ncv_week_predictions(actuals, predictions, num_days=3*7+1, shift=0)\n","sub_path":"model_lstm_multivariate.py","file_name":"model_lstm_multivariate.py","file_ext":"py","file_size_in_byte":14748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"317918550","text":"#!/usr/bin/env python3\n\"\"\"\nCopyright (c) Facebook, Inc. and its affiliates.\nAll rights reserved.\nThis source code is licensed under the license found in the LICENSE file in the\nroot directory of this source tree.\n\n Script for converting the main SIMMC datasets (.JSON format)\n into the line-by-line stringified format (and back).\n\n The reformatted data is used as input for the GPT-2 based\n DST model baseline.\n\"\"\"\nimport json\nimport gzip\nimport pickle\nimport re\nimport os\nfrom glob import glob\n# DSTC style dataset fieldnames\nFIELDNAME_DIALOG = \"dialogue\"\nFIELDNAME_USER_UTTR = \"transcript\"\nFIELDNAME_ASST_UTTR = \"system_transcript\"\nFIELDNAME_BELIEF_STATE = \"transcript_annotated\"\nFIELDNAME_SYSTEM_STATE = \"system_transcript_annotated\"\n\n# Templates for GPT-2 formatting\nSTART_OF_MULTIMODAL_CONTEXTS = \"\"\nEND_OF_MULTIMODAL_CONTEXTS = \"\"\nSTART_BELIEF_STATE = \"=> Belief State :\"\n# START_OF_RESPONSE = \"\"\n# END_OF_BELIEF = \"\"\n# END_OF_SENTENCE = \"\"\n\nCLS_TOKEN = ''\nSEP_1_TOKEN = ''\nSEP_2_TOKEN = ''\nEND_TOKEN = ''\nTEMPLATE_PREDICT = \"{context} {START_BELIEF_STATE} \"\nTEMPLATE_TARGET = (\n \"{CLS_TOKEN} {belief_state} {SEP_2_TOKEN} {response} {END_TOKEN}\"\n)\n\n# No belief state predictions and target.\nTEMPLATE_PREDICT_NOBELIEF = \"{context} {START_OF_RESPONSE} \"\nTEMPLATE_TARGET_NOBELIEF = \"{START_OF_RESPONSE} {response} {END_OF_SENTENCE}\"\n\ndef object_id_to_meta(objects, meta_data):\n total_obj_data = list()\n each_obj_data = list()\n for obj in objects:\n # 1\n each_obj_data.append(str(obj))\n\n meta = list()\n for key, value in meta_data[int(obj)].items():\n meta.append(str(value))\n\n # color:red, pattern:stripped, type:skirt\n meta = (\", \").join(meta)\n # color: red, pattern: stripped, type: skirt\n meta = meta.replace(\":\", \": \")\n\n each_obj_data.extend(['{', meta, '}'])\n total_obj_data.append((\" \").join(each_obj_data))\n each_obj_data.clear()\n total_obj_data = (\", \").join(total_obj_data)\n return total_obj_data\n\n\ndef convert_json_to_flattened(\n input_path_json,\n output_path_predict,\n output_path_target,\n len_context=2,\n use_multimodal_contexts=True,\n use_belief_states=True,\n input_path_special_tokens=\"\",\n output_path_special_tokens=\"\",\n):\n \"\"\"\n Input: JSON representation of the dialogs\n Output: line-by-line stringified representation of each turn\n \"\"\"\n\n with open(input_path_json, \"r\") as f_in:\n data = json.load(f_in)[\"dialogue_data\"]\n\n predicts = []\n targets = []\n if input_path_special_tokens != \"\":\n with open(input_path_special_tokens, \"r\") as f_in:\n special_tokens = json.load(f_in)\n else:\n # special_tokens = {\"eos_token\": END_OF_SENTENCE}\n special_tokens = {\"eos_token\": END_TOKEN}\n additional_special_tokens = []\n # if use_belief_states:\n # additional_special_tokens.append(END_OF_BELIEF)\n # else:\n # additional_special_tokens.append(START_OF_RESPONSE)\n if use_multimodal_contexts:\n additional_special_tokens.extend(\n [START_OF_MULTIMODAL_CONTEXTS, END_OF_MULTIMODAL_CONTEXTS]\n )\n\n # BART 버전에서 추가\n additional_special_tokens.extend([CLS_TOKEN, SEP_1_TOKEN, SEP_2_TOKEN, END_TOKEN, '', '', ''])\n\n special_tokens[\"additional_special_tokens\"] = additional_special_tokens\n\n if output_path_special_tokens != \"\":\n # If a new output path for special tokens is given,\n # we track new OOVs\n oov = set()\n\n\n scene_paths = glob(\"../data/simmc2_scene_images_dstc10_teststd/*_scene.json\")\n \n with open(\"../data/fashion_prefab_metadata_all.json\", mode=\"r\") as inp:\n mata_fashion = json.load(inp)\n\n\n with open(\"../data/furniture_prefab_metadata_all.json\", mode=\"r\") as inp:\n meta_furniture = json.load(inp)\n\n # with open(\"../data/visual_meta_data_predicted.json\", mode=\"r\") as inp:\n with gzip.open(\"../data/object_teststd.pickle\", mode=\"r\") as inp:\n visual_meta = pickle.load(inp)\n\n for _, dialog in enumerate(data):\n # 현재 대화에 필요한 meta data 저장 완료\n domain = dialog['domain']\n scene_ids = [scene_id for scene_id in dialog['scene_ids'].values()] \n # scene_path = [path for path in scene_paths for ids in scene_ids if ids in path]\n scene_path = scene_ids\n # visual + non visual 위치\n\n meta_data = dict()\n\n for s_path in scene_path:\n s_name = s_path.split(\"/\")[-1].rstrip(\"_scene.json\")\n s_path = \"../data/simmc2_scene_jsons_dstc10_teststd/\" + s_name +\"_scene.json\"\n with open(s_path, mode=\"r\") as inp:\n data = json.load(inp)['scenes'][0]['objects']\n for obj in data:\n obj_name = obj[\"prefab_path\"]\n obj_idx = obj[\"index\"]\n\n meta_data[obj_idx] = dict()\n if domain == 'fashion': \n source_meta = mata_fashion\n meta_data[obj_idx]['customerReview'] = source_meta[obj_name]['customerReview']\n meta_data[obj_idx]['brand'] = source_meta[obj_name]['brand']\n meta_data[obj_idx]['size'] = source_meta[obj_name]['size']\n meta_data[obj_idx]['price'] = source_meta[obj_name]['price']\n meta_data[obj_idx]['availableSizes'] = source_meta[obj_name]['availableSizes']\n\n # print('\\n\\ns_name : {}'.format(s_name))\n # print('\\n\\nobj_idx : {} {}'.format(obj_idx, type(obj_idx)))\n # print('\\n\\nvisual_meta[s_name] : {} {}'.format(visual_meta[s_name], type(visual_meta[s_name])))\n # print('\\n\\nvisual_meta[s_name][obj_idx] : {} {}'.format(visual_meta[s_name][obj_idx], type(visual_meta[s_name][obj_idx])))\n\n if len(visual_meta[s_name][obj_idx]) > 0:\n meta_data[obj_idx]['type'] = visual_meta[s_name][obj_idx][0] # Fashion\n meta_data[obj_idx]['pattern'] = visual_meta[s_name][obj_idx][1] \n meta_data[obj_idx]['color'] = visual_meta[s_name][obj_idx][2]\n\n else: \n source_meta = meta_furniture\n meta_data[obj_idx]['customerRating'] = source_meta[obj_name]['customerRating'] \n meta_data[obj_idx]['brand'] = source_meta[obj_name]['brand'] \n meta_data[obj_idx]['price'] = source_meta[obj_name]['price']\n if len(visual_meta[s_name][obj_idx]) > 0: \n meta_data[obj_idx]['type'] = visual_meta[s_name][obj_idx][0] # Furniture\n meta_data[obj_idx]['materials'] = visual_meta[s_name][obj_idx][1]\n meta_data[obj_idx]['color'] = visual_meta[s_name][obj_idx][2]\n\n prev_asst_uttr = None\n prev_turn = None\n lst_context = []\n prev_objects_memory = list()\n\n for turn in dialog[FIELDNAME_DIALOG]:\n user_uttr = turn[FIELDNAME_USER_UTTR].replace(\"\\n\", \" \").strip()\n # user_belief = turn[FIELDNAME_BELIEF_STATE]\n if FIELDNAME_ASST_UTTR in turn:\n asst_uttr = turn[FIELDNAME_ASST_UTTR].replace(\"\\n\", \" \").strip()\n else:\n asst_uttr = \"\"\n # Format main input context\n context = \"\"\n if prev_asst_uttr:\n context += f\"System : {prev_asst_uttr} \"\n if use_multimodal_contexts:\n # Add multimodal contexts\n visual_objects = prev_turn[FIELDNAME_SYSTEM_STATE][\n \"act_attributes\"\n ][\"objects\"]\n if len(visual_objects) > 0:\n prev_objects_memory = visual_objects.copy()\n elif len(visual_objects) == 0:\n visual_objects = prev_objects_memory.copy()\n\n visual_objects = [object_id_to_meta(visual_objects, meta_data)] \n context += represent_visual_objects(visual_objects) + \" \"\n context += f\"User : {user_uttr}\"\n prev_asst_uttr = asst_uttr\n prev_turn = turn\n\n lst_context.append(context)\n context = \" \".join(lst_context[-len_context:])\n\n # Format belief state\n if use_belief_states:\n belief_state = []\n # for bs_per_frame in user_belief:\n # str_belief_state_per_frame = (\n # \"{act} {SEP_1_TOKEN} [ {slot_values} ] ({request_slots}) < {objects} >\".format(\n # act=user_belief[\"act\"].strip(),\n # SEP_1_TOKEN = SEP_1_TOKEN,\n # slot_values=\", \".join(\n # [\n # f\"{k.strip()} = {str(v).strip()}\"\n # for k, v in user_belief[\"act_attributes\"][\n # \"slot_values\"\n # ].items()\n # ]\n # ),\n # request_slots=\", \".join(\n # user_belief[\"act_attributes\"][\"request_slots\"]\n # ),\n # objects=\", \".join(\n # [str(o) for o in user_belief[\"act_attributes\"][\"objects\"]]\n # ),\n # )\n # )\n # belief_state.append(str_belief_state_per_frame)\n\n # Track OOVs\n # if output_path_special_tokens != \"\":\n # oov.add(user_belief[\"act\"])\n # for slot_name in user_belief[\"act_attributes\"][\"slot_values\"]:\n # oov.add(str(slot_name))\n # # slot_name, slot_value = kv[0].strip(), kv[1].strip()\n # # oov.add(slot_name)\n # # oov.add(slot_value)\n\n # str_belief_state = \" \".join(belief_state)\n\n # Format the main input\n predict = TEMPLATE_PREDICT.format(\n context=context,\n START_BELIEF_STATE=START_BELIEF_STATE,\n )\n predicts.append(predict)\n\n # Format the main output\n # target = TEMPLATE_TARGET.format(\n # CLS_TOKEN=CLS_TOKEN,\n # belief_state=str_belief_state,\n # SEP_2_TOKEN=SEP_2_TOKEN,\n # response=asst_uttr,\n # END_TOKEN=END_TOKEN,\n # )\n # targets.append(target)\n else:\n # Format the main input\n predict = TEMPLATE_PREDICT_NOBELIEF.format(\n context=context, START_OF_RESPONSE=START_OF_RESPONSE\n )\n predicts.append(predict)\n\n # Format the main output\n target = TEMPLATE_TARGET_NOBELIEF.format(\n response=asst_uttr,\n END_OF_SENTENCE=END_OF_SENTENCE,\n START_OF_RESPONSE=START_OF_RESPONSE,\n )\n targets.append(target)\n \n # Create a directory if it does not exist\n directory = os.path.dirname(output_path_predict)\n if not os.path.exists(directory):\n os.makedirs(directory, exist_ok=True)\n\n # directory = os.path.dirname(output_path_target)\n # if not os.path.exists(directory):\n # os.makedirs(directory, exist_ok=True)\n\n # Output into text files\n with open(output_path_predict, \"w\") as f_predict:\n X = \"\\n\".join(predicts)\n f_predict.write(X)\n\n # with open(output_path_target, \"w\") as f_target:\n # Y = \"\\n\".join(targets)\n # f_target.write(Y)\n\n if output_path_special_tokens != \"\":\n # Create a directory if it does not exist\n directory = os.path.dirname(output_path_special_tokens)\n if not os.path.exists(directory):\n os.makedirs(directory, exist_ok=True)\n\n with open(output_path_special_tokens, \"w\") as f_special_tokens:\n # Add oov's (acts and slot names, etc.) to special tokens as well\n special_tokens[\"additional_special_tokens\"].extend(list(oov))\n json.dump(special_tokens, f_special_tokens)\n\n\ndef represent_visual_objects(object_ids):\n # Stringify visual objects (JSON)\n \"\"\"\n target_attributes = ['pos', 'color', 'type', 'class_name', 'decor_style']\n\n list_str_objects = []\n for obj_name, obj in visual_objects.items():\n s = obj_name + ' :'\n for target_attribute in target_attributes:\n if target_attribute in obj:\n target_value = obj.get(target_attribute)\n if target_value == '' or target_value == []:\n pass\n else:\n s += f' {target_attribute} {str(target_value)}'\n list_str_objects.append(s)\n\n str_objects = ' '.join(list_str_objects)\n \"\"\"\n str_objects = \", \".join([str(o) for o in object_ids])\n return f\"{START_OF_MULTIMODAL_CONTEXTS} {str_objects} {END_OF_MULTIMODAL_CONTEXTS}\"\n\n\ndef parse_flattened_results_from_file(path):\n results = []\n with open(path, \"r\") as f_in:\n for line in f_in:\n parsed = parse_flattened_result(line)\n results.append(parsed)\n\n return results\n\n\ndef parse_flattened_result(to_parse):\n \"\"\"\n Parse out the belief state from the raw text.\n Return an empty list if the belief state can't be parsed\n\n Input:\n - A single of flattened result\n e.g. 'User: Show me something else => Belief State : DA:REQUEST ...'\n\n Output:\n - Parsed result in a JSON format, where the format is:\n [\n {\n 'act': # e.g. 'DA:REQUEST',\n 'slots': [\n slot_name,\n slot_value\n ]\n }, ... # End of a frame\n ] # End of a dialog\n \"\"\"\n dialog_act_regex = re.compile(\n r\"([\\w:?.?]*) *\\[([^\\]]*)\\] *\\(([^\\]]*)\\) *\\<([^\\]]*)\\>\"\n )\n slot_regex = re.compile(r\"([A-Za-z0-9_.-:]*) *= ([^,]*)\")\n request_regex = re.compile(r\"([A-Za-z0-9_.-:]+)\")\n object_regex = re.compile(r\"([A-Za-z0-9]+)\")\n\n belief = []\n\n # Parse\n splits = to_parse.strip().split(SEP_2_TOKEN)\n if len(splits) == 1: # 옳바른 응답을 생성하지 못한 경우\n # ['. ']\n d = {\n \"act\": \"\",\n \"slots\": [],\n \"request_slots\": [],\n \"objects\": [],\n }\n belief.append(d)\n return belief \n last_uttr = splits[1].strip().replace(END_TOKEN, \"\").strip()\n if len(splits) == 2:\n to_parse = splits[0].strip().replace(CLS_TOKEN, \"\").strip()\n splits = to_parse.replace(SEP_1_TOKEN,\"\").replace(\" \", \" \")\n for dialog_act in dialog_act_regex.finditer(splits):\n d = {\n \"act\": dialog_act.group(1),\n \"slots\": [],\n \"request_slots\": [],\n \"objects\": [],\n }\n\n for slot in slot_regex.finditer(dialog_act.group(2)):\n d[\"slots\"].append([slot.group(1).strip(), slot.group(2).strip()]) \n\n\n for request_slot in request_regex.finditer(dialog_act.group(3)):\n d[\"request_slots\"].append(request_slot.group(1).strip())\n\n for object_id in object_regex.finditer(dialog_act.group(4)):\n d[\"objects\"].append(object_id.group(1).strip())\n\n if d != {}:\n belief.append(d)\n\n return belief\n","sub_path":"model/mm_dst/gpt2_dst/utils/convert_BART_v5_image_100_final.py","file_name":"convert_BART_v5_image_100_final.py","file_ext":"py","file_size_in_byte":16063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"411540138","text":"import json\nfrom collections import OrderedDict\nfrom unittest import TestCase\n\nfrom cate.util.opmetainf import OpMetaInfo\nfrom cate.util.misc import object_to_qualified_name\nfrom cate.util.monitor import Monitor\n\nMONITOR = OpMetaInfo.MONITOR_INPUT_NAME\nRETURN = OpMetaInfo.RETURN_OUTPUT_NAME\n\n\nclass OpMetaInfoTest(TestCase):\n def test_init(self):\n op_meta_info = OpMetaInfo('x.y.Z')\n op_meta_info.header['description'] = 'Hello!'\n op_meta_info.input['x'] = {'data_type': str}\n op_meta_info.input['y'] = {'data_type': int}\n op_meta_info.output[RETURN] = {'data_type': str}\n\n self.assertEqual(str(op_meta_info), \"OpMetaInfo('x.y.Z')\")\n self.assertEqual(repr(op_meta_info), \"OpMetaInfo('x.y.Z')\")\n self.assertEqual(op_meta_info.qualified_name, 'x.y.Z')\n self.assertEqual(op_meta_info.has_monitor, False)\n self.assertEqual(op_meta_info.has_named_outputs, False)\n self.assertEqual(op_meta_info.can_cache, True)\n self.assertEqual(op_meta_info.header, {'description': 'Hello!'})\n self.assertEqual(OrderedDict(op_meta_info.input),\n OrderedDict([('x', {'data_type': str}), ('y', {'data_type': int})]))\n self.assertEqual(OrderedDict(op_meta_info.output),\n OrderedDict([(RETURN, {'data_type': str})]))\n\n def test_introspect_operation(self):\n # noinspection PyUnusedLocal\n def f(a: str, b: int, c: float = 1, d='A') -> float:\n \"\"\"\n The doc.\n\n :param a: the a str\n :param b: the\n b int\n :param c: the c float\n :param d:\n the d 'A'\n\n :return: a float\n \"\"\"\n\n op_meta_info = OpMetaInfo.introspect_operation(f)\n self.assertEqual(op_meta_info.qualified_name, object_to_qualified_name(f))\n self.assertEqual(op_meta_info.header, dict(description='The doc.'))\n self.assertEqual(len(op_meta_info.input), 4)\n self.assertEqual(len(op_meta_info.output), 1)\n self.assertIn('a', op_meta_info.input)\n self.assertIn('b', op_meta_info.input)\n self.assertIn('c', op_meta_info.input)\n self.assertIn('d', op_meta_info.input)\n self.assertIn(RETURN, op_meta_info.output)\n self.assertEqual(op_meta_info.input['a'], dict(data_type=str, position=0, description='the a str'))\n self.assertEqual(op_meta_info.input['b'], dict(data_type=int, position=1, description='the b int'))\n self.assertEqual(op_meta_info.input['c'], dict(data_type=float, default_value=1, description='the c float'))\n self.assertEqual(op_meta_info.input['d'], dict(default_value='A', description=\"the d 'A'\"))\n self.assertEqual(op_meta_info.output[RETURN], dict(data_type=float, description='a float'))\n self.assertEqual(op_meta_info.has_monitor, False)\n self.assertEqual(op_meta_info.has_named_outputs, False)\n self.assertEqual(op_meta_info.can_cache, True)\n\n def test_introspect_operation_with_monitor(self):\n # noinspection PyUnusedLocal\n def g(x: float, monitor: Monitor) -> float:\n \"\"\"The doc.\"\"\"\n\n op_meta_info = OpMetaInfo.introspect_operation(g)\n self.assertEqual(op_meta_info.qualified_name, object_to_qualified_name(g))\n self.assertEqual(op_meta_info.header, dict(description='The doc.'))\n self.assertEqual(len(op_meta_info.input), 1)\n self.assertEqual(len(op_meta_info.output), 1)\n self.assertIn('x', op_meta_info.input)\n self.assertNotIn(MONITOR, op_meta_info.input)\n self.assertIn(RETURN, op_meta_info.output)\n self.assertEqual(op_meta_info.input['x'], dict(data_type=float, position=0))\n self.assertEqual(op_meta_info.output[RETURN], dict(data_type=float))\n self.assertEqual(op_meta_info.has_monitor, True)\n self.assertEqual(op_meta_info.has_named_outputs, False)\n\n def test_to_json_dict(self):\n op_meta_info = OpMetaInfo('x.y.Z')\n op_meta_info.header['description'] = 'Hello!'\n op_meta_info.input['x'] = {'data_type': str}\n op_meta_info.input['y'] = {'data_type': int}\n op_meta_info.output[RETURN] = {'data_type': float}\n actual_json_dict = op_meta_info.to_json_dict()\n actual_json_text = json.dumps(actual_json_dict, indent=4)\n\n expected_json_text = \"\"\"\n {\n \"qualified_name\": \"x.y.Z\",\n \"header\": {\n \"description\": \"Hello!\"\n },\n \"input\": {\n \"x\": {\n \"data_type\": \"str\"\n },\n \"y\": {\n \"data_type\": \"int\"\n }\n },\n \"output\": {\n \"return\": {\n \"data_type\": \"float\"\n }\n }\n }\n \"\"\"\n expected_json_dict = json.loads(expected_json_text)\n\n self.assertEqual(actual_json_dict, expected_json_dict,\n msg='\\n%sexpected:\\n%s\\n%s\\nbut got:\\n%s\\n' %\n (120 * '-', expected_json_text,\n 120 * '-', actual_json_text))\n\n def test_from_json_dict(self):\n json_text = \"\"\"\n {\n \"qualified_name\": \"x.y.Z\",\n \"has_monitor\": true,\n \"header\": {\n \"description\": \"Hello!\"\n },\n \"input\": {\n \"x\": {\n \"data_type\": \"str\"\n },\n \"y\": {\n \"data_type\": \"int\"\n }\n },\n \"output\": {\n \"return\": {\n \"data_type\": \"float\"\n }\n }\n }\n \"\"\"\n json_dict = json.loads(json_text)\n\n op_meta_info = OpMetaInfo.from_json_dict(json_dict)\n self.assertEqual(op_meta_info.qualified_name, 'x.y.Z')\n self.assertEqual(op_meta_info.header, dict(description='Hello!'))\n self.assertTrue(op_meta_info.has_monitor)\n self.assertEqual(len(op_meta_info.input), 2)\n self.assertIn('x', op_meta_info.input)\n self.assertIn('y', op_meta_info.input)\n self.assertEqual(op_meta_info.input['x'], OrderedDict([('data_type', str)]))\n self.assertEqual(op_meta_info.input['y'], OrderedDict([('data_type', int)]))\n self.assertEqual(len(op_meta_info.output), 1)\n self.assertEqual(op_meta_info.output[RETURN], OrderedDict([('data_type', float)]))\n","sub_path":"test/util/test_opmetainfo.py","file_name":"test_opmetainfo.py","file_ext":"py","file_size_in_byte":6499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"371906008","text":"import torch\nimport numpy as np\n\nimport os\nimport random\nfrom tqdm import tqdm\nfrom math import sqrt\nfrom matplotlib import pyplot as plt\nimport argparse\n\n\nfrom models import *\nfrom data_loader import data_loader, get_encoder_file\nfrom config import BATCH_SIZE\n\ndef L1_dist(object1, object2):\n \"\"\"\n return L1 distance between two objects.\n Two objects must be in the same dimension\n \"\"\"\n return torch.sum(torch.abs(object1- object2)).item()\n\n\ndef L2_dist(object1, object2):\n \"\"\"\n return L2 distance between two objects.\n Two objects must be in the same dimension\n \"\"\"\n return sqrt(torch.sum((object1-object2)**2).item())\n\n\ndef feature_map_pair(enc_path1, enc_path2, enc_checkpoint):\n \"\"\"\n Taken the trained encoder as input, return a list whose element is a tuple of the image-feature map pair\n \"\"\"\n # Environment setup\n dataset = 'cifar10'\n \n \n if torch.cuda.is_available:\n batch_size = BATCH_SIZE*torch.cuda.device_count()\n device = torch.device('cuda:0')\n else:\n batch_size = BATCH_SIZE\n device = torch.device('cpu')\n\n\n # load trained encoder\n def load_encoder(enc_file,enc_checkpoint):\n encoder = Encoder()\n encoder = nn.DataParallel(encoder).to(device)\n enc_file = get_encoder_file(enc_file,enc_checkpoint)\n encoder.load_state_dict(torch.load(str(enc_file)))\n encoder.eval()\n return encoder\n encoder1 = load_encoder(enc_path1,enc_checkpoint)\n encoder2 = load_encoder(enc_path2,enc_checkpoint)\n \n\n # load test data\n _, _, test_batches, _ = data_loader(dataset, batch_size)\n\n # compute latent space for each image in test batches\n img_M1 = [] #store the image, feature map M pairs\n img_M2 = []\n test_batches = tqdm(test_batches)\n with torch.no_grad():\n for batch, labels in test_batches:\n batch = batch.to(device)\n M1, _, _ = encoder1(batch)\n M2, _, _ = encoder2(batch)\n\n # move back to cpu for faster computation\n images = batch.to(torch.device('cpu')).unbind(0)\n M1 = M1.to(torch.device('cpu')).unbind(0)\n M2 = M2.to(torch.device('cpu')).unbind(0)\n\n\n # construct and store image with its feature map as a tuple in the list\n img_M_pair1 = [pair for pair in zip(images, M1)]\n img_M_pair2 = [pair for pair in zip(images, M2)]\n img_M1 += img_M_pair1\n img_M2 += img_M_pair2\n torch.cuda.empty_cache()\n return img_M1, img_M2\n\n \ndef display(img_M,N, K):\n fig, subs = plt.subplots(N, K+1, figsize=(5,5))\n for i, sub in enumerate(subs.ravel()):\n sub.imshow(img_M[i][0].permute(1,2,0))\n sub.axis('off')\n if i==0:\n sub.set_title(\"Query\")\n plt.show()\n \n\ndef KNN(target_ids,img_M,N,K,dist='l1'):\n \"\"\"\n Task 2. un-supervised: clustering\n Compute L2 distance on the feature map of the given image and the rest of the images\n display its KNN nearest neighbors.\n\n Input:\n img_M: the image-feature map pair\n K: return the K nearest neighbors\n \"\"\"\n nearest_K=[]\n furthest_K=[]\n for img_id in target_ids:\n # Get the image and its feature map\n target_img, target_M = img_M[img_id]\n furthest_K.append(img_M[img_id])\n # Compute L2 distance and sort the list\n if dist=='l1':\n result = sorted(img_M,key=lambda pair:L1_dist(target_M, pair[1]))\n elif dist=='l2':\n result = sorted(img_M,key=lambda pair:L2_dist(target_M, pair[1]))\n else:\n raise ValueError(\"Undefined distance metric\")\n nearest_K += result[0:K+1] #the first one is the target image itself\n furthest_K += result[-K:]\n\n\n # Display the results\n display(nearest_K,N,K)\n display(furthest_K,N,K)\n\ndef random_list(n,img_M):\n target_ids = []\n for _ in range(n):\n img_id = random.randrange(0,len(img_M))\n target_ids.append(img_id)\n return target_ids\n \n\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Downstream task: clustering')\n parser.add_argument('-d', '--dist', default='l1', type=str, help='distance metric')\n parser.add_argument('-n', '--n', default=4, type=int, help='number of sample images')\n parser.add_argument('-k', '--k', default=10, type=int, help='number of nearest neighbors')\n parser.add_argument('-p1', '--enc_path1', type=str, help='folder name of the encoder model to be used under /output')\n parser.add_argument('-p2', '--enc_path2', type=str, help='folder name of the encoder model to be used under /output')\n parser.add_argument('-c', '--enc_checkpoint', type=int, help='checkpoint number to be used. E.g, 500')\n\n # loading hyper-parameters\n args = parser.parse_args()\n enc_path1 = args.enc_path1\n enc_path2 = args.enc_path2\n enc_checkpoint = args.enc_checkpoint\n dist = args.dist\n k = args.k\n n = args.n\n\n\n img_M_globalDIM, img_M_localDIM = feature_map_pair(enc_path1,enc_path2,enc_checkpoint)\n # Randomly generated a list of image ids\n target_ids = random_list(K,img_M_globalDIM)\n # Compute and display its KNN neighbor using GLOBAL only DIM\n KNN(target_ids,img_M_globalDIM, n,k,dist=dist)\n KNN(target_ids,img_M_localDIM,n,k,dist=dist)\n\n\n\n\n\n\n\n\n","sub_path":"clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":5342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"646728720","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtSvg import *\nfrom sub_widgets.Button import Button\nfrom sub_widgets.Label import Label\nfrom random import randrange\n\nclass SeatMonitoring(QWidget):\n def __init__(self, pager=None):\n super().__init__()\n self.resize(800, 480)\n self.setAttribute(Qt.WA_StyledBackground, True)\n self.pager = pager\n self.bus = QSvgRenderer('res/bus.svg')\n self.lists = [[0 for j in range(7)] for i in range(3)]\n self.setStyleSheet('SeatMonitoring { background-color: white }')\n self.colors = [QColor(0xC4C4C4), QColor(0xFF0000), QColor(0x3300FF)]\n self.createWidgets()\n\n def createWidgets(self):\n self.requestBtn = Button('수동 구조 요청', self)\n self.requestBtn.setGeometry(400,400,200,80)\n self.requestBtn.clicked.connect(self.onRequest)\n self.settingBtn = Button('설정', self)\n self.settingBtn.setGeometry(601,400,200,80)\n self.settingBtn.clicked.connect(self.onSetting)\n self.titleLabel = Label('총 착석 인원 : 10', self, 24)\n self.titleLabel.setGeometry(0,0,800,100)\n self.teamLabel = Label('전좌석 모니터링', self, 15)\n self.teamLabel.setGeometry(0,0,200,100)\n \n def paintEvent(self, event):\n qp = QPainter(self)\n self.bus.render(qp, QRectF(33, 95, 734, 290))\n #draw bus\n count = [0,0,0]\n cX = 161\n cY = [141, 233, 289]\n for i, col in enumerate(self.lists):\n for j, row in enumerate(col):\n rect = QRect(cX + j * 87, cY[i], 50, 50)\n qp.fillRect(rect, self.colors[row])\n # draw seats\n count[row] = count[row] + 1\n # count seats\n\n qp.drawLine(0, 399, 800, 399)\n qp.drawLine(600, 399, 600, 480)\n qp.drawLine(399, 400, 399, 480)\n # draw lines\n\n qp.setFont(QFont('나눔스퀘어', 13))\n state = ['미착석 : ', '미착용 : ', '착용중 : ']\n for i in range(3):\n qp.fillRect(20 + i * 120, 430, 20, 20, self.colors[i])\n qp.drawText(50 + i * 120, 445, state[i] + str(count[i]))\n # draw state\n qp.end()\n \n def changeState(self, y, x, state):\n self.lists[y][x] = state\n self.update()\n\n def onRequest(self):\n self.pager.emit(1)\n\n def onSetting(self):\n pass\n\nif __name__ == \"__main__\":\n import sys\n app = QApplication(sys.argv)\n ui = SeatMonitoring()\n ui.show()\n sys.exit(app.exec_())\n","sub_path":"SeatMonitoring.py","file_name":"SeatMonitoring.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"140671525","text":"\r\n#Exercise 11.5\r\n\r\ndef histogram(word):\r\n dictionary = dict()\r\n for letter in word:\r\n dictionary[letter] = 1 + dictionary.get(letter, 0)\r\n return dictionary\r\n\r\n\r\ndef invert_dict(d):\r\n inv = dict()\r\n for key in d:\r\n val = d[key]\r\n inv.setdefault(val, [])\r\n inv[val].append(key)\r\n return inv\r\n\r\nhist = histogram('parrot')\r\n# print hist\r\ninv = invert_dict(hist)\r\nprint (inv)\r\n\r\n","sub_path":"chapter 11/11.5.py","file_name":"11.5.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"186724126","text":"import random, os, torch, numpy as np\n\ndef seed_everything(seed=42):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n \n\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\nfrom echo.src.base_objective import BaseObjective\nfrom collections import defaultdict\nimport pandas as pd\nimport torch.fft\nimport subprocess\nimport logging\nimport shutil\nimport psutil\nimport scipy\nimport lpips\nimport copy\nimport yaml\nimport time\nimport tqdm\nimport sys\nimport gc\n\nimport segmentation_models_pytorch as smp\n\nfrom torchvision.utils import save_image\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets\nfrom torch.autograd import Variable\n\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom holodecml.data import PickleReader, UpsamplingReader, XarrayReader, XarrayReaderLabels\nfrom holodecml.propagation import InferencePropagator\nfrom holodecml.transforms import LoadTransformations\nfrom holodecml.models import load_model\nfrom holodecml.losses import load_loss\nimport sklearn, sklearn.metrics\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\"\"\"\nhttps://stats.stackexchange.com/questions/482653/what-is-the-stop-criteria-of-generative-adversarial-nets\nhttps://github.com/richzhang/PerceptualSimilarity\nhttps://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/f13aab8148bd5f15b9eb47b690496df8dadbab0c/models/networks.py\n\"\"\"\n\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\navailable_ncpus = len(psutil.Process().cpu_affinity())\n\n# Set up the GPU\nis_cuda = torch.cuda.is_available()\ndevice = torch.device(\"cpu\") if not is_cuda else torch.device(\"cuda:0\")\n\n\n# # ### Set seeds for reproducibility\n# def seed_everything(seed=1234):\n# random.seed(seed)\n# os.environ['PYTHONHASHSEED'] = str(seed)\n# np.random.seed(seed)\n# torch.manual_seed(seed)\n# if torch.cuda.is_available():\n# torch.cuda.manual_seed(seed)\n# torch.backends.cudnn.benchmark = True\n# torch.backends.cudnn.deterministic = True\n\ndef requires_grad(model, flag=True):\n for p in model.parameters():\n p.requires_grad = flag\n \n \nclass Objective(BaseObjective):\n\n def __init__(self, config, metric=\"val_loss\", device=\"cpu\"):\n\n # Initialize the base class\n BaseObjective.__init__(self, config, metric, device)\n\n def train(self, trial, conf):\n return trainer(conf, save_images = False, trial = trial)\n \n\ndef man_metrics(results, tol = 1e-8):\n result = {}\n for metric in [\"f1\", \"auc\", 'pod', \"far\", \"csi\"]: #\"man_prec\", \"man_recall\",\n if metric == 'f1':\n score = sklearn.metrics.f1_score(results[\"true\"], results[\"pred\"], average = \"weighted\")\n elif metric == 'prec':\n score = sklearn.metrics.precision_score(results[\"true\"], results[\"pred\"], average = \"weighted\")\n elif metric == 'recall':\n score = sklearn.metrics.recall_score(results[\"true\"], results[\"pred\"], average = \"weighted\")\n elif metric == 'auc':\n try:\n score = sklearn.metrics.roc_auc_score(results[\"true\"], results[\"pred\"], average = \"weighted\")\n except:\n score = 1.0\n elif metric == \"csi\":\n try:\n TN, FP, FN, TP = sklearn.metrics.confusion_matrix(results[\"true\"], results[\"pred\"]).ravel()\n score = TP / (TP + FN + FP)\n except:\n score = 1\n elif metric == 'far':\n try:\n TN, FP, FN, TP = sklearn.metrics.confusion_matrix(results[\"true\"], results[\"pred\"]).ravel()\n score = (FP + tol) / (TP + FP + tol)\n except:\n score = 1\n elif metric == 'pod':\n try:\n TN, FP, FN, TP = sklearn.metrics.confusion_matrix(results[\"true\"], results[\"pred\"]).ravel()\n score = (TP + tol) / (TP + FN + tol)\n except: \n score = 1\n result[metric] = score\n #print(metric, round(score, 3))\n return result\n\ndef apply_transforms(transforms, image):\n im = {\"image\": image}\n for image_transform in transforms:\n im = image_transform(im)\n image = im[\"image\"]\n return image\n\n \ndef trainer(conf, save_images = True, trial = False):\n \n # Set seeds for reproducibility\n seed = 1000 if \"seed\" not in conf else conf[\"seed\"]\n seed_everything(seed)\n \n save_loc = conf[\"save_loc\"]\n os.makedirs(save_loc, exist_ok = True)\n os.makedirs(os.path.join(save_loc, \"images\"), exist_ok = True)\n \n tile_size = int(conf[\"data\"][\"tile_size\"])\n step_size = int(conf[\"data\"][\"step_size\"])\n data_path = conf[\"data\"][\"output_path\"]\n data_path_raw = conf[\"data\"][\"output_path_raw\"]\n\n total_positive = int(conf[\"data\"][\"total_positive\"])\n total_negative = int(conf[\"data\"][\"total_negative\"])\n total_examples = int(conf[\"data\"][\"total_training\"])\n\n transform_mode = \"None\" if \"transform_mode\" not in conf[\"data\"] else conf[\"data\"][\"transform_mode\"]\n config_ncpus = int(conf[\"data\"][\"cores\"])\n use_cached = False if \"use_cached\" not in conf[\"data\"] else conf[\"data\"][\"use_cached\"]\n\n name_tag = f\"{tile_size}_{step_size}_{total_positive}_{total_negative}_{total_examples}_{transform_mode}\"\n fn_train = f\"{data_path}/training_{name_tag}.nc\"\n fn_valid = f\"{data_path}/validation_{name_tag}.nc\"\n fn_train_raw = data_path_raw#f\"{data_path_raw}/training_{name_tag}.nc\"\n fn_valid_raw = f\"{data_path_raw}/validation_{name_tag}.nc\"\n\n # Trainer params\n train_batch_size = conf[\"trainer\"][\"train_batch_size\"]\n valid_batch_size = conf[\"trainer\"][\"valid_batch_size\"]\n \n epochs = conf[\"trainer\"][\"epochs\"]\n batches_per_epoch = conf[\"trainer\"][\"batches_per_epoch\"]\n Tensor = torch.cuda.FloatTensor if is_cuda else torch.FloatTensor\n adv_loss = conf[\"trainer\"][\"adv_loss\"]\n lambda_gp = conf[\"trainer\"][\"lambda_gp\"]\n train_gen_every = conf[\"trainer\"][\"train_gen_every\"]\n train_disc_every = conf[\"trainer\"][\"train_disc_every\"]\n threshold = conf[\"trainer\"][\"threshold\"]\n mask_penalty = conf[\"trainer\"][\"mask_penalty\"]\n regression_penalty = conf[\"trainer\"][\"regression_penalty\"]\n stopping_patience = conf[\"trainer\"][\"stopping_patience\"]\n\n # Load the preprocessing transforms\n if \"Normalize\" in conf[\"transforms\"][\"training\"]:\n conf[\"transforms\"][\"validation\"][\"Normalize\"][\"mode\"] = conf[\"transforms\"][\"training\"][\"Normalize\"][\"mode\"]\n conf[\"transforms\"][\"inference\"][\"Normalize\"][\"mode\"] = conf[\"transforms\"][\"training\"][\"Normalize\"][\"mode\"]\n\n train_transforms = LoadTransformations(conf[\"transforms\"][\"training\"])\n valid_transforms = LoadTransformations(conf[\"transforms\"][\"validation\"])\n\n train_synthetic_dataset = XarrayReader(fn_train, train_transforms)\n #test_synthetic_dataset = XarrayReader(fn_valid, valid_transforms)\n\n train_synthetic_loader = torch.utils.data.DataLoader(\n train_synthetic_dataset,\n batch_size=train_batch_size,\n num_workers=available_ncpus//2,\n pin_memory=True,\n shuffle=True)\n\n# test_synthetic_loader = torch.utils.data.DataLoader(\n# test_synthetic_dataset,\n# batch_size=valid_batch_size,\n# num_workers=0, # 0 = One worker with the main process\n# pin_memory=True,\n# shuffle=False)\n\n train_holodec_dataset = XarrayReaderLabels(fn_train_raw, train_transforms)\n #test_holodec_dataset = XarrayReader(fn_valid_raw, valid_transforms)\n\n train_holodec_loader = torch.utils.data.DataLoader(\n train_holodec_dataset,\n batch_size=train_batch_size,\n num_workers=available_ncpus//2,\n pin_memory=True,\n shuffle=True)\n\n# test_holodec_loader = torch.utils.data.DataLoader(\n# test_holodec_dataset,\n# batch_size=valid_batch_size,\n# num_workers=0, # 0 = One worker with the main process\n# pin_memory=True,\n# shuffle=False)\n\n # Load the models\n generator = load_model(conf[\"generator\"]).to(device)\n discriminator = load_model(conf[\"discriminator\"]).to(device)\n model = load_model(conf[\"model\"]).to(device)\n\n # Load loss function\n adv_loss = conf[\"trainer\"][\"adv_loss\"]\n if adv_loss == \"bce\":\n adversarial_loss = torch.nn.BCELoss().to(device)\n \n # Load perceptual-alex-net as the metric\n perceptual_alex = lpips.LPIPS(net='alex').to(device)\n # Load mask loss\n Mask_Loss = load_loss(\"focal-tyversky\")\n\n # Load the optimizers\n optimizer_G = torch.optim.Adam(\n filter(lambda p: p.requires_grad, generator.parameters()),\n lr = conf[\"optimizer_G\"][\"learning_rate\"],\n betas = (conf[\"optimizer_G\"][\"b0\"], conf[\"optimizer_G\"][\"b1\"]))\n \n optimizer_D = torch.optim.Adam(\n filter(lambda p: p.requires_grad, discriminator.parameters()), \n lr = conf[\"optimizer_D\"][\"learning_rate\"], \n betas = (conf[\"optimizer_D\"][\"b0\"], conf[\"optimizer_D\"][\"b1\"]))\n \n optimizer_M = torch.optim.Adam(\n filter(lambda p: p.requires_grad, model.parameters()), \n lr = conf[\"optimizer_M\"][\"learning_rate\"], \n betas = (conf[\"optimizer_M\"][\"b0\"], conf[\"optimizer_M\"][\"b1\"]))\n \n # Anneal the learning rate\n lr_G_decay = torch.optim.lr_scheduler.StepLR(optimizer_G, step_size=10, gamma=0.2)\n lr_D_decay = torch.optim.lr_scheduler.StepLR(optimizer_D, step_size=10, gamma=0.2)\n lr_M_decay = torch.optim.lr_scheduler.StepLR(optimizer_M, step_size=10, gamma=0.2)\n\n results = defaultdict(list)\n for epoch in range(epochs):\n\n ### Train\n real_images = iter(train_holodec_loader)\n synthethic_images = iter(train_synthetic_loader)\n dual_iter = tqdm.tqdm(\n enumerate(zip(real_images, synthethic_images)),\n total = batches_per_epoch, \n leave = True)\n\n train_results = defaultdict(list)\n for i, ((holo_img, holo_label), (synth_img, synth_label)) in dual_iter:\n\n if holo_img.shape[0] != synth_img.shape[0]:\n continue\n\n # Adversarial ground truths\n valid = Variable(Tensor(holo_img.size(0), 1).fill_(1.0), requires_grad=False)\n fake = Variable(Tensor(holo_img.size(0), 1).fill_(0.0), requires_grad=False)\n\n # Configure input\n real_imgs = Variable(holo_img.type(Tensor))\n synthethic_imgs = Variable(synth_img.type(Tensor))\n \n # Sample noise as generator input\n z = Variable(Tensor(np.random.normal(0, 1.0, holo_img.shape)))\n # C-GAN-like input using the synthethic image as conditional input\n gen_input = torch.cat([synthethic_imgs, z], 1)\n # Generate a batch of images\n gen_imgs = generator(gen_input)\n # Add to the synthetic images\n # Discriminate the fake images\n _, verdict = discriminator(gen_imgs)\n \n # -----------------\n # Train mask model\n # -----------------\n\n optimizer_M.zero_grad()\n requires_grad(model, True)\n pred_masks = model(gen_imgs.detach())\n mask_loss = Mask_Loss(pred_masks, synth_label.to(device))\n train_results[\"mask_loss\"].append(mask_loss.item())\n mask_loss.backward()\n optimizer_M.step()\n requires_grad(model, False)\n\n # -----------------\n # Train Generator\n # -----------------\n\n if (i + 1) % train_gen_every == 0 or i == 0:\n\n optimizer_G.zero_grad()\n requires_grad(generator, True)\n requires_grad(discriminator, False)\n\n # Loss measures generator's ability to fool the discriminator\n if adv_loss == 'wgan-gp':\n g_loss = -verdict.mean()\n elif adv_loss == 'hinge':\n g_loss = -verdict.mean()\n elif adv_loss == 'bce':\n g_loss = adversarial_loss(verdict, valid)\n\n\n # compute L1/L2 reg term\n# mask = synth_label.to(device).bool()\n# reg_loss = torch.nn.MSELoss()(\n# torch.masked_select(gen_imgs, mask),\n# torch.masked_select(synthethic_imgs, mask)\n# )\n \n mask = synth_label.to(device)\n reg_loss = torch.nn.MSELoss()(gen_imgs, synthethic_imgs)\n \n train_results[\"g_reg\"].append(reg_loss.item())\n g_loss += regression_penalty * reg_loss\n\n # compute mask loss reg term\n #pred_masks, _ = model(gen_imgs)\n mask_loss = Mask_Loss(pred_masks.detach(), synth_label.to(device))\n #train_results[\"fake_mask_loss\"].append(mask_loss.item())\n g_loss += mask_penalty * mask_loss\n train_results[\"g_loss\"].append(g_loss.item())\n\n g_loss.backward()\n optimizer_G.step()\n\n # compute perception scores\n p_score_syn = perceptual_alex(gen_imgs, synthethic_imgs).mean()\n p_score_real = perceptual_alex(gen_imgs, real_imgs).mean()\n train_results[\"p_syn\"].append(p_score_syn.item())\n train_results[\"p_real\"].append(p_score_real.item())\n\n # ---------------------\n # Train Discriminator\n # ---------------------\n\n if (i + 1) % train_disc_every == 0 or i == 0:\n\n optimizer_D.zero_grad()\n requires_grad(generator, False)\n requires_grad(discriminator, True)\n\n # Measure discriminator's ability to classify real from generated samples\n _, disc_real = discriminator(real_imgs)\n _, disc_synth = discriminator(gen_imgs.detach())\n _, disc_synth_true = discriminator(synthethic_imgs)\n\n train_results[\"real_acc\"].append(((disc_real > threshold) == valid).float().mean().item())\n train_results[\"syn_acc\"].append(((disc_synth > threshold) == fake).float().mean().item())\n train_results[\"syn_true_acc\"].append(((disc_synth_true > threshold) == valid).float().mean().item())\n\n if adv_loss == 'wgan-gp':\n real_loss = -torch.mean(disc_real) \n fake_loss = disc_synth.mean() \n elif adv_loss == 'hinge':\n real_loss = torch.nn.ReLU()(1.0 - disc_real).mean() \n fake_loss = torch.nn.ReLU()(1.0 + disc_synth).mean() \n elif adv_loss == 'bce':\n real_loss = adversarial_loss(disc_real, valid) \n fake_loss = adversarial_loss(disc_synth, fake) \n\n d_loss = real_loss + fake_loss \n train_results[\"d_loss\"].append(d_loss.item())\n\n if adv_loss == 'wgan-gp':\n # Compute gradient penalty\n alpha = torch.rand(real_imgs.size(0), 1, 1, 1).cuda().expand_as(real_imgs)\n interpolated = Variable(alpha * real_imgs.data + (1 - alpha) * gen_imgs.data, requires_grad=True)\n out = discriminator(interpolated)[1]\n\n grad = torch.autograd.grad(outputs=out,\n inputs=interpolated,\n grad_outputs=torch.ones(out.size()).cuda(),\n retain_graph=True,\n create_graph=True,\n only_inputs=True)[0]\n\n grad = grad.view(grad.size(0), -1)\n grad_l2norm = torch.sqrt(torch.sum(grad ** 2, dim=1))\n d_loss_gp = torch.mean((grad_l2norm - 1) ** 2)\n d_loss_reg = lambda_gp * d_loss_gp\n d_loss += d_loss_reg\n train_results[\"d_reg\"].append(d_loss_reg.item())\n\n d_loss.backward()\n optimizer_D.step()\n \n\n print_str = f'Epoch {epoch}'\n print_str += f' D_loss {np.mean(train_results[\"d_loss\"]):.6f}'\n if adv_loss == 'wgan-gp':\n print_str += f' D_reg {np.mean(train_results[\"d_reg\"]):.6f}'\n print_str += f' G_loss {np.mean(train_results[\"g_loss\"]):6f}'\n print_str += f' G_reg {np.mean(train_results[\"g_reg\"]):6f}'\n print_str += f' mask_loss {np.mean(train_results[\"mask_loss\"]):6f}'\n #print_str += f' fake_mask_loss {np.mean(train_results[\"fake_mask_loss\"]):6f}'\n print_str += f' h_acc {np.mean(train_results[\"real_acc\"]):.4f}'\n print_str += f' f_acc {np.mean(train_results[\"syn_acc\"]):.4f}'\n print_str += f' s_acc {np.mean(train_results[\"syn_true_acc\"]):.4f}'\n print_str += f' p_syn {np.mean(train_results[\"p_syn\"]):.4f}'\n print_str += f' p_real {np.mean(train_results[\"p_real\"]):.4f}'\n dual_iter.set_description(print_str)\n dual_iter.refresh()\n\n if i == batches_per_epoch and i > 0:\n break\n\n # Epoch is over. Save some stuff.\n if save_images:\n save_image(synthethic_imgs.data[:16], f'{conf[\"save_loc\"]}/images/synth_{epoch}.png', nrow=4, normalize=True)\n save_image(real_imgs.data[:16], f'{conf[\"save_loc\"]}/images/real_{epoch}.png', nrow=4, normalize=True)\n save_image(gen_imgs.data[:16], f'{conf[\"save_loc\"]}/images/pred_{epoch}.png', nrow=4, normalize=True)\n #save_image(gen_noise.data[:16], f\"../results/gan/images/noise_{epoch}.png\", nrow=4, normalize=True)\n\n # Save the dataframe to disk\n results[\"epoch\"].append(epoch)\n results[\"d_loss\"].append(np.mean(train_results[\"d_loss\"]))\n if adv_loss == 'wgan-gp':\n results[\"d_loss_reg\"].append(np.mean(train_results[\"d_reg\"]))\n results[\"g_loss\"].append(np.mean(train_results[\"g_loss\"]))\n results[\"g_reg\"].append(np.mean(train_results[\"g_reg\"]))\n results[\"mask_loss\"].append(np.mean(train_results[\"mask_loss\"]))\n #results[\"fake_mask_loss\"].append(np.mean(train_results[\"fake_mask_loss\"]))\n results[\"holo_acc\"].append(np.mean(train_results[\"real_acc\"]))\n results[\"fake_acc\"].append(np.mean(train_results[\"syn_acc\"]))\n results[\"synth_acc\"].append(np.mean(train_results[\"syn_true_acc\"]))\n results[\"perception_syn\"].append(np.mean(train_results[\"p_syn\"]))\n results[\"perception_holo\"].append(np.mean(train_results[\"p_real\"]))\n \n metric = \"custom\"\n metric_value = results[\"mask_loss\"][-1] + results[\"perception_holo\"][-1]\n results[metric].append(metric_value)\n \n # Validate \n requires_grad(model, False)\n inputs = torch.from_numpy(np.load(os.path.join(\n data_path, f'manual_images_{transform_mode}_test.npy'))).float()\n labels = torch.from_numpy(np.load(os.path.join(\n data_path, f'manual_labels_{transform_mode}_test.npy'))).float()\n inputs = torch.from_numpy(np.expand_dims(\n np.vstack([apply_transforms(valid_transforms, x) for x in inputs.numpy()]), 1))\n\n results_dict_set1 = defaultdict(list)\n my_iter = enumerate(zip(inputs, labels))\n for k, (x, y) in my_iter:\n pred_label = model(x.unsqueeze(0).to(device))\n arr, n = scipy.ndimage.label(pred_label.cpu() > 0.5)\n centroid = scipy.ndimage.find_objects(arr)\n pred_label = len(centroid)\n if pred_label > 0 and pred_label < 10000:\n pred_label = 1\n else:\n pred_label = 0\n results_dict_set1[\"pred\"].append(pred_label)\n results_dict_set1[\"true\"].append(y[0].item())\n #mets = man_metrics(results_dict_set1)\n #f1, pod, far, csi = mets[\"f1\"], mets[\"pod\"], mets[\"far\"], mets[\"csi\"]\n #my_iter.set_description(f\"Epoch {epoch} F1: {f1:.3f} POD: {pod:.3f} FAR: {far:.3f} CSI: {csi:3f}\")\n #my_iter.refresh()\n mets = man_metrics(results_dict_set1)\n f1, pod, far, csi = mets[\"f1\"], mets[\"pod\"], mets[\"far\"], mets[\"csi\"]\n results[\"man_f1\"].append(f1)\n results[\"man_pod\"].append(pod)\n results[\"man_far\"].append(far)\n results[\"man_csi\"].append(csi)\n \n if save_images:\n try:\n df = pd.DataFrame.from_dict(results).reset_index()\n df.to_csv(f'{conf[\"save_loc\"]}/training_log.csv', index=False)\n except:\n print(results)\n raise\n\n # Save the model\n if metric_value == min(results[metric]):\n state_dict = {\n 'epoch': epoch,\n 'discriminator_state_dict': discriminator.state_dict(),\n 'optimizer_D_state_dict': optimizer_D.state_dict(),\n 'generator_state_dict': generator.state_dict(),\n 'optimizer_G_state_dict': optimizer_G.state_dict(),\n 'model_state_dict': model.state_dict(),\n 'model_optimizer_state_dict': optimizer_M.state_dict(),\n }\n torch.save(state_dict, f'{conf[\"save_loc\"]}/best.pt')\n \n # Update optuna trial if using ECHO\n if trial:\n # Report result to the trial\n attempt = 0\n while attempt < 10:\n try:\n trial.report(metric_value, step=epoch)\n break\n except Exception as E:\n logging.warning(\n f\"WARNING failed to update the trial with metric {metric} at epoch {epoch}. Error {str(E)}\")\n logging.warning(f\"Trying again ... {attempt + 1} / 10\")\n time.sleep(1)\n attempt += 1\n \n # Stop training if we have not improved after X epochs (stopping patience)\n best_epoch = [i for i, j in enumerate(\n results[metric]) if j == min(results[metric])][0]\n offset = epoch - best_epoch\n if offset >= stopping_patience:\n logging.info(f\"Trial {trial.number} is stopping early after {stopping_patience} epochs.\")\n break\n \n # Anneal learning rates \n lr_G_decay.step(epoch)\n lr_D_decay.step(epoch)\n lr_M_decay.step(epoch)\n \n if trial:\n trial_id = trial.number\n save_image(synthethic_imgs.data[:8], f'{conf[\"save_loc\"]}/images/synth_{trial_id}.png', nrow=2, normalize=True)\n save_image(real_imgs.data[:8], f'{conf[\"save_loc\"]}/images/real_{trial_id}.png', nrow=2, normalize=True)\n save_image(gen_imgs.data[:8], f'{conf[\"save_loc\"]}/images/pred_{trial_id}.png', nrow=2, normalize=True)\n \n result_dict = {\n \"epoch\": best_epoch,\n #\"combined_perception\": results[\"combined_perception\"][best_epoch],\n \"holodec_perception\": results[\"perception_holo\"][best_epoch],\n \"synthetic_perception\": results[\"perception_syn\"][best_epoch],\n \"mask_loss\": results[\"mask_loss\"][best_epoch],\n #\"fake_mask_loss\": results[\"fake_mask_loss\"][best_epoch],\n \"man_f1\": results[\"man_f1\"][best_epoch],\n \"man_pod\": results[\"man_pod\"][best_epoch],\n \"man_far\": results[\"man_far\"][best_epoch], \n \"man_csi\": results[\"man_csi\"][best_epoch],\n metric: results[metric][best_epoch]\n }\n \n return result_dict\n\n \nif __name__ == '__main__':\n\n if len(sys.argv) != 2:\n print(\"Usage: python gan.py config.yml\")\n sys.exit()\n\n # ### Set up logger to print stuff\n root = logging.getLogger()\n root.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(levelname)s:%(name)s:%(message)s')\n\n # Stream output to stdout\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n ch.setFormatter(formatter)\n root.addHandler(ch)\n \n # ### Load the configuration and get the relevant variables\n config = sys.argv[1]\n with open(config) as cf:\n conf = yaml.load(cf, Loader=yaml.FullLoader)\n \n # Set seeds for reproducibility\n #seed = 1000 if \"seed\" not in conf else conf[\"seed\"]\n #seed_everything()\n \n save_loc = conf[\"save_loc\"]\n os.makedirs(save_loc, exist_ok = True)\n os.makedirs(os.path.join(save_loc, \"images\"), exist_ok = True)\n if not os.path.isfile(os.path.join(save_loc, \"model.yml\")):\n shutil.copyfile(config, os.path.join(save_loc, \"model.yml\"), exist_ok = True) \n result = trainer(conf, save_images = True)","sub_path":"applications/gan.py","file_name":"gan.py","file_ext":"py","file_size_in_byte":24831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"202266582","text":"#!/usr/bin/env python3\n\n# ----------------------------------------------------------\n\nimport collections\nimport itertools\n\nimport boto3\nimport csv\nimport json \n\nimport operator\nimport random\n\nMY_ACCESS_KEY_ID = ''\nMY_SECRET_ACCESS_KEY = '/'\n\n# request to add user to db\n\t# check db for user\n\t\t# user is already in db\n\t\t\t# respond with 'thanks, you're already signed up'\n\t\t\t# send another email for the invite\n\t\t# user is not in db\n\t\t\t# add user to db\n\t\t\t# send invite to latest lunch\n# request to remove user from db\n\t# check db for user\n\t\t# user is already removed from db\n\t\t\t# respond with 'user removed'\n\t\t# user is in db\n\t\t\t# remove user from db\n\t\t\t# send confirmation\n# update user info in db\n\t# check for user in db\n\t\t# user not in db\n\t\t\t# repond 'user not found'\n\t\t# user in db\n\t\t\t# update info (job etc)\n\n# doro launches lunch date\n\t# email sent out \n\t\t# user doesn't respond\n\t\t\t# user remains in the user db\n\t# user responds\n\t\t# user added to new db of potential lunchees\n\t\t\t# after cutoff date groups are formed\n\t\t\t\t# each group added to a new db\n\t\t\t\t\t# saved info:\n\t\t\t\t\t\t\t# users in group\n\t\t\t\t\t\t\t# date of lunch\n\t\t\t\t# each group recieves an email with location infomation\n\n\n\n# db users\n# ask users\n# db attendees\n\n\ndef get_csv_file_from_s3(self):\n\n\treturn fakedata.csv\n\ndef csv_json_parser(self):\n\t\n\tget_csv_file_from_s3()\n\t# Pass the file to function either open locally of via lambda\n\t# csvfile = csvfile\n\n\t# Open CSV\n\ttarget = open('fakedata.csv', 'rU')\n\n\t# List the column names\n\treader = csv.DictReader(target, fieldnames=(\"numberID\", \"name\", \"email\", \"title\", \"team\")) \n\n\t# Parse CSV into JSON \n\tout = json.dumps([row for row in reader]) \n\n\t# Save JSON \n\topen('csv_parsed_data.json', 'w').write(out) \n\n# ----------------------------------------------------------\n#\n# Read from the CSV file and save the info to be acted upon\n# \n# ----------------------------------------------------------\n\nopen_csv = open('data.csv', 'r')\ndata_dump = csv.reader(open_csv, delimiter = \";\")\n\nbig_group = []\n\nfor row in data_dump:\n big_group.append(row)\n\n# set the group size for lunches\ngroup_size = 4\ngroup_count = len(big_group) // group_size\n\n# create job pools to build groups from\nProgram_Manager \t\t\t= []\nRnD_Manager\t\t\t\t\t= []\nPrincipal_Software_Engineer = []\nProduct_Manager\t\t\t\t= []\nEngineer \t\t\t\t\t= []\nHR_Consultant \t\t\t\t= []\nDirector_Business_Solutions = []\nVisual_Designer \t\t\t= []\nMgr_Program_Management \t\t= []\nSoftware_Engineer \t\t\t= []\nMgr_Quality_Improvement \t= []\nUX_Designer \t\t\t\t= []\nPrincipal_Architect \t\t= []\nEmployee_Comms_Specialist \t= []\nCartography_Designer \t\t= []\nQA_engineer \t\t\t\t= []\n\n\nfor each_person in big_group:\n\n\tjob = each_person[3]\n\n\tif \"Program Manager\" in job:\n\t\tProgram_Manager.append(each_person)\n\telif \"R&D Manager\" in job:\n\t\tRnD_Manager.append(each_person)\n\telif \"Principal Software Engineer\" in job:\n\t\tPrincipal_Software_Engineer.append(each_person)\n\telif \"Product Manager\" in job:\n\t\tProduct_Manager.append(each_person)\n\telif \"Software Engineer\" in job:\n\t\tSoftware_Engineer.append(each_person)\n\telif \"QA engineer\" in job:\n\t\tQA_engineer.append(each_person)\n\telif \"Engineer\" in job:\n\t\tEngineer.append(each_person)\n\telif \"HR Consultant\" in job:\n\t\tHR_Consultant.append(each_person)\n\telif \"Director Business Solutions\" in job:\n\t\tDirector_Business_Solutions.append(each_person)\n\telif \"Visual Designer\" in job:\n\t\tVisual_Designer.append(each_person)\n\telif \"Mgr Program Management\" in job:\n\t\tMgr_Program_Management.append(each_person)\n\telif \"Mgr Quality Improvement\" in job:\n\t\tMgr_Quality_Improvement.append(each_person)\n\telif \"UX Designer\" in job:\n\t\tUX_Designer.append(each_person)\n\telif \"Principal Architect\" in job:\n\t\tPrincipal_Architect.append(each_person)\n\telif \"Employee Comms Specialist\" in job:\n\t\tEmployee_Comms_Specialist.append(each_person)\n\telif \"Cartography Designer\" in job:\n\t\tCartography_Designer.append(each_person)\n\telse:\n\t\tpass\n\nlarge_group = [Program_Manager,\n\t\t\t\tRnD_Manager,\n\t\t\t\tPrincipal_Software_Engineer,\n\t\t\t\tProduct_Manager,\n\t\t\t\tEngineer,\n\t\t\t\tHR_Consultant,\n\t\t\t\tDirector_Business_Solutions,\n\t\t\t\tVisual_Designer,\n\t\t\t\tMgr_Program_Management,\n\t\t\t\tSoftware_Engineer,\n\t\t\t\tMgr_Quality_Improvement,\n\t\t\t\tUX_Designer,\n\t\t\t\tPrincipal_Architect,\n\t\t\t\tEmployee_Comms_Specialist,\n\t\t\t\tCartography_Designer,\n\t\t\t\tQA_engineer\n\t\t\t\t]\n\n\ndef weighting(given_collection_of_job_groups):\n\n\ttotal_people = 0\n\tcount = 1\n\tweights = []\n\n\tfor each_job_group in given_collection_of_job_groups:\n\t\ttotal_people += len(each_job_group)\n\t\tif len(each_job_group) > 0:\n\t\t\tweights.append(.01*(int(len(each_job_group)/total_people*100)))\n\t\t\tcount += 1\n\t\telse:\n\t\t\tpass\n\t\n\treturn weights\n\nlist_of_lunch_groups = []\n\nfor x in range(len(big_group) // group_size):\n\tlist_of_lunch_groups.append([])\n\n#-------------------------------------------------------\n# populate each of the lunch groups using the random\n# selection method, applying the weighted distributions\n\nfor z in range(group_size):\n\tfor each_lunch_group in list_of_lunch_groups:\n\t\tgotchya = random.choices(large_group, weighting(large_group))[0]\n\t\tnowwhat = gotchya.pop(0)\n\t\teach_lunch_group.append(nowwhat)\n\t\t# remove empty groups from the large_group list\n\t\tlarge_group2 = [x for x in large_group if x != []]\n\t\tlarge_group = large_group2\n\n\n#-------------------------------------------------------\n# print the groups to eyeball for errors\n\nfor x in large_group:\n\tremainer = x.pop(0)\n\tlist_of_lunch_groups[0].append(remainer)\n\nfor x in list_of_lunch_groups:\n\tfor z in x:\n\t\tprint(z)\n\tprint(\"\\n\")\n\n#-------------------------------------------------------\n\ndef copy_lunchees_to_attendee_database(self, lunchees):\n # check to see if user is in database already\n # add userdata to database\n pass\n\ndef send_out_meeting_point_emails_to_each_group(self, groups_list):\n for each_group in groups_list:\n # create email from template\n # assign a pre-selected meeting point from lists\n # extract 4 email addresses from the group data\n # target the email addresses\n pass\n","sub_path":"clean_group_maker.py","file_name":"clean_group_maker.py","file_ext":"py","file_size_in_byte":5976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"546975307","text":"from helpers.helpers_functions import *\nimport pytest\nimport requests\n\n\n@pytest.mark.parametrize(('symbol'), LIST_OF_ARGVALUES[0:20])\ndef test_trades_response(symbol):\n response = make_request(create_endpoint('trades/t{}/hist'.format(symbol)))\n response_time = get_response_time(response)\n\n headers_data = get_response_headers(response)\n content_type = get_json_from_asset(os.path.abspath('assets/content_type.json'))\n body = get_response_body(response)\n write_response_to_a_file(response, \"resp_text4.txt\")\n\n assert response.ok\n assert response_time < 300\n assert headers_data['Content-Type'] == content_type['Content-Type']\n assert isinstance(body, list) # not empty\n assert len(body) != 0\n\n for i in range(0, len(body)):\n for j in range(1, len(body[i])):\n field_type = (type(body[i][j]))\n assert field_type == int or field_type == float","sub_path":"endpoints/trades/test_trades.py","file_name":"test_trades.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"8064737","text":"\"\"\"\r\nExperimental code that will convert from BMP format to GBA\r\n\r\neach block is 8x8\r\nit's \"4bpp\", so each byte has two pixel\r\neach pixel is an index in the palette\r\n\r\n\"\"\"\r\nfrom PIL import Image\r\nimport random\r\n\r\nimg = Image.open(\"graphics/licensed.png\")\r\n\r\npixels = img.load()\r\n\r\nwidth, height = img.size\r\n\r\ngba_gfx = [0] * int((width * height) / 2)\r\n\r\nz = 0x0\r\nv = 0x0\r\n\r\ndebug = 0\r\nwhile z < int((width * height) / 2):\r\n\tfor i in range(0x0, 0x8):\r\n\t\tfor j in range(0, 0x4):\r\n\t\t\tdata_1 = int(pixels[(j*2)+v,i][0] / 80)\r\n\t\t\tdata_2 = int(pixels[(j*2+1)+v,i][0] / 80)\r\n\r\n\t\t\tpixel = (data_2 << 0x4) | data_1\r\n\r\n\t\t\tgba_gfx[z + (i*4) + j] = pixel\r\n\r\n\tv += 0x8\r\n\tz += 0x20\r\n\r\nf = open(\"graphics/licensed_by_nintendo_gfx.bin\", \"wb\")\r\nf.write(bytes(gba_gfx))\r\nf.close()\r\n","sub_path":"tools/png_to_gfx.py","file_name":"png_to_gfx.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"334507025","text":"#!/usr/bin/python\n\"\"\"\n Author: Fabio Hellmann \n\"\"\"\n\nimport logging\nfrom flask import Blueprint\nfrom flask_restplus import Api\nfrom app.api.api_radiofrequency import ns_rf\nfrom app.api.api_thermometer import ns_tm\nfrom app.api.api_thermostat import ns_ts\n\n_LOGGER = logging.getLogger(__name__)\n\nrest_api = Blueprint('api', __name__)\n\napi = Api(\n rest_api,\n version='0.2',\n title='My Smart Home - Rest API',\n description='The rest api allows to access all the sensor data and control the actuators.',\n contact_email='info@fabio-hellmann.de'\n)\napi.add_namespace(ns_rf)\napi.add_namespace(ns_tm)\napi.add_namespace(ns_ts)\n\n\n@api.errorhandler\ndef default_error_handler(e: Exception):\n _LOGGER.exception('An unhandled exception occurred.')\n\n\ndef register_blueprints(app):\n app.register_blueprint(rest_api, url_prefix='/api')\n","sub_path":"app/api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"105066660","text":"import logging\nimport webapp2\nimport math\n\nfrom google.appengine.api import images\nfrom google.appengine.ext import db\n\nfrom cache_controller import CacheController\nfrom model_choosie_post import ChoosiePost\nfrom model_user import User\nfrom utils import Utils\n\nclass PostsHandler(webapp2.RequestHandler):\n def shrinkImage(self, data):\n img = images.Image(data)\n max_width = 800\n max_height = 800\n logging.info(\"width-\" + str(img.width))\n logging.info(\"height-\" + str(img.height))\n ratio = math.ceil(min(float(max_width)/float(img.width), float(max_height)/float(img.height)))\n if ratio < 1.0:\n logging.info(\"ratio:\" + str(ratio))\n # Only shrink the image: if it is already smaller than 800px on both axes\n # do nothing.\n img.resize(width=ratio*img.width, height=ratio*img.height)\n img.im_feeling_lucky()\n return img.execute_transforms(output_encoding=images.PNG)\n\n def post(self):\n user = CacheController.get_user_by_fb_id(self.request.get('fb_uid'))\n logging.info(self.request.get('fb_uid'))\n if user is None:\n self.error(500)\n logging.error(\"user not found!\")\n return\n\n logging.info(\"user found!\")\n logging.info(\"share_to_fb_param: \" + self.request.get(\"share_to_fb\", default_value=\"off\"))\n debug_show_fb = self.request.get(\"debug_show_fb\", default_value=\"\")\n logging.info(\"debug_show_fb: \" + debug_show_fb)\n \n post_type_id = int(self.request.get(\"post_type_id\", default_value=\"1\"))\n\n if debug_show_fb:\n img1 = images.Image(self.shrinkImage(self.request.get('photo1')))\n img2 = images.Image(self.shrinkImage(self.request.get('photo2')))\n self.response.headers['Content-Type'] = 'image/png'\n self.response.out.write(Utils.compose_two_images(img1, img2))\n return\n\n if self.request.get(\"share_to_fb\", default_value=\"off\") == \"on\":\n logging.info(\"user\" + user.fb_access_token)\n logging.info(\"user_db\" + str(self.request.get('fb_access_token')))\n logging.info(\"key \" + str(user.key()))\n # updating user access token cause he might added publish_stream permission\n if user.fb_access_token != str(self.request.get('fb_access_token')):\n logging.info(\"Changing access_token!\")\n user.fb_access_token = str(self.request.get('fb_access_token'))\n user.fb_access_token_expdate = Utils.get_access_token_from_request(self.request)\n user.put()\n CacheController.invalidate_user_fb_id(user.fb_uid)\n\n if user.num_votes:\n user.num_votes += 1\n else:\n user.num_votes = 1\n user.put()\n CacheController.invalidate_user_fb_id(user.fb_uid)\n photo1_blob_key = Utils.write_file_to_blobstore(self.shrinkImage(self.request.get('photo1')))\n if post_type_id == 1:\n photo2_blob_key = Utils.write_file_to_blobstore(self.shrinkImage(self.request.get('photo2')))\n else:\n photo2_blob_key = None\n choosie_post = ChoosiePost(question = self.request.get('question'),\n user_fb_id = self.request.get('fb_uid'),\n photo1_blob_key = photo1_blob_key,\n photo2_blob_key = photo2_blob_key,\n post_type_id = post_type_id)\n\n # Save this post in the datastore, and also in the memcache.\n choosie_post.put()\n CacheController.set_model(choosie_post)\n logging.info(\"share:\" + self.request.get(\"share_to_fb\", default_value=\"off\"))\n if self.request.get(\"share_to_fb\") == \"on\":\n logging.info(\"publishing!!\")\n choosie_post.publish_to_facebook(self.request.host_url) \n\n choosie_post.notify_friends()\n self.redirect('/')\n ","sub_path":"choosie-server/posts_handler.py","file_name":"posts_handler.py","file_ext":"py","file_size_in_byte":3644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"262368230","text":"#encoding: utf-8\n'''\nCreated on Feb 15, 2011\n\n@author: santiago\n'''\n\nimport nltk\n\ndef get_label(palabra):\n if palabra == u'cuándo' \\\n or palabra == u'cuánto' \\\n or palabra == u'dónde' \\\n or palabra == u'cómo' \\\n or palabra == u'adónde' \\\n or palabra == u'qué':\n return u'CON_TILDE'\n elif palabra == u'cuando' \\\n or palabra == u'cuanto' \\\n or palabra == u'donde' \\\n or palabra == u'como' \\\n or palabra == u'adonde' \\\n or palabra == u'que':\n return u'SIN_TILDE'\n else:\n return u'O'\n\nif __name__ == '__main__':\n corpus_file = open('corpus_conll2002.txt', 'w')\n \n for oracion in nltk.corpus.conll2002.sents('esp.train'): \n for palabra in oracion:\n palabra_norm = palabra\n palabra_output = palabra_norm + \" \" + get_label(palabra_norm.lower()) + \"\\n\"\n corpus_file.write(palabra_output.encode('utf-8'))\n corpus_file.write(\"\\n\".encode('utf-8'))\n\n for oracion in nltk.corpus.conll2002.sents('esp.testa'):\n for palabra in oracion:\n palabra_norm = palabra\n palabra_output = palabra_norm + \" \" + get_label(palabra_norm.lower()) + \"\\n\"\n corpus_file.write(palabra_output.encode('utf-8'))\n corpus_file.write(\"\\n\".encode('utf-8'))\n \n for oracion in nltk.corpus.conll2002.sents('esp.testb'):\n for palabra in oracion:\n palabra_norm = palabra\n palabra_output = palabra_norm + \" \" + get_label(palabra_norm.lower()) + \"\\n\"\n corpus_file.write(palabra_output.encode('utf-8'))\n corpus_file.write(\"\\n\".encode('utf-8'))\n \n corpus_file.close()","sub_path":"aprend_aut/articulo_final/python/aprendaut/src/conll2002/dump.py","file_name":"dump.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"205582733","text":"board = [\n [7, 8, 0, 4, 0, 0, 1, 2, 0],\n [6, 0, 0, 0, 7, 5, 0, 0, 9],\n [0, 0, 0, 6, 0, 1, 0, 7, 8],\n [0, 0, 7, 0, 4, 0, 2, 6, 0],\n [0, 0, 1, 0, 5, 0, 9, 3, 0],\n [9, 0, 4, 0, 6, 0, 0, 0, 5],\n [0, 7, 0, 3, 0, 0, 0, 1, 2],\n [1, 2, 0, 0, 0, 7, 4, 0, 0],\n [0, 4, 9, 2, 0, 6, 0, 0, 7]\n]\n\n\ndef print_board(bo):\n for i in range(len(bo)):\n if i % 3 == 0 and i != 0:\n print(\"- - - - - - - - - - \") # after every 3 rows we want to divide the sections\n for j in range(len(bo[0])): # gets length of the row, which is\n if j % 3 == 0 and j != 0:\n print(\"|\", end=\"\") # end = \"\" --> does not print '/n' so you don't go to the next line, stay on\n # same line when printing\n if j == 8:\n print(bo[i][j])\n else:\n print(str(bo[i][j]) + \" \", end=\"\")\n\n\ndef find_empty(bo):\n # loop through board, find an empty spot and return the coordinates of that location\n for i in range(len(bo)):\n for j in range(len(bo)):\n if bo[i][j] == 0:\n return (i, j) # returns row and column\n return None\n\n\ndef is_valid(bo, num, pos):\n # check row, column, and sub grid for validity\n\n # check Row\n for i in range(len(bo[0])):\n if bo[pos[0]][i] == num and pos[1] != i: # assume we inserted our num already. checks if the any elements in\n # the row are equal to it AND checks that its not the same position we just inserted our num into\n return False\n # check Column\n for i in range(len(bo)): # loop through every row (going down), check if current column value is equal to\n # number we just inserted AND checks that its not the same position we just inserted our num into\n if bo[i][pos[1]] == num and pos[0] != i:\n return False\n\n # check Sub grid, determine which of the 9 sub grids we are in.\n box_x = pos[1] // 3 # get our first position (column) and integer divide by 3\n box_y = pos[0] // 3 # gets our row and integer divide by 3\n # loop through box\n for i in range(box_y * 3, box_y * 3 + 3): # returns the correct indexes to loop for the box after integer division\n for j in range(box_x * 3, box_x * 3 + 3):\n if bo[i][j] == num and (i, j) != pos:\n return False\n\n return True\n\n\ndef solve_board(bo):\n # recursively call this function w/in itself. Base case is when the board is full.\n find = find_empty(bo)\n if not find:\n return True # we have found the solution, since there are no empty cells left, so return True\n else:\n row, col = find\n for i in range (1, 10): # loop through values 1-9 and check if they are valid solutions within our board.\n if is_valid(bo, i, (row, col)):\n bo[row][col] = i # adding new value\n if solve_board(bo): # recursive call, try to finish solution on NEW BOARD, with new value added\n return True\n bo[row][col] = 0 # if we looped through 1-9 and none work, solve isn't true, so reset last element\n # we added to 0 and try again with another i (value)\n return False\n\n\nprint_board(board)\nsolve_board(board)\n\nprint(\"\\n-----SOLVED BOARD BELOW-----\\n\")\nprint_board(board)","sub_path":"sudokusolver.py","file_name":"sudokusolver.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"180758414","text":"import threading\nfrom lxml import html\nimport re\nimport os\nimport platform\n\n\nclass Book(threading.Thread):\n\n def __init__(self, queue):\n threading.Thread.__init__(self)\n self.queue = queue\n self.dir = os.path.dirname(__file__)\n\n def run(self):\n url = self.queue.get()\n try:\n tree = html.parse(url)\n link = tree.xpath(\"//td/a/@href\")[0]\n title = re.sub('[^a-zA-Z0-9\\n_\\+]', \"_\", tree.xpath(\"//h1/text()\")[0]) + \".pdf\"\n if platform.system() == 'Windows':\n wget_path = os.path.abspath(os.path.join(self.dir, os.pardir)) + os.path.sep + 'wget.exe'\n else:\n wget_path = \"wget\"\n command = wget_path + \" --referer=\" + url + \" --output-document=\" + title + \" \" + link\n os.system(command)\n except Exception as ex:\n ex = \"Error: \" + str(ex)\n print(ex)\n error_file = open(\"errors.txt\", \"a\")\n error_file.writelines(ex)\n error_file.close()\n self.queue.task_done()","sub_path":"Book.py","file_name":"Book.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"617597709","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\nimport MovieClass\r\nimport pickle\r\nimport re\r\nfrom matplotlib import pyplot as plt\r\nimport matplotlib\r\nimport numpy as np\r\n\r\ncolors = [\"#cc6699\",\"#9966cc\",\"#cc99cc\",\"#ff66ff\",\"#cc66cc\",\"#996699\",\"#ff33ff\",\"#cc33cc\",\"#993399\",\"#663366\"]\r\n\r\ndef areaplot(arealist):\r\n others=arealist[9:]\r\n arealist=arealist[0:9]\r\n arealist.append(['其它',[sum([v[1][0] for v in others])]])\r\n plt.figure(figsize=(6,8),dpi=200)\r\n labels=[ area[0]+'\\n'+str(area[1][0]) for area in arealist]\r\n # print(labels)\r\n movienum=sum([v[1][0] for v in arealist])\r\n value=[ area[1][0]/movienum for area in arealist]\r\n\r\n patches,l_text,t_text = plt.pie(value,labels=labels,colors=colors,labeldistance = 1.1,autopct = '%3.1f%%',shadow = False,\r\n startangle = 90,pctdistance = 0.6)\r\n for t in l_text:\r\n t.set_size(11)\r\n for t in t_text[0:7]:\r\n t.set_size(11)\r\n for t in t_text[7:9]:\r\n t.set_size(0)\r\n t_text[9].set_size(11)\r\n\r\n plt.axis('equal')\r\n # plt.legend()\r\n plt.title('\"豆瓣Top250\"中各地区电影占比')\r\n plt.savefig('地区占比.png')\r\n plt.clf()\r\n plt.close('all')\r\n\r\n\r\ndef directorplot(direlist):\r\n # print(direlist)\r\n direlist=[v for v in direlist if v[1][0]>1]\r\n direname=[dir[0] for dir in direlist]\r\n direnum=[dir[1][0] for dir in direlist]\r\n\r\n plt.figure(figsize=(14,9),dpi=200)\r\n plt.axes([0.1,0.2,.8,.7])\r\n x_pos=np.arange(1,len(direname)+1)\r\n rects=plt.bar(x_pos,direnum,align='center',color=colors)\r\n for rect in rects:\r\n rect.set_edgecolor('white')\r\n x_p,x_l=plt.xticks(x_pos,direname,rotation='vertical')\r\n for l in x_l:\r\n l.set_size(9)\r\n # l.set_rotation('vertical')\r\n plt.title('\"豆瓣Top250\"导演的作品数目')\r\n plt.ylabel('上榜作品数')\r\n plt.xlabel('演员')\r\n plt.savefig('导演作品数.png')\r\n plt.clf()\r\n plt.close('all')\r\n\r\ndef yearplot(datelist):\r\n print(datelist)\r\n xlabel=['1966前','1976','1986','1996','2006','2016']\r\n value=[dl[1] for dl in datelist]\r\n x_pos=np.arange(1,len(datelist)+1)\r\n\r\n plt.figure(figsize=(14,9),dpi=200)\r\n rects=plt.bar(x_pos,value,align='center',color=colors)\r\n plt.xticks([1,12,22,32,42,52],xlabel)\r\n plt.title('\"豆瓣Top250\"各年份的电影数目')\r\n plt.ylabel('上榜作品数')\r\n plt.xlabel('年份')\r\n for rect in rects:\r\n rect.set_edgecolor('white')\r\n\r\n plt.savefig('年份作品数.png')\r\n plt.clf()\r\n plt.close('all')\r\n\r\ndef typeplot(typelist):\r\n typelist=[v for v in typelist if v[1][0]>3]\r\n xlabel=[tl[0] for tl in typelist]\r\n value=[tl[1][0] for tl in typelist]\r\n x_pos=np.arange(1,len(value)+1)\r\n\r\n plt.figure(figsize=(14,9),dpi=200)\r\n rects=plt.bar(x_pos,value,align='center',color=colors)\r\n x_p,x_l=plt.xticks(x_pos,xlabel)\r\n plt.title('\"豆瓣Top250\"各类型的电影数目')\r\n plt.ylabel('上榜作品数')\r\n plt.xlabel('电影类型')\r\n for rect in rects:\r\n rect.set_edgecolor('white')\r\n\r\n for l in x_l:\r\n l.set_size(8)\r\n\r\n plt.savefig('类型.png')\r\n plt.clf()\r\n plt.close('all')\r\n\r\ndef actorplot(actorlist):\r\n actorlist=[v for v in actorlist if v[1][0]>2]\r\n plt.figure(figsize=(14,9),dpi=200)\r\n plt.axes([0.1,0.2,.8,.7])\r\n xlabel=[tl[0] for tl in actorlist]\r\n value=[tl[1][0] for tl in actorlist]\r\n x_pos=np.arange(1,len(value)+1)\r\n rects=plt.bar(x_pos,value,align='center',color=colors)\r\n x_p,x_l=plt.xticks(x_pos,xlabel)\r\n plt.title('\"豆瓣Top250\"各演员的电影数目')\r\n plt.ylabel('上榜作品数')\r\n plt.xlabel('演员')\r\n for rect in rects:\r\n rect.set_edgecolor('white')\r\n for l in x_l:\r\n l.set_size(8)\r\n l.set_rotation('vertical')\r\n\r\n plt.savefig('演员作品数.png')\r\n\r\n","sub_path":"Displayplot.py","file_name":"Displayplot.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"496270451","text":"def swap(part,s,e):\n part=\"\"\n char = list(part.split(\"\"))\n temp=char[s]\n char[s]=char[e]\n char[e]=temp\n return(part.join(char))\ndef permute(var,l,r):\n if l==r:\n print(var)\n else:\n for i in range(l,r,1):\n res=swap(var,l,i)\n permute(res,l+1,r)\ns=\"a\"\npermute(s,0,len(s))","sub_path":"Week1/Permutation.py","file_name":"Permutation.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"611665375","text":"\nfrom down import *\n\nurl='https://yuhui.blog.csdn.net/article/list/2?'\n\nif 0:\n data = getdata(url)\n html = etree.HTML(data)\n aa = '//div/@data-articleid'\n li = html.xpath(aa)\n print((li))\n print(len(li))\n print(len(data))\n #save_txt('aaa.txt', data)\n ##print(data)\n\ndef getlist(url, aa):\n ll=[]\n data = getdata(url)\n html = etree.HTML(data)\n print(len(data))\n ll = html.xpath(aa)\n return ll\n\n#li = ['82762601', '83549202', '83410050', '83383119', '83302424', '83104764', '83056420', '82868658', '82865579', '82839713', '82783265', '82684203', '82660979', '82492354', '81506977', '81224151', '81218840', '81171545', '80820511', '80654007', '80207646']\n#li = ['82762601']\n\n#li=getlist()\n\nimport htmltree\nimport win32clipboard as w\nimport win32con\n\ndef gettext():\n w.OpenClipboard()\n t = w.GetClipboardData(win32con.CF_TEXT)\n w.CloseClipboard()\n return t\n\ndef down_csdn_one(url):\n print(url)\n data = getdata(url)\n save_txt('test1.html', data)\n t, d = htmltree.htm2md(data)\n if len(t)<2:\n return\n if len(d)<2:\n return\n t = t.replace('/', ' ').replace('\\\\', ' ').replace('*', ' ').replace('?', ' ')\n t = t.replace('.', ' ').replace('|', ' ')\n t = t.replace(':', ' ')\n t = t.replace('~', ' ')\n t = t.replace(' - ', '/')\n cc = t.split('/')\n ttt=cc[-1].strip()\n name=cc[-2].strip()\n t = '-'.join(cc[0:-2]).strip()\n mkdir(ttt)\n mkdir(ttt+'/'+name)\n print(t)\n print(len(d))\n if len(t)>1:\n save_txt(ttt+'/'+name + '/'+t+'.md', d)\n\ndef down_csdn_list_one(url, aa):\n ll=getlist(url, aa)\n for li in ll:\n down_csdn_one(li)\n return ll\n\nimport sys\n\ndef down_csdn_list(url, aa):\n if len(sys.argv)>1:\n n = int(sys.argv[1])\n for i in range(1, 1000):\n url1='%s/%d?'%(url, i)\n print('---'+url1)\n ll = down_csdn_list_one(url1, aa)\n else:\n ll = down_csdn_list_one(url, aa)\n return 0\n\nif 1:\n url='https://yuhui.blog.csdn.net/article/details/80106526'\n url='https://www.cnblogs.com/chaihy/p/10615117.html'\n url='https://blog.csdn.net/sinat_26917383/article/category/6093543'\n url='https://blog.csdn.net/sinat_26917383/article/details/82880021'\n url='https://www.cnblogs.com/pinard/p/6645766.html'\n url='https://www.cnblogs.com/pinard/category/894690.html'\n url = gettext().decode('gbk')\n if url.find('/category/')>0 and url.find('csdn.net')>0:\n aa='//div[@data-articleid]/h4/a/@href'\n down_csdn_list(url, aa)\n elif url.find('/category/')>0 and url.find('www.cnblogs.com')>0:\n aa='//div[@class]/a/@href'\n down_csdn_list_one(url, aa)\n else:\n down_csdn_one(url)\n if url.find('csdn.net')>0:\n aa='//div[@data-articleid]/h4/a/@href'\n down_csdn_list(url, aa)\n\n if url.find('www.cnblogs.com')>0:\n aa='//div[@class]/a/@href'\n down_csdn_list(url, aa)\n ##print(data)\n","sub_path":"www/blob.csdn.net/down_csdn.py","file_name":"down_csdn.py","file_ext":"py","file_size_in_byte":2973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"74763278","text":"import os\n\nimport boto3\n\nCHARSET = 'UTF-8'\nREGION = os.environ.get('AWS_REGION')\nSOURCE = os.environ.get('SOURCE_EMAIL_ADDRESS')\nSUBJECT = \"New message from Alex' serverless messaging API\"\n\n\ndef send(email_address, body):\n client = boto3.client('ses', region_name=REGION)\n\n client.send_email(\n Source=SOURCE,\n Destination={\n 'ToAddresses': [email_address]\n },\n Message={\n 'Subject': {\n 'Data': SUBJECT,\n 'Charset': CHARSET\n },\n\n 'Body': {\n 'Text': {\n 'Data': body,\n 'Charset': CHARSET\n },\n }\n },\n )\n","sub_path":"messaging/services/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"353486930","text":"# coding: utf-8\r\n\r\nimport sys\r\nimport threading\r\n\r\nimport perfdog_pb2\r\nfrom cmd_base import Command, Quit, Menu\r\nfrom config import PERFDOG_SERVICE_OUTPUT_DIRECTORY\r\nfrom stub import set_screenshot_interval, get_app_process_list, print_app_process_list, \\\r\n start_app_process_test, print_sys_process_list, get_sys_process_list, start_sys_process_test, get_apps, \\\r\n print_apps, start_app_test, get_device_support_types, print_device_types, disable_device_type, enable_device_type, \\\r\n get_device_types, get_device_manager, get_stub, get_app_pid_windows_map, \\\r\n print_app_pid_windows_map\r\n\r\n\r\nclass MonitorDevice(Command):\r\n def execute(self):\r\n class Listener:\r\n @staticmethod\r\n def on_add_device(device):\r\n print('Add Device:')\r\n print(device)\r\n\r\n @staticmethod\r\n def on_remove_device(device):\r\n print('Remove Device:')\r\n print(device)\r\n\r\n event_stream = get_device_manager().start_monitor(Listener())\r\n input('')\r\n get_device_manager().stop_monitor(event_stream)\r\n\r\n return Quit()\r\n\r\n\r\nclass PrintDevices(Command):\r\n def execute(self):\r\n get_device_manager().print_devices()\r\n return Quit()\r\n\r\n\r\nclass DeviceBase(Command):\r\n def execute(self):\r\n device = get_device_manager().select_device()\r\n return self.do_execute(device)\r\n\r\n def do_execute(self, device):\r\n raise NotImplementedError()\r\n\r\n\r\nclass GetDeviceStatus(DeviceBase):\r\n def do_execute(self, device):\r\n print(get_stub().getDeviceStatus(device))\r\n return Quit()\r\n\r\n\r\nclass InitDevice(DeviceBase):\r\n def do_execute(self, device):\r\n res = get_stub().getDeviceStatus(device)\r\n if res.isTesting:\r\n return True, DeviceContext(device)\r\n\r\n get_stub().initDevice(device)\r\n return True, DeviceContext(device)\r\n\r\n\r\nclass SetGlobalDataUploadServer(Command):\r\n def execute(self):\r\n server_url = input('请输入第三方数据上传服务地址:')\r\n print('0. json')\r\n print('1. pb')\r\n server_format = int(input('请选择要上传的格式:'))\r\n req = perfdog_pb2.SetDataUploadServerReq(serverUrl=server_url, dataUploadFormat=server_format)\r\n get_stub().setGlobalDataUploadServer(req)\r\n\r\n return Quit()\r\n\r\n\r\nclass ClearGlobalDataUploadServer(Command):\r\n def execute(self):\r\n req = perfdog_pb2.SetDataUploadServerReq(serverUrl='')\r\n get_stub().setGlobalDataUploadServer(req)\r\n\r\n return Quit()\r\n\r\n\r\nclass SetScreenShotInterval(DeviceBase):\r\n def do_execute(self, device):\r\n seconds = int(input('请输入截屏时间间隔:'))\r\n set_screenshot_interval(device, seconds)\r\n return Quit()\r\n\r\n\r\nclass EnableInstallApk(Command):\r\n def execute(self):\r\n preferences = perfdog_pb2.Preferences(doNotInstallPerfDogApp=False)\r\n req = perfdog_pb2.SetPreferencesReq(preferences=preferences)\r\n get_stub().setPreferences(req)\r\n return Quit()\r\n\r\n\r\nclass DisableInstallApk(Command):\r\n def execute(self):\r\n preferences = perfdog_pb2.Preferences(doNotInstallPerfDogApp=True)\r\n req = perfdog_pb2.SetPreferencesReq(preferences=preferences)\r\n get_stub().setPreferences(req)\r\n return Quit()\r\n\r\n\r\nclass SaveTestData(DeviceBase):\r\n def do_execute(self, device):\r\n begin_time = int(input('请输入保存数据开始时间点:'))\r\n end_time = int(input('请输入保存数据结束时间点:'))\r\n case_name = input('请输入case名称:')\r\n is_upload = True if input('是否上传到云服务(y/n):') in 'yY' else False\r\n is_export = True if input('是否保存到本地(y/n):') in 'yY' else False\r\n print('0. excel')\r\n print('1. json')\r\n print('2. pb')\r\n output_format = int(input('请选择导出格式:'))\r\n req = perfdog_pb2.SaveDataReq(\r\n device=device,\r\n beginTime=begin_time,\r\n endTime=end_time,\r\n caseName=case_name,\r\n uploadToServer=is_upload,\r\n exportToFile=is_export,\r\n outputDirectory=PERFDOG_SERVICE_OUTPUT_DIRECTORY,\r\n dataExportFormat=output_format,\r\n )\r\n print(get_stub().saveData(req))\r\n\r\n return Quit()\r\n\r\n\r\nclass GetDeviceCacheData(DeviceBase):\r\n def do_execute(self, device):\r\n req = perfdog_pb2.GetDeviceCacheDataReq(device=device)\r\n stream = get_stub().getDeviceCacheData(req)\r\n t = threading.Thread(target=self.run, args=(stream,))\r\n t.start()\r\n input('')\r\n stream.cancel()\r\n t.join()\r\n\r\n return Quit()\r\n\r\n @staticmethod\r\n def run(stream):\r\n try:\r\n for d in stream:\r\n print(d)\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\nclass GetDeviceCacheDataPacked(DeviceBase):\r\n def do_execute(self, device):\r\n print('0. json')\r\n print('1. pb')\r\n data_format = int(input('请选择要拉取设备缓存数据格式:'))\r\n req = perfdog_pb2.GetDeviceCacheDataPackedReq(device=device, dataFormat=data_format)\r\n stream = get_stub().getDeviceCacheDataPacked(req)\r\n t = threading.Thread(target=self.run, args=(stream,))\r\n t.start()\r\n input('')\r\n stream.cancel()\r\n t.join()\r\n\r\n return Quit()\r\n\r\n @staticmethod\r\n def run(stream):\r\n try:\r\n for d in stream:\r\n print(d)\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\nclass CreateTask(Command):\r\n def execute(self):\r\n task_name = input('请输入任务名:')\r\n req = perfdog_pb2.CreateTaskReq(taskName=task_name)\r\n print(get_stub().createTask(req))\r\n\r\n return Quit()\r\n\r\n\r\nclass ArchiveCaseToTask(Command):\r\n def execute(self):\r\n case_id = input('请输入caseID:')\r\n task_id = input('请输入任务ID:')\r\n req = perfdog_pb2.ArchiveCaseToTaskReq(caseId=case_id, taskId=task_id)\r\n get_stub().archiveCaseToTask(req)\r\n\r\n return Quit()\r\n\r\n\r\nclass ShareCase(Command):\r\n def execute(self):\r\n case_id = input('请输入caseID:')\r\n expire_time = int(input('请输入失效时间: '))\r\n non_password = True if input('是否取消分享密码(y/n):') in 'yY' else False\r\n req = perfdog_pb2.ShareCaseReq(caseId=case_id, expireTime=expire_time, nonPassword=non_password)\r\n print(get_stub().shareCase(req))\r\n\r\n return Quit()\r\n\r\n\r\nclass KillServer(Command):\r\n def execute(self):\r\n req = perfdog_pb2.Empty()\r\n print(get_stub().killServer(req))\r\n sys.exit(0)\r\n\r\n return Quit()\r\n\r\n\r\nclass DeviceContext(Menu):\r\n def __init__(self, device):\r\n super(DeviceContext, self).__init__([\r\n GetDeviceInfo('获取设备信息', device),\r\n GetDeviceAppList('获取App列表', device),\r\n GetDeviceAppProcessList('获取App进程列表', device),\r\n GetDeviceAppWindowsMap('获取App进程对应的Activity和SurfaceView', device),\r\n GetDeviceSysProcessList('获取系统进程列表', device),\r\n UpdateAppInfo('更新App信息', device),\r\n GetDeviceSupportTypes('获取设备支持的测试类型', device),\r\n GetDeviceTypes('获取设备当前打开的测试类型', device),\r\n EnableDeviceType('启用设备测试类型', device),\r\n DisableDeviceType('禁用设备测试类型', device),\r\n StartTest('开始测试', device),\r\n StopTest('结束测试', device),\r\n ])\r\n\r\n\r\nclass GetDeviceInfo(Command):\r\n def __init__(self, desc, device):\r\n super(GetDeviceInfo, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n print(get_stub().getDeviceInfo(self.device))\r\n return Quit()\r\n\r\n\r\nclass GetDeviceAppList(Command):\r\n def __init__(self, desc, device):\r\n super(GetDeviceAppList, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n apps = get_apps(self.device)\r\n print_apps(apps)\r\n return Quit()\r\n\r\n\r\nclass GetDeviceAppProcessList(Command):\r\n def __init__(self, desc, device):\r\n super(GetDeviceAppProcessList, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n apps = get_apps(self.device)\r\n print_apps(apps)\r\n idx = int(input('请选择要获取进程列表的App:'))\r\n process_list = get_app_process_list(self.device, apps[idx])\r\n print_app_process_list(process_list)\r\n return Quit()\r\n\r\n\r\nclass GetDeviceAppWindowsMap(Command):\r\n def __init__(self, desc, device):\r\n super(GetDeviceAppWindowsMap, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n apps = get_apps(self.device)\r\n print_apps(apps)\r\n idx = int(input('请选择要获取信息的App:'))\r\n pid_windows_map = get_app_pid_windows_map(self.device, apps[idx])\r\n print_app_pid_windows_map(pid_windows_map)\r\n return Quit()\r\n\r\n\r\nclass GetDeviceSysProcessList(Command):\r\n def __init__(self, desc, device):\r\n super(GetDeviceSysProcessList, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n process_list = get_sys_process_list(self.device)\r\n print_sys_process_list(process_list)\r\n return Quit()\r\n\r\n\r\nclass UpdateAppInfo(Command):\r\n def __init__(self, desc, device):\r\n super(UpdateAppInfo, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n apps = get_apps(self.device)\r\n print_apps(apps)\r\n idx = int(input('请选择要测试的App:'))\r\n app = apps[idx]\r\n req = perfdog_pb2.UpdateAppInfoReq(device=self.device, app=app)\r\n print(get_stub().updateAppInfo(req))\r\n\r\n return Quit()\r\n\r\n\r\nclass GetDeviceSupportTypes(Command):\r\n def __init__(self, desc, device):\r\n super(GetDeviceSupportTypes, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n types = get_device_support_types(self.device)\r\n print_device_types(types)\r\n return Quit()\r\n\r\n\r\nclass GetDeviceTypes(Command):\r\n def __init__(self, desc, device):\r\n super(GetDeviceTypes, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n types = get_device_types(self.device)\r\n print_device_types(types)\r\n return Quit()\r\n\r\n\r\nclass EnableDeviceType(Command):\r\n def __init__(self, desc, device):\r\n super(EnableDeviceType, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n types = get_device_support_types(self.device)\r\n print_device_types(types)\r\n idx = int(input('请选择要启用的类型:'))\r\n enable_device_type(self.device, types[idx])\r\n return Quit()\r\n\r\n\r\nclass DisableDeviceType(Command):\r\n def __init__(self, desc, device):\r\n super(DisableDeviceType, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n types = get_device_support_types(self.device)\r\n print_device_types(types)\r\n idx = int(input('请选择要关闭的类型:'))\r\n disable_device_type(self.device, types[idx])\r\n return Quit()\r\n\r\n\r\nclass StartTest(Command):\r\n def __init__(self, desc, device):\r\n super(StartTest, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n res = get_stub().getDeviceStatus(self.device)\r\n if res.isTesting:\r\n return True, TestContext(self.device)\r\n\r\n self.print_usage()\r\n idx = int(input('选择要测试的类型:'))\r\n\r\n if idx == 0:\r\n self.test_app()\r\n elif idx == 1:\r\n self.test_app_process()\r\n elif idx == 2:\r\n self.test_sys_process()\r\n else:\r\n return Quit()\r\n\r\n return True, TestContext(self.device)\r\n\r\n @staticmethod\r\n def print_usage():\r\n print('0. app')\r\n print('1. app process')\r\n print('2. sys process')\r\n\r\n def test_app(self):\r\n apps = get_apps(self.device)\r\n print_apps(apps)\r\n idx = int(input('请选择要测试的App:'))\r\n app = apps[idx]\r\n start_app_test(self.device, app)\r\n\r\n def test_app_process(self):\r\n apps = get_apps(self.device)\r\n print_apps(apps)\r\n idx = int(input('请选择要测试的App:'))\r\n app = apps[idx]\r\n\r\n process_list = get_app_process_list(self.device, app)\r\n print_app_process_list(process_list)\r\n idx = int(input('请选择要测试App进程:'))\r\n process = process_list[idx]\r\n\r\n is_hide_float_window = True if input('是否隐藏浮窗(y/n):') in 'yY' else False\r\n is_test_sub_window = True if input('是否测试子窗口(y/n):') in 'yY' else False\r\n if is_test_sub_window:\r\n sub_list = get_app_pid_windows_map(self.device, app)\r\n print_app_pid_windows_map(sub_list)\r\n sub_window = input('请输入要获取的子窗口名字:')\r\n else:\r\n sub_window = None\r\n\r\n start_app_process_test(self.device, app, process, is_hide_float_window, sub_window)\r\n\r\n def test_sys_process(self):\r\n process_list = get_sys_process_list(self.device)\r\n print_sys_process_list(process_list)\r\n idx = int(input('请选择要测试系统进程:'))\r\n process = process_list[idx]\r\n is_hide_float_window = True if input('是否隐藏浮窗(y/n):') in 'yY' else False\r\n\r\n start_sys_process_test(self.device, process, is_hide_float_window)\r\n\r\n\r\nclass StopTest(Command):\r\n def __init__(self, desc, device):\r\n super(StopTest, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n req = perfdog_pb2.StopTestReq(device=self.device)\r\n get_stub().stopTest(req)\r\n\r\n return Quit()\r\n\r\n\r\nclass TestContext(Menu):\r\n def __init__(self, device):\r\n super(TestContext, self).__init__([\r\n OpenPerfDataStream('获取当前测试设备的实时测试数据流(按任意键结束)', device),\r\n SetLabel('设置标签', device),\r\n UpdateLabel('更新标签', device),\r\n AddNote('添加标注', device),\r\n RemoteNote('删除标注', device),\r\n GetRenderResolution('获取渲染分辨率(适用Android)', device),\r\n ])\r\n\r\n\r\nclass OpenPerfDataStream(Command):\r\n def __init__(self, desc, device):\r\n super(OpenPerfDataStream, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n req = perfdog_pb2.OpenPerfDataStreamReq(device=self.device)\r\n stream = get_stub().openPerfDataStream(req)\r\n t = threading.Thread(target=self.run, args=(stream,))\r\n t.start()\r\n input('')\r\n stream.cancel()\r\n t.join()\r\n\r\n return Quit()\r\n\r\n @staticmethod\r\n def run(stream):\r\n try:\r\n for data in stream:\r\n print(data)\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\nclass SetLabel(Command):\r\n def __init__(self, desc, device):\r\n super(SetLabel, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n label_name = input('请输入标签名字:')\r\n req = perfdog_pb2.SetLabelReq(device=self.device, label=label_name)\r\n print(get_stub().setLabel(req))\r\n\r\n return Quit()\r\n\r\n\r\nclass UpdateLabel(Command):\r\n def __init__(self, desc, device):\r\n super(UpdateLabel, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n label_time = int(input('请输入标签时间戳:'))\r\n label_name = input('请输入标签名字:')\r\n req = perfdog_pb2.UpdateLabelReq(device=self.device, time=label_time, label=label_name)\r\n get_stub().updateLabel(req)\r\n\r\n return Quit()\r\n\r\n\r\nclass AddNote(Command):\r\n def __init__(self, desc, device):\r\n super(AddNote, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n note_time = int(input('请输入标注时间戳:'))\r\n note_name = input('请输入标注名字:')\r\n req = perfdog_pb2.AddNoteReq(device=self.device, time=note_time, note=note_name)\r\n get_stub().addNote(req)\r\n\r\n return Quit()\r\n\r\n\r\nclass RemoteNote(Command):\r\n def __init__(self, desc, device):\r\n super(RemoteNote, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n note_time = int(input('请输入标注时间戳:'))\r\n req = perfdog_pb2.RemoveNoteReq(device=self.device, time=note_time)\r\n get_stub().removeNote(req)\r\n\r\n return Quit()\r\n\r\n\r\nclass GetRenderResolution(Command):\r\n def __init__(self, desc, device):\r\n super(GetRenderResolution, self).__init__(desc)\r\n self.device = device\r\n\r\n def execute(self):\r\n req = perfdog_pb2.GetRenderResolutionReq(device=self.device)\r\n print(get_stub().GetRenderResolutionOfWindowUnderTest(req))\r\n return Quit()\r\n\r\n\r\ndef get_top_menus():\r\n return [\r\n MonitorDevice('监控设备连接断开情况'),\r\n PrintDevices('打印当前连接所有设备'),\r\n GetDeviceStatus('获取设备状态'),\r\n InitDevice('初始化设备'),\r\n SetGlobalDataUploadServer('配置第三方数据存储服务'),\r\n ClearGlobalDataUploadServer('清除第三方数据存储服务配置'),\r\n SetScreenShotInterval('配置设备截屏时间间隔'),\r\n EnableInstallApk('设置测试安卓设备时安装APK'),\r\n DisableInstallApk('设置测试安卓设备时不安装APK'),\r\n SaveTestData('保存数据'),\r\n GetDeviceCacheData('单条拉取设备缓存数据(按任意键结束)'),\r\n GetDeviceCacheDataPacked('批量拉取设备缓存数据(按任意键结束)'),\r\n CreateTask('创建任务'),\r\n ArchiveCaseToTask('归档Case到任务'),\r\n ShareCase('分享Case'),\r\n KillServer('killServer'),\r\n ]\r\n","sub_path":"cmds.py","file_name":"cmds.py","file_ext":"py","file_size_in_byte":18154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"24467973","text":"import torch\n\nimport server_deploy.nms_wrapper as wrapper\n\n\ndef multiclass_nms(\n multi_bboxes,\n multi_scores,\n score_thr,\n nms_cfg,\n max_num=-1,\n score_factors=None\n):\n \"\"\"NMS for multi-class bboxes.\n PERFORM NMS CLASS-INDEPENDENTLY.\n\n Args:\n multi_bboxes (Tensor): shape (n, #class*4) or (n, 4)\n multi_scores (Tensor): shape (n, #class)\n score_thr (float): bbox threshold, bboxes with scores lower than it\n will not be considered.\n nms_cfg (List): nms configurations.\n [nms, dets, iou_thr, device_id]\n [soft_nms, dets, iou_thr, method, sigma, min_score]\n max_num (int): if there are more than max_num bboxes after NMS,\n only top max_num will be kept.\n score_factors (Tensor): The factors multiplied to scores before\n applying NMS\n\n Returns:\n tuple: (bboxes, labels), tensors of shape (k, 5) and (k, 1). Labels\n are 0-based.\n \"\"\"\n num_classes = multi_scores.shape[1]\n bboxes, labels = [], []\n for i in range(1, num_classes):\n cls_inds = multi_scores[:, i] > score_thr\n if not cls_inds.any():\n continue\n # get bboxes and scores of this class\n if multi_bboxes.shape[1] == 4:\n _bboxes = multi_bboxes[cls_inds, :]\n else:\n _bboxes = multi_bboxes[cls_inds, i * 4:(i + 1) * 4]\n _scores = multi_scores[cls_inds, i]\n if score_factors is not None:\n _scores *= score_factors[cls_inds]\n cls_dets = torch.cat([_bboxes, _scores[:, None]], dim=1)\n\n if nms_cfg[0] == 'nms':\n cls_dets, _ = wrapper.nms(dets=cls_dets, iou_thr=nms_cfg[1], device_id=nms_cfg[2])\n elif nms_cfg[0] == 'soft_nms':\n # cls_dets, _ = wrapper.soft_nms(\n # dets=cls_dets, iou_thr=nms_cfg[1], method=nms_cfg[2], sigma=nms_cfg[3], min_score=nms_cfg[4]\n # )\n raise RuntimeError('not supported nms operation type!')\n else:\n raise RuntimeError('not supported nms operation type!')\n\n cls_labels = multi_bboxes.new_full(\n (cls_dets.shape[0], ), i - 1, dtype=torch.long)\n bboxes.append(cls_dets)\n labels.append(cls_labels)\n if bboxes:\n bboxes = torch.cat(bboxes)\n labels = torch.cat(labels)\n if bboxes.shape[0] > max_num:\n _, inds = bboxes[:, -1].sort(descending=True)\n inds = inds[:max_num]\n bboxes = bboxes[inds]\n labels = labels[inds]\n else:\n bboxes = multi_bboxes.new_zeros((0, 5))\n labels = multi_bboxes.new_zeros((0, ), dtype=torch.long)\n\n return bboxes, labels\n","sub_path":"server_deploy/nms.py","file_name":"nms.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"585846906","text":"#!/usr/bin/env python\n# A basic ZAP Python API example which spiders and scans a target URL\n\nimport time\nfrom pprint import pprint\nfrom zapv2 import ZAPv2\nimport json\n\ntarget = 'http://0.0.0.0:32777/htmli_get.php'\napikey = 'None' # Change to match the API key set in ZAP, or use None if the API key is disabled\n#\n# By default ZAP API client will connect to port 8080\nzap = ZAPv2(apikey=apikey, proxies={'http': 'http://localhost:8080', 'https': 'http://localhost:8080'})\n# Use the line below if ZAP is not listening on port 8080, for example, if listening on port 8090\n# zap = ZAPv2(apikey=apikey, proxies={'http': 'http://127.0.0.1:8090', 'https': 'http://127.0.0.1:8090'})\n\nuseProxyChain = False\n\ncore = zap.core\n\n# Proxy a request to the target so that ZAP has something to deal with\nprint('Accessing target {}'.format(target))\ntest = zap.urlopen(target)\n\n# Give the sites tree a chance to get updated\ntime.sleep(2)\n\n# Spider\nprint('Spidering target {}'.format(target))\nscanid = zap.spider.scan(target)\nprint(scanid)\n\n# Give the Spider a chance to start\ntime.sleep(2)\n\n# while (int(zap.spider.status(scanid)) < 100):\n# # Loop until the spider has finished\n# print('Spider progress %: {}'.format(zap.spider.status(scanid)))\n#\n# print ('Spider completed')\n\nprint ('Active Scanning target {}'.format(target))\n\nscanid = zap.ascan.scan(target)\n\nprint('This is the scanid {}'.format(scanid))\nwhile (int(zap.ascan.status(scanid)) < 100):\n # Loop until the scanner has finished\n print('Message: {}'.format(zap.core.message(id)))\n #print ('Scan progress %: {}'.format(zap.ascan.status(scanid)))\n time.sleep(10)\n\nids = zap.ascan.messages_ids(scanid)\nprint(\"Numbers of IDs: {}\".format(len(ids)))\n\n\n# print(ids)\n# for id in ids:\n # file = open(\"data/train/0/\" + id + \".txt\", \"w\")\n # message = zap.core.message(id)\n # file.write(message[\"requestHeader\"] + \"\\n\")\n # file.write(message[\"requestBody\"] + \"\\n\")\n # file.write(message[\"responseHeader\"] + \"\\n\")\n # file.write(message[\"responseBody\"])\n # print(zap.core.alerts(id))\n # file.close()\nprint ('Active Scan completed')\n\n# Report the results\nprint ('Alerts: {}'.format(zap.ascan.alerts_ids(scanid)))\n\npprint('Enable all passive scanners -> ' +\n zap.pscan.enable_all_scanners())\n\nascan = zap.ascan\n\n","sub_path":"zap_base.py","file_name":"zap_base.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"241242357","text":"# Copyright 2017, Google LLC All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\n\nfrom concurrent import futures\nfrom queue import Queue\nimport logging\nimport threading\n\nimport grpc\n\nfrom google.cloud.pubsub_v1 import types\nfrom google.cloud.pubsub_v1.subscriber import _helper_threads\nfrom google.cloud.pubsub_v1.subscriber.futures import Future\nfrom google.cloud.pubsub_v1.subscriber.policy import base\nfrom google.cloud.pubsub_v1.subscriber.message import Message\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef _callback_completed(future):\n \"\"\"Simple callback that just logs a `Future`'s result.\"\"\"\n logger.debug('Result: %s', future.result())\n\n\nclass Policy(base.BasePolicy):\n \"\"\"A consumer class based on :class:`threading.Thread`.\n\n This consumer handles the connection to the Pub/Sub service and all of\n the concurrency needs.\n \"\"\"\n def __init__(self, client, subscription, flow_control=types.FlowControl(),\n executor=None, queue=None):\n \"\"\"Instantiate the policy.\n\n Args:\n client (~.pubsub_v1.subscriber.client): The subscriber client used\n to create this instance.\n subscription (str): The name of the subscription. The canonical\n format for this is\n ``projects/{project}/subscriptions/{subscription}``.\n flow_control (~google.cloud.pubsub_v1.types.FlowControl): The flow\n control settings.\n executor (~concurrent.futures.ThreadPoolExecutor): (Optional.) A\n ThreadPoolExecutor instance, or anything duck-type compatible\n with it.\n queue (~queue.Queue): (Optional.) A Queue instance, appropriate\n for crossing the concurrency boundary implemented by\n ``executor``.\n \"\"\"\n # Default the callback to a no-op; it is provided by `.open`.\n self._callback = lambda message: None\n\n # Default the future to None; it is provided by `.open`.\n self._future = None\n\n # Create a queue for keeping track of shared state.\n if queue is None:\n queue = Queue()\n self._request_queue = queue\n\n # Call the superclass constructor.\n super(Policy, self).__init__(\n client=client,\n flow_control=flow_control,\n subscription=subscription,\n )\n\n # Also maintain a request queue and an executor.\n logger.debug('Creating callback requests thread (not starting).')\n if executor is None:\n executor = futures.ThreadPoolExecutor(max_workers=10)\n self._executor = executor\n self._callback_requests = _helper_threads.QueueCallbackThread(\n self._request_queue,\n self.on_callback_request,\n )\n\n def close(self):\n \"\"\"Close the existing connection.\"\"\"\n # Stop consuming messages.\n self._consumer.helper_threads.stop('callback requests worker')\n self._consumer.stop_consuming()\n\n # The subscription is closing cleanly; resolve the future if it is not\n # resolved already.\n if self._future and not self._future.done():\n self._future.set_result(None)\n self._future = None\n\n def open(self, callback):\n \"\"\"Open a streaming pull connection and begin receiving messages.\n\n For each message received, the ``callback`` function is fired with\n a :class:`~.pubsub_v1.subscriber.message.Message` as its only\n argument.\n\n Args:\n callback (Callable): The callback function.\n\n Returns:\n ~google.api_core.future.Future: A future that provides\n an interface to block on the subscription if desired, and\n handle errors.\n \"\"\"\n # Create the Future that this method will return.\n # This future is the main thread's interface to handle exceptions,\n # block on the subscription, etc.\n self._future = Future(policy=self)\n\n # Start the thread to pass the requests.\n logger.debug('Starting callback requests worker.')\n self._callback = callback\n self._consumer.helper_threads.start(\n 'callback requests worker',\n self._request_queue,\n self._callback_requests,\n )\n\n # Actually start consuming messages.\n self._consumer.start_consuming()\n\n # Spawn a helper thread that maintains all of the leases for\n # this policy.\n logger.debug('Spawning lease maintenance worker.')\n self._leaser = threading.Thread(target=self.maintain_leases)\n self._leaser.daemon = True\n self._leaser.start()\n\n # Return the future.\n return self._future\n\n def on_callback_request(self, callback_request):\n \"\"\"Map the callback request to the appropriate GRPC request.\"\"\"\n action, kwargs = callback_request[0], callback_request[1]\n getattr(self, action)(**kwargs)\n\n def on_exception(self, exception):\n \"\"\"Bubble the exception.\n\n This will cause the stream to exit loudly.\n \"\"\"\n # If this is DEADLINE_EXCEEDED, then we want to retry.\n # That entails just returning None.\n deadline_exceeded = grpc.StatusCode.DEADLINE_EXCEEDED\n if getattr(exception, 'code', lambda: None)() == deadline_exceeded:\n return\n\n # Set any other exception on the future.\n self._future.set_exception(exception)\n\n def on_response(self, response):\n \"\"\"Process all received Pub/Sub messages.\n\n For each message, schedule a callback with the executor.\n \"\"\"\n for msg in response.received_messages:\n logger.debug('New message received from Pub/Sub: %r', msg)\n logger.debug(self._callback)\n message = Message(msg.message, msg.ack_id, self._request_queue)\n future = self._executor.submit(self._callback, message)\n future.add_done_callback(_callback_completed)\n","sub_path":"pubsub/google/cloud/pubsub_v1/subscriber/policy/thread.py","file_name":"thread.py","file_ext":"py","file_size_in_byte":6533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"514263063","text":"import sys\nimport math\nfrom collections import deque\n\nsys.setrecursionlimit(1000000)\nMOD = 10 ** 9 + 7\ninput = lambda: sys.stdin.readline().strip()\nNI = lambda: int(input())\nNMI = lambda: map(int, input().split())\nNLI = lambda: list(NMI())\nSI = lambda: input()\n\n\ndef make_grid(h, w, num): return [[int(num)] * w for _ in range(h)]\n\n\ndef main():\n N, X = NMI()\n A = [1]\n P = [1]\n for i in range(N):\n A.append(A[-1]*2+3)\n P.append(P[-1]*2+1)\n\n def rec(n, x):\n if n == 0:\n return 1\n\n if x == 1:\n return 0\n elif x <= A[n-1]+1:\n return rec(n-1, x-1)\n elif x == A[n-1]+2:\n return P[n-1]+1\n elif x <= A[n]-1:\n return P[n-1]+1+rec(n-1, x-A[n-1]-2)\n else:\n return P[n]\n\n print(rec(N, X))\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Python_codes/p03209/s216665210.py","file_name":"s216665210.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"628213492","text":"class wall():\n\tdef __init__(self,matrix):\n\t\tself.matrix=matrix\n\n\tdef make_wall(self):\n\t\tfor i in range(38):\n\t\t\tfor j in range(76):\n\t\t\t\tif(i == 0 or i == 1 or i == 36 or i == 37 or j == 0 or j == 1 or j == 2 or j == 3 or j == 72 or j == 73 or j == 74 or j == 75):\n\t\t\t\t\tself.matrix[i][j]='X'\n\t\t\t\telif ((i%4 == 0 or i%4 == 1) and (j%8 == 0 or j%8 == 1 or j%8 == 2 or j%8 == 3)):\n\t\t\t\t\tself.matrix[i][j]='X'\n\t\treturn self.matrix\n\t#adds walls to the game \n","sub_path":"wall.py","file_name":"wall.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"442401451","text":"from sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom sklearn.metrics import classification_report\nfrom scipy import signal\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nfrom .timeseries_preprocessing import ltsm_sequence_generator\n\ndef evaluate_performance(model, train_data_raw, test_data_raw, train_data_sm_sc, \n\t\t\t\t\t\t\ttest_data_sm_sc, seq_length, y_col):\n\n\tpast_x_days = train_data_raw.tail(seq_length)\n\tdf = past_x_days.append(test_data_raw, ignore_index = True)\n\n\tscaler = MinMaxScaler()\n\n\tinputs = scaler.fit_transform(df)\n\t\n\t# print(inputs.shape)\n\t\n\tinputs_df = pd.DataFrame()\n\t\n\t# print(train_data_raw.columns)\n\t\n\tfor col in range(inputs.shape[1]):\n\t\t# print(train_data_raw.columns[col])\n\t\t# print(type(train_data_raw.columns[col]))\n\t\tinputs_df[train_data_raw.columns[col]] = inputs[:, col]\n\t\n\t# print(\"shapes \", df.shape, inputs.shape, inputs_df.shape)\n\t\n\tscale_index = train_data_raw.columns.get_loc(y_col)\n\n\t'''\n\tX_test = []\n\ty_test = []\n\n\tfor i in range(seq_length, inputs.shape[0]):\n\t\tX_test.append(inputs[i-seq_length:i])\n\t\ty_test.append(inputs[i, 0])\n\t\t\n\tX_test, y_test = np.array(X_test), np.array(y_test)\t\n\t'''\n\n\tX_test, y_test = ltsm_sequence_generator(inputs_df, seq_length, y_col)\n\n\ty_pred = model.predict(X_test).transpose()[0]\n\n\tscale_arr = scaler.scale_\n\tmin_arr = scaler.data_min_\n\n\ty_pred /= scale_arr[scale_index] \n\ty_pred += min_arr[scale_index]\n\n\ty_test /= scale_arr[scale_index]\n\ty_test += min_arr[scale_index]\n\n\t# Visualizing the prediction results\n\tplt.figure()\n\tfig, axs = plt.subplots(2, 1, figsize=(14,8))\n\taxs[0].plot(y_test, color = 'red', label = 'Real')\n\taxs[0].plot(y_pred, color = 'blue', label = 'Predicted')\n\taxs[0].set_title('Prediction')\n\taxs[0].set_xlabel('Time')\n\taxs[0].set_ylabel('Price')\n\taxs[0].legend()\t\n\t\n\tplt.subplots_adjust(hspace = 0.5)\n\t# Visualizing autocorrelation\n\n\t# Check if Close_diff... and remove NaN values\n\tif 'Close_diff' in y_col:\n\t\ty_pred = y_pred[:-1]\n\t\ty_test = y_test[:-1] # Contains NaN as last value\n\t\tclose_diff_dir_evaluation(y_pred, y_test)\n\t\t\n\tx_corr = signal.correlate(y_test, y_pred, mode='full')\n\t\t\n\thoriz = np.array(range(x_corr.shape[0]))\n\n\thoriz -= y_test.shape[0]\n\n\taxs[1].plot(horiz, x_corr)\n\taxs[1].set_title('Cross-correlation')\n\tx_corr_max_x = np.argmax(x_corr) - y_test.shape[0]\n\tx_corr_max_y = x_corr.max()\n\t\n\taxs[1].plot([x_corr_max_x], [x_corr_max_y], marker='o', color='r',\n\t\tlabel=('lag: '+str(x_corr_max_x))) # \n\n\taxs[1].legend()\n\t\t\n\tplt.show()\n\t\n\treturn y_pred, fig\n\ndef close_diff_dir_evaluation(y_pred, y_test):\n\ty_pred_sign = np.sign(y_pred)\n\ty_test_sign = np.sign(y_test)\n\t\n\tprint(classification_report(y_test_sign, y_pred_sign))\n\t\n\treturn\n\t","sub_path":"Forecasting_Exp_1/Forecasting_Exp_1_files/gen/network_evaluation.py","file_name":"network_evaluation.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"375459333","text":"# Author: Surya Dhole\n\n# Technical TASK 1: Prediction using Supervised ML (Level - Beginner)\n# Task Description: in this task, we will predict the percentage of marks that a student\n# is expected to score based upon the number of hours\n# they studied. This is a simple linear regression task as it involves just two variables.\n\n\n# Importing required libraries\nimport pandas as pd\nimport numpy as np\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nimport matplotlib.pyplot as plt\n\n\n# Importing and Reading the dataset from remote link\ndata = pd.read_csv('http://bit.ly/w-data')\nprint(data)\nprint(\"data imported successfully!\")\n\n\n# Plotting the distribution of score\ndata.plot(x='Hours', y='Scores', style='o')\nplt.title('Hours vs Percentage')\nplt.xlabel('Hours Studied')\nplt.ylabel('Percentage Scored')\nplt.show()\n\n\n# dividing the data into \"attributes\" (inputs) and \"labels\" (outputs)\nx = data.iloc[:, :-1].values\ny = data.iloc[:, 1].values\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)\n\n\n# Training the model\nreg = LinearRegression()\nreg.fit(x_train.reshape(-1, 1), y_train)\nprint(\"Trained!!\")\n\n\n# Plotting the regression line\nline = reg.coef_ * x + reg.intercept_\n\n\n# Plotting for the test data\nplt.scatter(x, y)\nplt.plot(x, line, color='Black')\nplt.show()\n\n\n# Testing data - In Hours\nprint(x_test)\n# Predicting the scores\ny_predict = reg.predict(x_test)\n\n\n# Comparing Actual vs Predicted\ndata = pd.DataFrame({'Actual': y_test, 'Predicted': y_predict})\nprint(data)\n\n\n# Estimating the Training Data and Test Data Score\nprint(\"Training score:\", reg.score(x_train, y_train))\nprint(\"Testing score:\", reg.score(x_test, y_test))\n\n\n# Plotting the line graph to depict the difference between actual and predicted value.\ndata.plot(kind='line', figsize=(8, 5))\nplt.grid(which='major', linewidth='0.5', color='black')\nplt.grid(which='major', linewidth='0.5', color='black')\nplt.show()\n\n\n# Testing the model.\nhours = 8.5\ntest_data = np.array([hours])\ntest_data = test_data.reshape(-1, 1)\nown_predict = reg.predict(test_data)\nprint(\"Hours = {}\".format(hours))\nprint(\"Predicted Score = {}\".format(own_predict[0]))\n\n\n# Checking the efficiency of model\n# This is the final step to evaluate the performance of an algorithm.\n# This step is particularly important to compare how well different algorithms\n# perform on a given dataset\nprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_predict))\nprint('Mean Squared Error:', metrics.mean_squared_error(y_test, y_predict))\nprint('Root mean squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_predict)))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"116967946","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 10 15:15:00 2017\n\n@author: Jim\n\"\"\"\n\n# Extract relevent data for goal-analysis from the European Soccer Database by Hugo Mathien at kaggle #\n\nimport sqlite3\nimport pandas as pd\nimport re\nimport xml.etree.ElementTree as et\nimport math\n\n\ndef get_possession(poss_str):\n poss_xml = et.fromstring(poss_str)\n\n poss_time = 0\n home_poss = 0\n values = poss_xml.findall('value')\n for value in values:\n # Some matches contain corner data without a team or player.\n # Comparison with other sources indicates these corners did not occur and may therefore be ignored.\n try:\n elapsed = int(value.find('elapsed').text)\n if elapsed > poss_time: poss_time = elapsed\n except:\n print(\"Excess possession data ignored.\")\n continue\n\n for value in values:\n try:\n if int(value.find('elapsed').text) == poss_time:\n home_poss = int(value.find('homepos').text)\n except:\n continue\n if home_poss == 0:\n print(\"home_poss = 0\")\n return math.nan\n return home_poss\n\n\ndef get_shots(match, shoton=True):\n \"\"\" Return the number of shots taken by home and away teams for a match.\n shoton returns number of shots on target if True and off target if False.\n \"\"\"\n\n if shoton:\n shots_xml = et.fromstring(match['shoton'])\n else:\n shots_xml = et.fromstring(match['shotoff'])\n n_home_shots = 0\n n_away_shots = 0\n\n for value in shots_xml.findall('value'):\n try:\n team = int(value.find('team').text)\n except:\n # Remenents of incorrect data that was later reverted from database (no team)\n print(\"Excess shot data ignored, match id: \" + str(match['id']))\n continue\n if team == match['home_id']:\n n_home_shots += 1\n elif team == match['away_id']:\n n_away_shots += 1\n else:\n print(\"Invalid team id: \\'corner\\' team \" + str(team) +\n \" does not equal either \\'match\\' team \" + str(match['home_id']) +\n \", \" + str(match['away_id']))\n return (n_home_shots, n_away_shots)\n\n\ndef get_goal_data(match_data):\n \"\"\" Reformat and select columns from the database input \"\"\"\n\n match_data = match_data.rename(columns={'home_team_api_id': 'home_id',\n 'away_team_api_id': 'away_id',\n 'home_team_goal': 'home_goals',\n 'away_team_goal': 'away_goals'})\n\n print(\"Extracting possession data...\")\n match_data['home_possession'] = match_data['possession'].apply(get_possession)\n match_data['away_possession'] = match_data['home_possession'].multiply(-1).add(100)\n\n print(\"Extracting shot data...\")\n match_data['home_shoton'], match_data['away_shoton'] = zip(*match_data.apply(get_shots,\n axis=1,\n args=(True,)))\n match_data['home_shotoff'], match_data['away_shotoff'] = zip(*match_data.apply(get_shots,\n axis=1,\n args=(False,)))\n return match_data[['id', 'season', 'stage',\n 'home_id', 'away_id',\n 'home_goals', 'away_goals',\n 'home_possession', 'away_possession',\n 'home_shoton', 'away_shoton',\n 'home_shotoff', 'away_shotoff',\n 'max_over_2_5', 'avg_over_2_5',\n 'max_less_2_5', 'avg_less_2_5']]\n\n\ndef get_column_names(suffix_str):\n return [\n 'h_score' + suffix_str,\n 'h_concede' + suffix_str,\n 'h_possession' + suffix_str,\n 'h_shoton' + suffix_str,\n 'h_shotoff' + suffix_str,\n 'h_opp_shoton' + suffix_str,\n 'h_opp_shotoff' + suffix_str,\n 'a_score' + suffix_str,\n 'a_concede' + suffix_str,\n 'a_possession' + suffix_str,\n 'a_shoton' + suffix_str,\n 'a_shotoff' + suffix_str,\n 'a_opp_shoton' + suffix_str,\n 'a_opp_shotoff' + suffix_str\n ]\n\n\ndef create_features(goal_data, goal_threshold=2.5, n_individual_matches=1, n_recent_matches=5, min_season_matches=5):\n # Number of matches that must have occured so far this season\n min_overall_matches = n_individual_matches + n_recent_matches + min_season_matches\n col_names = ['id', 'season', 'stage',\n 'total_goals', 'h_goals', 'a_goals',\n 'over_threshold', 'winning_team',\n 'max_over_2_5', 'avg_over_2_5',\n 'max_less_2_5', 'avg_less_2_5']\n for i in range(1, n_individual_matches + 1):\n col_names.extend(get_column_names('_g%d' % i))\n col_names.extend(get_column_names('_recent'))\n col_names.extend(get_column_names('_season'))\n match_features = pd.DataFrame(columns=col_names)\n\n for season in goal_data.season.unique():\n season_matches = goal_data[goal_data.season == season]\n\n for home_id in season_matches.home_id.unique():\n homes_matches = season_matches[(season_matches.home_id == home_id)\n | (season_matches.away_id == home_id)]\n check_matches = homes_matches[(homes_matches.home_id == home_id)]\n\n for match in check_matches[(check_matches.stage > min_overall_matches)].itertuples():\n aways_matches = season_matches[(season_matches.home_id == match.away_id)\n | (season_matches.away_id == match.away_id)]\n over_threshold = goal_threshold < (match.home_goals + match.away_goals)\n\n data = dict.fromkeys(col_names, [0])\n data.update({'id': match.id,\n 'season': match.season,\n 'stage': match.stage,\n 'total_goals': match.home_goals + match.away_goals,\n 'h_goals': match.home_goals,\n 'a_goals': match.away_goals,\n 'over_threshold': [over_threshold],\n 'max_over_2_5': match.max_over_2_5,\n 'avg_over_2_5': match.avg_over_2_5,\n 'max_less_2_5': match.max_less_2_5,\n 'avg_less_2_5': match.avg_less_2_5})\n if (match.home_goals > match.away_goals):\n data.update({'winning_team': \"home\"})\n elif (match.home_goals < match.away_goals):\n data.update({'winning_team': \"away\"})\n else:\n data.update({'winning_team': \"draw\"})\n\n for i in range(1, match.stage):\n this_stage = match.stage - i\n homes_game = homes_matches[homes_matches.stage == this_stage]\n aways_game = aways_matches[aways_matches.stage == this_stage]\n\n if i <= n_individual_matches:\n suffix = '_g' + str(i)\n m = 1\n elif i <= n_individual_matches + n_recent_matches:\n suffix = '_recent'\n m = i - n_individual_matches\n else:\n suffix = '_season'\n m = i - n_individual_matches - n_recent_matches\n\n if homes_game.home_id.iloc[0] == match.home_id:\n data['h_score' + suffix] = [\n (data['h_score' + suffix][0] * (m - 1) + homes_game.home_goals.iloc[0]) / m]\n data['h_concede' + suffix] = [\n (data['h_concede' + suffix][0] * (m - 1) + homes_game.away_goals.iloc[0]) / m]\n data['h_possession' + suffix] = [\n (data['h_possession' + suffix][0] * (m - 1) + homes_game.home_possession.iloc[0]) / m]\n data['h_shoton' + suffix] = [\n (data['h_shoton' + suffix][0] * (m - 1) + homes_game.home_shoton.iloc[0]) / m]\n data['h_shotoff' + suffix] = [\n (data['h_shotoff' + suffix][0] * (m - 1) + homes_game.home_shotoff.iloc[0]) / m]\n data['h_opp_shoton' + suffix] = [\n (data['h_opp_shoton' + suffix][0] * (m - 1) + homes_game.away_shoton.iloc[0]) / m]\n data['h_opp_shotoff' + suffix] = [\n (data['h_opp_shotoff' + suffix][0] * (m - 1) + homes_game.away_shotoff.iloc[0]) / m]\n else:\n data['h_score' + suffix] = [\n (data['h_score' + suffix][0] * (m - 1) + homes_game.away_goals.iloc[0]) / m]\n data['h_concede' + suffix] = [\n (data['h_concede' + suffix][0] * (m - 1) + homes_game.home_goals.iloc[0]) / m]\n data['h_possession' + suffix] = [\n (data['h_possession' + suffix][0] * (m - 1) + homes_game.away_possession.iloc[0]) / m]\n data['h_shoton' + suffix] = [\n (data['h_shoton' + suffix][0] * (m - 1) + homes_game.away_shoton.iloc[0]) / m]\n data['h_shotoff' + suffix] = [\n (data['h_shotoff' + suffix][0] * (m - 1) + homes_game.away_shotoff.iloc[0]) / m]\n data['h_opp_shoton' + suffix] = [\n (data['h_opp_shoton' + suffix][0] * (m - 1) + homes_game.home_shoton.iloc[0]) / m]\n data['h_opp_shotoff' + suffix] = [\n (data['h_opp_shotoff' + suffix][0] * (m - 1) + homes_game.home_shotoff.iloc[0]) / m]\n\n if aways_game.home_id.iloc[0] == match.away_id:\n data['a_score' + suffix] = [\n (data['a_score' + suffix][0] * (m - 1) + aways_game.home_goals.iloc[0]) / m]\n data['a_concede' + suffix] = [\n (data['a_concede' + suffix][0] * (m - 1) + aways_game.away_goals.iloc[0]) / m]\n data['a_possession' + suffix] = [\n (data['a_possession' + suffix][0] * (m - 1) + aways_game.home_possession.iloc[0]) / m]\n data['a_shoton' + suffix] = [\n (data['a_shoton' + suffix][0] * (m - 1) + aways_game.home_shoton.iloc[0]) / m]\n data['a_shotoff' + suffix] = [\n (data['a_shotoff' + suffix][0] * (m - 1) + aways_game.home_shotoff.iloc[0]) / m]\n data['a_opp_shoton' + suffix] = [\n (data['a_opp_shoton' + suffix][0] * (m - 1) + aways_game.away_shoton.iloc[0]) / m]\n data['a_opp_shotoff' + suffix] = [\n (data['a_opp_shotoff' + suffix][0] * (m - 1) + aways_game.away_shotoff.iloc[0]) / m]\n else:\n data['a_score' + suffix] = [\n (data['a_score' + suffix][0] * (m - 1) + aways_game.away_goals.iloc[0]) / m]\n data['a_concede' + suffix] = [\n (data['a_concede' + suffix][0] * (m - 1) + aways_game.home_goals.iloc[0]) / m]\n data['a_possession' + suffix] = [\n (data['a_possession' + suffix][0] * (m - 1) + aways_game.away_possession.iloc[0]) / m]\n data['a_shoton' + suffix] = [\n (data['a_shoton' + suffix][0] * (m - 1) + aways_game.away_shoton.iloc[0]) / m]\n data['a_shotoff' + suffix] = [\n (data['a_shotoff' + suffix][0] * (m - 1) + aways_game.away_shotoff.iloc[0]) / m]\n data['a_opp_shoton' + suffix] = [\n (data['a_opp_shoton' + suffix][0] * (m - 1) + aways_game.home_shoton.iloc[0]) / m]\n data['a_opp_shotoff' + suffix] = [\n (data['a_opp_shotoff' + suffix][0] * (m - 1) + aways_game.home_shotoff.iloc[0]) / m]\n\n data.update(data)\n match_features = match_features.append(pd.DataFrame(data, columns=col_names))\n print('Done match: ' + str(match.id))\n return match_features\n\n\nN_MATCHES_CHECKED = 1 # number of matches indiviudally used\nN_MEAN_MATCHES = 5 # number of matches used to find a mean of recent performance\nMIN_SEASON_MATCHES = 5 # minimum number of matches used for the seasonal performance calculation minimum\nGOAL_THRESHOLD = 2.5\nsave_features_file = \"goalFeatures\"\n\n# Connect to the database\ndbPath = \"../../data/\" # Path to database\ndbName = \"modDatabase.sqlite\"\nconn = sqlite3.connect(dbPath + dbName)\n\n# Load the required data from the database\nprint(\"\\nLoading from database...\")\nleague_data = pd.read_sql(\"SELECT * FROM League;\", conn)\nleague_id = league_data.loc[league_data['name'] == \"England Premier League\", 'id']\nmatch_data = pd.read_sql(\"SELECT * FROM Match WHERE Match.league_id = %d;\" % league_id, conn)\nconn.close()\n\n# Reformat the season from a string to an int representing the start year of the league\nmatch_data['season'] = match_data['season'].apply(lambda x: int(re.sub(\"/.*$\", \"\", x)))\n\n# Select relevant columns from database input\nprint(\"Selecting relevant data:\")\ngoal_data = get_goal_data(match_data)\nprint(\"Generating features...\")\ngoal_features = create_features(goal_data, GOAL_THRESHOLD, N_MATCHES_CHECKED)\ngoal_features = goal_features.set_index('id').sort_index()\n\n# Save to file\nprint(\"Saving features to file: \" + save_features_file + \".csv\")\ngoal_features.to_csv(save_features_file + \".csv\", index=True)\n","sub_path":"src/extractData.py","file_name":"extractData.py","file_ext":"py","file_size_in_byte":14099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"475962846","text":"#!/usr/bin/python\n\n'''\n对传入的URL列表去重\n'''\nimport hashlib\nimport json\nfrom urllib.parse import urlparse\nfrom urllib.parse import parse_qs\n\nclass Deldump:\n \n '''\n 针对传入的URL列表,通过计算md5的方式进行去重\n MD5(域名+PATH+参数)\n 目前无法处理POST请求参数中JSON格式的去重\n '''\n def deldumpurls(self,urllists):\n url = {}\n i = 1\n for oneurl in urllists:\n url_parse = urlparse(oneurl['url'])\n url_params = parse_qs(url_parse.query)\n url_postdata = parse_qs(oneurl['postdata'])\n #协议+域名+路径\n md5_r = url_parse.scheme +\"://\"+ url_parse.netloc + url_parse.path;\n for param in sorted(url_params.keys()):\n md5_r = md5_r + \"?\" + param + \"=&\"\n for param in sorted(url_postdata.keys()):\n md5_r = md5_r + \"?\" + param + \"=&\"\n md5_str = hashlib.md5(md5_r.encode('utf8')).hexdigest()\n if not (md5_str in url.keys()):\n oneurl['id'] = i\n url[md5_str] = oneurl\n i = i + 1\n \n return url\n \n ","sub_path":"SpiderScanner/tools/Deldump.py","file_name":"Deldump.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"180964032","text":"from app import database as db\nfrom fastapi import Response, HTTPException, status, APIRouter\nimport sqlite3\n\nrouter = APIRouter()\n\n@router.get(\"/tracks\")\nasync def get_tracks(response: Response, page: int = 0, per_page: int = 10):\n db.connection.row_factory = sqlite3.Row\n tracks = db.connection.execute(\"SELECT * FROM tracks ORDER BY TrackId \"\n \"LIMIT ? OFFSET ?\", (per_page, page*per_page, )).fetchall()\n response.status_code = status.HTTP_200_OK\n return tracks\n\n@router.get(\"/tracks/composers\")\nasync def get_composer_tracks(response: Response, composer_name: str):\n tracknames = db.connection.execute(\"SELECT Name FROM tracks WHERE Composer=? ORDER BY Name\", (composer_name, )).fetchall()\n if (tracknames == []):\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail={\"error\": \"No such composer\"}\n )\n response.status_code = status.HTTP_200_OK\n return [x[0] for x in tracknames]\n","sub_path":"app/routers/tracks.py","file_name":"tracks.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"206575107","text":"import json, os\nimport pickle\ndef compare(d1, d2, t='CIDEr'):\n assert d1.keys() == d2.keys()\n c1, c2, c3 = 0, 0, 0\n total = len(d1.keys())\n for k in d1.keys():\n if d1[k][t] > d2[k][t]:\n c1 += 1\n elif d1[k][t] == d2[k][t]:\n c2 += 1\n else:\n c3 += 1\n print(c1/total, c2/total, c3/total)\n \n\nd1 = json.load(open(\"/home/yangbang/VideoCaptioning/ARVC/nacf_ctmp_b6i5_135.json\", 'r'))\nd2 = json.load(open(\"/home/yangbang/VideoCaptioning/ARVC/nab_mp_b6i5_135.json\", 'r'))\nd3 = json.load(open(\"/home/yangbang/VideoCaptioning/ARVC/arb_b5.json\", 'r'))\nd4 = json.load(open(\"/home/yangbang/VideoCaptioning/ARVC/arb2_b5.json\", 'r'))\n\ncompare(d1, d2, 'Bleu_4')\ncompare(d1, d3, 'Bleu_4')\ncompare(d1, d4, 'Bleu_4')\n\n\ndef compare2(d1, d2, d3, d4=None):\n c1, c2, c3 = 0, 0, 0\n total = len(d1.keys())\n t1 = 'CIDEr'\n t2 = 'Bleu_4'\n target = []\n for k in d1.keys():\n if d1[k][t1] > d2[k][t1] and d1[k][t1] > d3[k][t1]:\n if d1[k][t2] > d2[k][t2] and d1[k][t2] > d3[k][t2]:\n if d4 is not None:\n s = d4[k][0].split(' ')\n if s[2] != '' or s[3] != '':\n print(k)\n target.append(k)\n else:\n target.append(k)\n c1 += 1\n print(c1/total)\n return target\nmp, mp_s = pickle.load(open(\"/home/yangbang/VideoCaptioning/ARVC/iterative_collect_results/MSRVTT_nv_AEmp_i5b6a135.pkl\", 'rb'))\nmpa, _ = pickle.load(open(\"/home/yangbang/VideoCaptioning/ARVC/iterative_collect_results/all/MSRVTT_nv_mp_i5b6a135.pkl\", 'rb'))\n\n\ntarget = compare2(d1, d2, d3)\n#target = compare2(d1, d2, d3, mp)\n\n\n\n#op = 'python generate_samples_to_compare.py --all --target %s'%(' '.join(target))\n#os.system(op)\n\ndef find_(data, tl):\n sub = [item for item in data if len(item.split(' ')) == tl]\n #for item in sub:\n # print(item)\n return sub[-1]\n\n\nkeylist = ['video7206','video7881','video9843','video9171','video9396','video7339']\n#keylist = mp.keys()\nc = 0\nfor k in target:#keylist:\n length = len(mp[k][-1].split(' '))\n s = find_(mpa[k], length)\n if mp[k][-1] != s and 'talk show' in mp[k][-1]:\n print(k, length, mp[k][-1], s)\n c+=1\nprint(c)\n\n\nmp, mp_s = pickle.load(open(\"/home/yangbang/VideoCaptioning/ARVC/iterative_collect_results/Youtube2Text_nv_AEmp_i5b5a100.pkl\", 'rb'))\nmpa, _ = pickle.load(open(\"/home/yangbang/VideoCaptioning/ARVC/iterative_collect_results/all/Youtube2Text_nv_mp_i5b5a100.pkl\", 'rb'))\nnab, _ = pickle.load(open(\"/home/yangbang/VideoCaptioning/ARVC/iterative_collect_results/Youtube2Text_mp_mp_i5b5a100.pkl\", 'rb'))\nkeylist = ['video1311','video1808','video1377']\n\nfor k in keylist:\n length = len(mp[k][-1].split(' '))\n s = find_(mpa[k], length)\n print(k, length, mp[k][-1], s, nab[k][-1])\n","sub_path":"analyze_codes/cider.py","file_name":"cider.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"539192589","text":"# -*-coding:utf-8-*-\nimport re\nfrom torchtext import data\nimport jieba\nimport logging\n\njieba.setLogLevel(logging.INFO)\n\nregex = re.compile(r'[^\\u4e00-\\u9fa5aA-Za-z0-9]')\n\n\ndef word_cut(text):\n text = regex.sub(' ', text)\n return [word for word in jieba.cut(text) if word.strip()]\n\n\ndef get_dataset(path, text_field, label_field):\n text_field.tokenize = word_cut\n train, dev = data.TabularDataset.splits(\n path=path, format='tsv', skip_header=False,\n train='train.tsv', validation='test.tsv',\n fields=[\n ('label', label_field),\n ('text1', text_field),\n ('text2', text_field)\n ]\n )\n return train, dev\n\n\ndef generate_test_dataset(path, text_field, file_name):\n text_field.tokenize = word_cut\n test = data.TabularDataset.splits(\n path=path, format='tsv', skip_header=False,\n train=file_name,\n fields=[\n ('text1', text_field),\n ('text2', text_field),\n ]\n )\n return test[0]\n","sub_path":"cl_dataset.py","file_name":"cl_dataset.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"263408433","text":"# write by xdd1997 xdd2026@qq.com\n\nimport os\nimport random\nimport requests\nimport urllib.request\nfrom bs4 import BeautifulSoup\n#微信下载图片的网址\nnum = random.randint(1,9999)\nurl = \"http://www.netbian.com/desk/{}.htm\".format(num)\n#url = \"http://www.netbian.com/desk/22152.htm\"\nr = requests.get(url)\ndemo = r.text\nsoup = BeautifulSoup(demo, \"html.parser\")\npiclist = []\nfor link in soup.find_all('img'):\n link_list = link.get('src')\n if link_list != None:\n piclist.append(link_list)\n\n# -------------递归创建的目录-----------\npath = \"F:\\desktop\\爬取的图片\"\nif not os.path.exists(path):\n os.makedirs(path)\n\nhttp = piclist[2]\nprint(http)\nfilesavepath = os.path.join(path, 'pic.jpg')\nurllib.request.urlretrieve(http, filesavepath)\nprint('下载完成,保存路径为' + path)\n\n","sub_path":"下载图片/下载彼岸桌面某一张照片.py","file_name":"下载彼岸桌面某一张照片.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"484991731","text":"\"\"\"\nStylization function\n\"\"\"\n\nimport logging\nfrom PIL import Image\n\nimport torch\nfrom torch import nn\nfrom torchvision import transforms\n\nfrom style_models import load_image, convert_from_tensor, convert_to_bytes, load_model\n\nTO_TENSOR = transforms.Compose([\n transforms.Resize(512),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n])\n\nlogger = logging.getLogger(\"styling\")\n\n\ndef stylize(content_image: Image, style_model: nn.Module) -> Image:\n \"\"\"\n NN stylization\n :param content_image: Image to stylize\n :param style_model: model for stylization\n :return: stylized image\n \"\"\"\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n content_image = TO_TENSOR(content_image)\n content_image = content_image.unsqueeze(0).to(device)\n\n with torch.no_grad():\n output = style_model(content_image).cpu()\n\n img = convert_from_tensor(output.squeeze(0))\n return img\n\n\ndef stylize_image(file, style: str) -> str:\n \"\"\"\n Preprocessing and stylization of bytes\n :param file: bytes of image\n :param style: name of style\n :return: stylized image as bytes\n \"\"\"\n logger.info(\"Start to load image\")\n content_image = load_image(file)\n orig_size = content_image.size\n logger.info(\"Image is loaded, image size %s, start loading model: %s.pth\" % (orig_size, style))\n style_model = load_model(style)\n logger.info(\"Model is loaded, start stylization with style %s\" % style)\n img = stylize(content_image, style_model)\n logger.info(\"Stylization is completed\")\n img = img.resize(orig_size)\n return convert_to_bytes(img)\n","sub_path":"stylize.py","file_name":"stylize.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"409268770","text":"###############################################################################\n#\n# imports and set up environment\n#\n###############################################################################\n'''Defining the environment for this class'''\nimport argparse\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport subprocess\nimport seaborn as sns\nimport scikitplot as skplt\nimport imblearn\nimport joblib\nimport logging\n\nimport matplotlib\nmatplotlib.use(\"Agg\")\n\nfrom imblearn.over_sampling import RandomOverSampler\nfrom imblearn.under_sampling import RandomUnderSampler\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.utils import resample\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score\nfrom sklearn.metrics import precision_recall_curve, roc_curve, roc_auc_score\nfrom sklearn.model_selection import RepeatedStratifiedKFold, RandomizedSearchCV\nfrom sklearn.model_selection import cross_val_score, cross_val_predict\nfrom datetime import datetime\nfrom scipy.stats import randint\nfrom scipy.stats import uniform\nfrom math import pi\nfrom pathlib import Path\n\n###############################################################################\n#\n# set up logging\n#\n###############################################################################\n\nlogging.basicConfig(level=logging.INFO, filename = \"training.log\", filemode = \"w\")\n\n###############################################################################\n#\n# define command line arguments\n#\n###############################################################################\n\ndef parse_command_line():\n '''defining the command line input to make it runable'''\n parser = argparse.ArgumentParser(\n description = \"AdaBoost and DecisionTree published hyperparameters\")\n\n parser.add_argument(\n \"--input\", \n type = str, \n dest = \"input\",\n default = \"\",\n help = \"The input CSV file\")\n\n parser.add_argument(\n \"--outdir\",\n type = str,\n dest = \"outdir\",\n default = \"\",\n help = \"Specify output directory\")\n\n args = parser.parse_args()\n if args.input == \"\":\n parser.print_help()\n exit(0)\n return args\n\n###############################################################################\n#\n# load the data from CSV file\n#\n###############################################################################\n\ndef load_metrix_data(csv_path):\n '''load the raw data as stored in CSV file'''\n # Load training files\n training_dir_path = Path(csv_path)\n assert (\n training_dir_path.exists()\n ), f\"Could not find directory at {training_dir_path}\"\n logging.info(f\"Opened dataframe containing training data\")\n return pd.read_csv(csv_path)\n \ndef make_output_folder(outdir):\n output_dir = os.path.join(outdir, \"decisiontree_ada_published\")\n os.makedirs(output_dir, exist_ok=True)\n return output_dir\n\n###############################################################################\n#\n# class for ML using random forest with randomised search and Ada boosting\n#\n###############################################################################\n\nclass RandomForestAdaRandSearch(object):\n '''This class is the doing the actual work in the following steps:\n * define smaller data frames: database, man_add, transform\n * split the data into training and test set\n * setup and run a randomized search for best paramaters to define a random forest\n * create a new random forest with best parameters\n * predict on this new random forest with test data and cross-validated training data\n * analyse the predisctions with graphs and stats\n '''\n def __init__(self, metrix, output_dir):\n self.metrix = metrix\n self.output_dir = output_dir\n self.prepare_metrix_data()\n self.split_data()\n self.forest_best_params()\n self.predict()\n self.analysis()\n\n def prepare_metrix_data(self):\n '''Function to create smaller dataframe.\n ******\n Input: large data frame\n Output: smaller dataframe\n '''\n print(\"*\" * 80)\n print(\"* Preparing input dataframe\")\n print(\"*\" * 80)\n\n columns = [\"anomalousCC\",\n \"anomalousslope\",\n \"lowreslimit\",\n \"f\",\n \"diffF\",\n \"diffI\",\n #\"autobuild_success\"]\n \"crank2_success\"]\n #\"autosharp_success\"]\n\n self.data = self.metrix[columns]\n\n logging.info(f\"Using dataframe with column labels {columns}\")\n\n###############################################################################\n#\n# creating training and test set\n#\n###############################################################################\n\n def split_data(self):\n '''Function which splits the input data into training set and test set.\n ******\n Input: a dataframe that contains the features and labels in columns and the samples\n in rows\n Output: sets of training and test data with an 80/20 split; X_train, X_test, y_train,\n y_test\n '''\n print(\"*\" * 80)\n print(\"* Splitting data into test and training set with test=20%\")\n print(\"*\" * 80)\n\n #y = self.metrix[\"autobuild_success\"]\n y = self.metrix[\"crank2_success\"]\n #y = self.metrix[\"autosharp_success\"]\n X = self.data[[\"anomalousCC\",\n \"anomalousslope\",\n \"lowreslimit\",\n \"f\",\n \"diffF\",\n \"diffI\"]]\n\n#stratified split of samples\n X_train, X_test, y_train, y_test = train_test_split(X, y,\n test_size=0.2,\n random_state=42,\n stratify=y)\n\n self.X_train = X_train\n self.X_test = X_test\n self.y_train = y_train\n self.y_test = y_test\n \n y_test_csv = os.path.join(self.output_dir, \"y_test.csv\")\n np.savetxt(y_test_csv, self.y_test, delimiter = \",\")\n\n X_train_shape = X_train.shape\n X_test_shape = X_test.shape\n y_train_shape = y_train.shape\n y_test_shape = y_test.shape\n\n logging.info(f\"Shape of test data X_train {X_train_shape}\")\n logging.info(f\"Shape of test data X_test {X_test_shape}\")\n logging.info(f\"Shape of test data y_train {y_train_shape}\")\n logging.info(f\"Shape of test data y_test {y_test_shape}\")\n\n\n###############################################################################\n#\n# optional step of over/undersampling if there is a large mis-match between classes\n#\n###############################################################################\n\n #the weight distribution for the classes used by \"class_weight\" weights = {0:0.1, 1:0.9}\n\n #print('*' *80)\n #print('* Applying Over/Undersampling and SMOTE')\n #print('*' *80)\n\n #oversample = RandomOverSampler(sampling_strategy = 'minority')\n #oversample = RandomOverSampler(sampling_strategy = 0.1)\n #oversample = SMOTE(sampling_strategy = 0.3, random_state=28)\n # fit and apply the transform\n #X_over, y_over = oversample.fit_resample(self.X_newdata_transform_train, self.y_train)\n\n #undersample = RandomUnderSampler(sampling_strategy=0.7)\n #X_over, y_over = undersample.fit_resample(X_over, y_over)\n #self.X_over = X_over\n #self.y_over = y_over\n\n###############################################################################\n#\n# creating classifier with best parameter from IUCrJ publication\n#\n###############################################################################\n\n def forest_best_params(self):\n '''create a new random forest using the best parameter combination found above'''\n print(\"*\" * 80)\n print(\"* Building new forest based on best parameter combination and save as pickle\")\n print(\"*\" * 80)\n\n# a blank decision tree with Ada Boost that can be used for hyperparameter search when\n# when starting from scratch\n# clf2 = DecisionTreeClassifier(**self.best_params_base_estimator,\n# random_state= 0)\n# self.tree_clf2_new_rand = AdaBoostClassifier(clf2,\n# **self.best_params_ada, \n# algorithm =\"SAMME.R\",\n# random_state=100)\n\n# hyperparameters as were used for the classifier published in IUCrJ; this was first run\n# in deployment with really bad performance;\n# the saved model is named: 2019 calibrated_classifier_20190501_1115.pkl\n clf2 = DecisionTreeClassifier(criterion=\"entropy\",\n max_depth=3,\n max_features=2,\n max_leaf_nodes=17,\n min_samples_leaf=8,\n min_samples_split=18,\n random_state= 0,\n class_weight = \"balanced\")\n self.tree_clf2_new_rand = AdaBoostClassifier(clf2,\n learning_rate=0.6355,\n n_estimators=5694,\n algorithm =\"SAMME.R\",\n random_state=5)\n\n# hyperparameters for a new classifier; this one was found after adding some user data\n# from run1 2020 to the training data; this one is now running in the automated data\n# analysis pipelines; the saved model is named: calibrated_classifier_20200408_1552.pkl\n# clf2 = DecisionTreeClassifier(criterion=\"entropy\",\n# max_depth=5,\n# max_features=2,\n# max_leaf_nodes=15,\n# min_samples_leaf=5,\n# min_samples_split=3,\n# random_state= 0,\n# class_weight = \"balanced\")\n# self.tree_clf2_new_rand = AdaBoostClassifier(\n# clf2,\n# learning_rate=0.6846,\n# n_estimators=4693,\n# algorithm =\"SAMME.R\",\n# random_state=5)\n\n classifier_params = self.tree_clf2_new_rand.get_params()\n print(classifier_params)\n\n self.tree_clf2_new_rand.fit(self.X_train, self.y_train)\n\n logging.info(\n f\"Created classifier based on IUCrJ publication and fitted training data.\\n\"\n f\"Classifier parameters: {classifier_params}\")\n\n###############################################################################\n#\n# Bootstrapping to find the 95% confidence interval\n#\n###############################################################################\n\n # Trying some bootstrap to assess confidence interval for classification\n print(\"*\" * 80)\n print(\"* Calculating confidence interval for best decisiontree with AdaBoost\")\n print(\"*\" * 80)\n\n def bootstrap_calc(data_train, data_test, train_labels, test_labels, found_model):\n # configure bootstrap\n n_iterations = 1000\n n_size = int(len(data_train))\n\n # run bootstrap\n stats = list()\n for i in range(n_iterations):\n # prepare train and test sets\n train_boot = resample(data_train, n_samples = n_size)\n test_boot = train_labels\n # fit model\n model = found_model\n model.fit(train_boot, test_boot)\n # evaluate model\n predictions = model.predict(data_test)\n score = accuracy_score(test_labels, predictions)\n stats.append(score)\n\n # plot scores\n plt.hist(stats)\n plt.savefig(os.path.join(self.output_dir, \"bootstrap_hist_ada.png\"), dpi=600)\n plt.close()\n # confidence interval\n alpha = 0.95\n p = ((1.0 - alpha) / 2.0) * 100\n lower = max(0.0, np.percentile(stats, p))\n p = (alpha + ((1.0 - alpha) / 2.0)) * 100\n upper = min(1.0, np.percentile(stats, p))\n \n lower_boundary = round((lower * 100), 2)\n upper_boundary = round((upper * 100), 2)\n \n logging.info(f\"Calculating 95% confidence interval from bootstrap exercise\\n\"\n f\"Lower boundary: {lower_boundary}\\n\"\n f\"Upper boundary: {upper_boundary}\")\n\n bootstrap_calc(self.X_train,\n self.X_test,\n self.y_train,\n self.y_test,\n self.tree_clf2_new_rand)\n\n###############################################################################\n#\n# get feature importances for best tree and full classifier;\n# plot feature importances for both\n#\n###############################################################################\n\n #print(self.tree_clf2_new_rand.estimators_)\n #print(self.tree_clf2_new_rand.feature_importances_)\n \n attr = [\"anomalousCC\",\n \"anomalousslope\",\n \"lowreslimit\",\n \"f\",\n \"diffF\",\n \"diffI\"]\n \n feature_importances = self.tree_clf2_new_rand.feature_importances_\n feature_importances_ls = sorted(zip(feature_importances, attr),\n reverse = True)\n #print(feature_importances_transform_ls)\n feature_importances_tree_mean = np.mean(\n [tree.feature_importances_ for tree in self.tree_clf2_new_rand.estimators_],\n axis = 0)\n\n feature_importances_tree_mean_ls = sorted(zip(feature_importances_tree_mean, attr),\n reverse = True)\n logging.info(\n f\"Feature importances, for best tree in classifier: {feature_importances_ls}\\n\"\n f\"Plotting bar plot of feature importances for best tree in classifier\\n\"\n f\"Feature importances, mean over all trees: {feature_importances_tree_mean_ls}\\n\"\n f\"Plotting bar plot of feature importances with mean and std for classifier\")\n\n def feature_importances_best_estimator(feature_list, directory):\n datestring = datetime.strftime(datetime.now(), \"%Y%m%d_%H%M\")\n feature_list.sort(key = lambda x: x[1], reverse = True)\n feature = list(zip(*feature_list))[1]\n score = list(zip(*feature_list))[0]\n x_pos = np.arange(len(feature))\n plt.bar(x_pos, score,align=\"center\")\n plt.xticks(x_pos, feature, rotation = 90, fontsize = 18)\n plt.title(\"Histogram of Feature Importances for best tree in best classifier\")\n plt.xlabel(\"Features\")\n plt.tight_layout()\n plt.savefig(os.path.join(directory,\n \"feature_importances_besttree_bestclassifier_bar_plot_\"+datestring+\".png\"),\n dpi = 600)\n plt.close()\n \n feature_importances_best_estimator(feature_importances_ls,\n self.output_dir)\n\n def feature_importances_pandas(clf, X_train, directory): \n datestring = datetime.strftime(datetime.now(), \"%Y%m%d_%H%M\") \n feature_list = []\n for tree in clf.estimators_:\n feature_importances_ls = tree.feature_importances_\n feature_list.append(feature_importances_ls)\n\n df = pd.DataFrame(feature_list, columns = X_train.columns)\n df_mean = df[X_train.columns].mean(axis = 0)\n df_std = df[X_train.columns].std(axis = 0)\n df_mean.plot(kind = \"bar\", color = \"b\", yerr = [df_std],\n align = \"center\", figsize = (20,10), rot = 90, fontsize = 18)\n plt.title(\n \"Histogram of Feature Importances over all trees in best classifier with std\")\n plt.xlabel('Features')\n plt.tight_layout()\n plt.savefig(os.path.join(directory,\n \"feature_importances_mean_std_bestclassifier_bar_plot_\"+datestring+\".png\"), dpi = 600)\n plt.close()\n \n feature_importances_pandas(self.tree_clf2_new_rand,\n self.X_train,\n self.output_dir)\n #feature_importances_pandas(self.tree_clf_rand_ada_new_transform, self.X_over, 'newdata_minusEP', self.newdata_minusEP)\n\n###############################################################################\n#\n# save best classifier as pickle file for future use\n#\n###############################################################################\n\n def write_pickle(forest, directory):\n datestring = datetime.strftime(datetime.now(), \"%Y%m%d_%H%M\")\n joblib.dump(forest,\n os.path.join(directory, \"best_classifier_rand_ada_\"+datestring+\".pkl\"))\n \n write_pickle(self.tree_clf2_new_rand,\n self.output_dir)\n\n logging.info(f\"Saving best classifier.\")\n\n print(\"*\" * 80)\n print(\"* Getting basic stats for new forest\")\n print(\"*\" * 80)\n\n###############################################################################\n#\n# get basic stats for 3-fold cross-validation on the training data\n#\n###############################################################################\n\n def basic_stats(forest, data_train, labels_train, directory):\n #distribution --> accuracy\n accuracy_each_cv = cross_val_score(forest, data_train,\n labels_train, cv=3, scoring=\"accuracy\")\n accuracy_mean_cv = round(cross_val_score(forest, data_train,\n labels_train, cv=3, scoring=\"accuracy\").mean(), 4)\n ## calculate cross_val_scoring with different scoring functions for CV train set\n train_roc_auc = round(cross_val_score(forest, data_train,\n labels_train, cv=3, scoring=\"roc_auc\").mean(), 4)\n train_recall = round(cross_val_score(forest, data_train,\n labels_train, cv=3, scoring=\"recall\").mean(), 4)\n train_precision = round(cross_val_score(forest, data_train,\n labels_train, cv=3, scoring=\"precision\").mean(), 4)\n train_f1 = round(cross_val_score(forest, data_train,\n labels_train, cv=3, scoring=\"f1\").mean(), 4)\n\n logging.info(\n f\"Get various cross_val_scores to evaluate clf performance for best parameters\\n\"\n f\"Training accuracy for individual folds in 3-fold CV: {accuracy_each_cv}\\n\"\n f\"Mean training accuracy over all folds in 3-fold CV: {accuracy_mean_cv}\\n\"\n f\"Mean training recall for 3-fold CV: {train_recall}\\n\"\n f\"Mean training precision for 3-fold CV: {train_precision}\\n\"\n f\"Mean training ROC_AUC for 3-fold CV: {train_roc_auc}\\n\"\n f\"Mean training F1 score for 3-fold CV: {train_f1}\")\n\n basic_stats(self.tree_clf2_new_rand,\n self.X_train,\n self.y_train,\n self.output_dir)\n\n###############################################################################\n#\n# predicting with test set\n#\n###############################################################################\n\n def predict(self):\n '''do predictions using the best classifier and the test set and doing some\n initial analysis on the output'''\n \n print(\"*\" * 80)\n print(\"* Predict using new forest and test set\")\n print(\"*\" * 80)\n\n #try out how well the classifier works to predict from the test set\n self.y_pred = self.tree_clf2_new_rand.predict(self.X_test)\n self.y_pred_proba = self.tree_clf2_new_rand.predict_proba(self.X_test)\n self.y_pred_proba_ones = self.y_pred_proba[:, 1]#test data to be class 1\n self.y_pred_proba_zeros = self.y_pred_proba[:, 0]#test data to be class 0\n \n y_pred_csv = os.path.join(self.output_dir, \"y_pred.csv\")\n y_pred_proba_csv = os.path.join(self.output_dir, \"y_pred_proba.csv\")\n \n np.savetxt(y_pred_csv, self.y_pred, delimiter = \",\")\n np.savetxt(y_pred_proba_csv, self.y_pred_proba, delimiter = \",\")\n\n# with open(y_pred_csv, \"w\", newline=\"\") as pred_csv:\n# pred_out = csv.writer(pred_csv)\n# pred_out.writerows(self.y_pred)\n\n logging.info(f\"Storing predictions for test set to y_pred.\\n\"\n f\"Storing probabilities for predictions for the test set to y_pred_proba\")\n\n print(\"*\" * 80)\n print(\"* Calculate prediction stats\")\n print(\"*\" * 80)\n\n def prediction_stats(y_test, y_pred, directory):\n # calculate accuracy\n y_accuracy = accuracy_score(y_test, y_pred)\n\n # examine the class distribution of the testing set (using a Pandas Series method)\n class_dist = self.y_test.value_counts()\n class_zero = class_dist[0]\n class_one = class_dist[1]\n\n self.biggest_class = 0\n if class_zero > class_one:\n self.biggest_class = class_zero\n else:\n self.biggest_class = class_one\n\n # calculate the percentage of ones\n # because y_test only contains ones and zeros,\n # we can simply calculate the mean = percentage of ones\n ones = round(y_test.mean(), 4)\n\n # calculate the percentage of zeros\n zeros = round(1 - y_test.mean(), 4)\n\n # calculate null accuracy in a single line of code\n # only for binary classification problems coded as 0/1\n null_acc = round(max(y_test.mean(), 1 - y_test.mean()), 4)\n\n logging.info(\n f\"Accuracy score or agreement between y_test and y_pred: {y_accuracy}\\n\"\n f\"Class distribution for y_test: {class_dist}\\n\"\n f\"Percent 1s in y_test: {ones}\\n\"\n f\"Percent 0s in y_test: {zeros}\\n\"\n f\"Null accuracy in y_test: {null_acc}\")\n\n prediction_stats(self.y_test,\n self.y_pred,\n self.output_dir)\n\n###############################################################################\n#\n# detailed analysis and stats\n#\n###############################################################################\n\n def analysis(self):\n '''detailed analysis of the output:\n * create a confusion matrix\n * split the data into TP, TN, FP, FN for test and train_CV\n * determine accuracy score\n * determine classification error\n * determine sensitivity\n * determine specificity\n * determine false-positive rate\n * determine precision\n * determine F1 score\n calculate prediction probabilities and draw plots\n * histogram for probability to be class 1\n * precision-recall curve\n * look for adjustments in classification thresholds\n * ROC curve\n * determine ROC_AUC\n * try different scoring functions for comparison'''\n\n print(\"*\" * 80)\n print(\"* Detailed analysis and plotting\")\n print(\"*\" * 80)\n\n###############################################################################\n#\n# calculate and draw confusion matrix for test set predictions\n#\n###############################################################################\n\n # IMPORTANT: first argument is true values, second argument is predicted values\n # this produces a 2x2 numpy array (matrix)\n\n conf_mat_test = confusion_matrix(self.y_test, self.y_pred)\n \n logging.info(f\"confusion matrix using test set: {conf_mat_test}\")\n def draw_conf_mat(matrix, directory):\n datestring = datetime.strftime(datetime.now(), \"%Y%m%d_%H%M\")\n labels = [\"0\", \"1\"] \n ax = plt.subplot()\n sns.heatmap(matrix, annot = True, ax = ax,\n annot_kws = {\"size\": 18}, vmin = 0, vmax = self.biggest_class)\n plt.title(\"Confusion matrix of the classifier\")\n ax.set_xticklabels(labels, fontdict = {\"fontsize\": 18})\n ax.set_yticklabels(labels, fontdict = {\"fontsize\": 18})\n plt.xlabel(\"Predicted\", fontsize = 20)\n plt.ylabel(\"True\", fontsize = 20)\n plt.tight_layout()\n plt.savefig(os.path.join(directory,\n \"confusion_matrix_for_test_set_predictions\"+datestring+\".png\"), dpi = 600)\n plt.close()\n\n draw_conf_mat(conf_mat_test,\n self.output_dir)\n\n###############################################################################\n#\n# calculate stats for the test set using classification outcomes\n#\n###############################################################################\n\n TP = conf_mat_test[1, 1]\n TN = conf_mat_test[0, 0]\n FP = conf_mat_test[0, 1]\n FN = conf_mat_test[1, 0]\n \n logging.info(f\"False-positives in predicting the test set: {FP}\")\n logging.info(f\"False-negatives in predicting the test set: {FN}\")\n\n #calculate accuracy\n acc_score_man_test = round((TP + TN) / float(TP + TN + FP + FN), 4)\n acc_score_sklearn_test = round(accuracy_score(self.y_test, self.y_pred), 4)\n #classification error\n class_err_man_test = round((FP + FN) / float(TP + TN + FP + FN), 4)\n class_err_sklearn_test = round(1 - accuracy_score(self.y_test, self.y_pred), 4)\n #sensitivity/recall/true positive rate; correctly placed positive cases\n sensitivity_man_test = round(TP / float(FN + TP), 4)\n sensitivity_sklearn_test = round(recall_score(self.y_test, self.y_pred), 4)\n #specificity\n specificity_man_test = round(TN / (TN + FP), 4)\n #false positive rate\n false_positive_rate_man_test = round(FP / float(TN + FP), 4)\n #precision/confidence of placement\n precision_man_test = round(TP / float(TP + FP), 4)\n precision_sklearn_test = round(precision_score(self.y_test, self.y_pred), 4)\n #F1 score; uses precision and recall\n f1_score_sklearn_test = round(f1_score(self.y_test, self.y_pred), 4)\n\n logging.info(f\"Detailed stats for the test set\\n\"\n f\"Accuracy score:\\n\"\n f\"accuracy score manual test: {acc_score_man_test}\\n\"\n f\"accuracy score sklearn test: {acc_score_sklearn_test}\\n\"\n f\"Classification error:\\n\"\n f\"classification error manual test: {class_err_man_test}\\n\"\n f\"classification error sklearn test: {class_err_sklearn_test}\\n\"\n f\"Sensitivity/Recall/True positives:\\n\"\n f\"sensitivity manual test: {sensitivity_man_test}\\n\"\n f\"sensitivity sklearn test: {sensitivity_sklearn_test}\\n\"\n f\"Specificity:\\n\"\n f\"specificity manual test: {specificity_man_test}\\n\"\n f\"False positive rate or 1-specificity:\\n\"\n f\"false positive rate manual test: {false_positive_rate_man_test}\\n\"\n f\"Precision or confidence of classification:\\n\"\n f\"precision manual: {precision_man_test}\\n\"\n f\"precision sklearn: {precision_sklearn_test}\\n\"\n f\"F1 score:\\n\"\n f\"F1 score sklearn test: {f1_score_sklearn_test}\")\n \n data_dict = {\"group\" : \"prediction\",\n \"ACC (%)\" : (acc_score_man_test * 100),\n \"Class Error (%)\" : (class_err_man_test * 100),\n \"Sensitivity (%)\" : (sensitivity_man_test * 100),\n \"Specificity (%)\" : (specificity_man_test * 100),\n \"FPR (%)\" : (false_positive_rate_man_test * 100),\n \"Precision (%)\" : (precision_man_test * 100),\n \"F1 score (%)\" : (f1_score_sklearn_test * 100)}\n \n df = pd.DataFrame(data = data_dict, index = [0])\n \n def plot_radar_chart(df, directory):\n datestring = datetime.strftime(datetime.now(), '%Y%m%d_%H%M')\n\n # ------- PART 1: Create background\n\n # number of variable\n categories = list(df)[1:]\n print(categories)\n N = len(categories)\n\n # What will be the angle of each axis in the plot? (we divide the plot / number of variable)\n angles = [n / float(N) * 2 * pi for n in range(N)]\n angles += angles[:1]\n\n # Initialise the spider plot\n #fig = plt.figure(figsize=(9, 9))\n fig = plt.figure(figsize=(7, 6))\n ax = fig.add_subplot(111, polar = True)\n\n # If you want the first axis to be on top:\n ax.set_theta_offset(pi / 2)\n ax.set_theta_direction(-1)\n\n # Draw one axe per variable + add labels labels yet\n ax.set_xticks(angles[:-1])\n ax.set_xticklabels(categories, fontsize = 20, wrap = True)\n #plt.xticks(angles[:-1], categories)\n\n # Draw ylabels\n ax.set_rlabel_position(15)\n ax.set_yticks([20, 40, 60, 80, 100])\n ax.set_yticklabels([\"20\", \"40\", \"60\", \"80\", \"100%\"], fontsize = 20, wrap = True)\n ax.set_ylim(0, 100)\n\n # ------- PART 2: Add plots\n #values = df.loc[0].values.flatten().tolist()\n values = df.loc[0].drop('group').values.flatten().tolist()\n print(values)\n values += values[:1]\n ax.plot(angles, values, linewidth = 2, linestyle = \"solid\", label = \"Test set\")\n ax.fill(angles, values, \"b\", alpha = 0.1)\n plt.savefig(os.path.join(directory,\n \"radar_chart_for_test_set_\"+datestring+\".png\"),\n dpi = 600)\n plt.close()\n\n plot_radar_chart(df, self.output_dir)\n\n###############################################################################\n#\n# plot histogram of test set probabilities\n#\n###############################################################################\n\n #plot histograms of probabilities \n def plot_hist_pred_proba(y_pred_proba, directory):\n datestring = datetime.strftime(datetime.now(), \"%Y%m%d_%H%M\")\n plt.hist(y_pred_proba[1], bins = 20, color = \"b\", label = \"class 1\")\n plt.hist(y_pred_proba[0], bins = 20, color = \"g\", label = \"class 0\")\n plt.xlim(0, 1)\n plt.title(\"Histogram of predicted probabilities for class 1 in the test set\")\n plt.xlabel(\"Predicted probability of EP_success\")\n plt.ylabel(\"Frequency\")\n plt.legend(loc = \"best\")\n plt.tight_layout()\n plt.savefig(os.path.join(directory, \"hist_pred_proba_\"+datestring+\".png\"), dpi = 600)\n plt.close()\n\n plot_hist_pred_proba(self.y_pred_proba,\n self.output_dir)\n\n###############################################################################\n#\n# plot precision-recall curve for class 1 samples in test set\n#\n###############################################################################\n\n #plot Precision Recall Threshold curve for test set class 1\n precisions, recalls, thresholds = precision_recall_curve(self.y_test,\n self.y_pred_proba_ones)\n\n def plot_precision_recall_vs_threshold(precisions, recalls, thresholds, directory):\n datestring = datetime.strftime(datetime.now(), \"%Y%m%d_%H%M\")\n plt.plot(thresholds, precisions[:-1], \"b--\", label = \"Precision\")\n plt.plot(thresholds, recalls[:-1], \"g--\", label = \"Recall\")\n plt.title(\"Precsion-Recall plot for classifier, test set, class 1\")\n plt.xlabel(\"Threshold\")\n plt.legend(loc = \"upper left\")\n plt.ylim([0, 1])\n plt.tight_layout()\n plt.savefig(os.path.join(directory, \"Precision_Recall_class1_\"+datestring+\".png\"),\n dpi = 600)\n plt.close()\n\n plot_precision_recall_vs_threshold(precisions,\n recalls,\n thresholds,\n self.output_dir)\n\n###############################################################################\n#\n# plot ROC curve, calculate AUC and explore thresholds for class 1 samples in test set\n#\n###############################################################################\n\n #IMPORTANT: first argument is true values, second argument is predicted probabilities\n #we pass y_test and y_pred_prob\n #we do not use y_pred, because it will give incorrect results without generating an error\n #roc_curve returns 3 objects fpr, tpr, thresholds\n #fpr: false positive rate\n #tpr: true positive rate\n fpr_1, tpr_1, thresholds_1 = roc_curve(self.y_test,\n self.y_pred_proba_ones)\n AUC_test_class1 = round(roc_auc_score(self.y_test,\n self.y_pred_proba_ones), 4)\n logging.info(f\"AUC score for class 1 in test set: {AUC_test_class1}\")\n \n #plot ROC curves manual approach\n def plot_roc_curve(fpr, tpr, directory):\n datestring = datetime.strftime(datetime.now(), \"%Y%m%d_%H%M\")\n plt.plot(fpr, tpr, linewidth = 2)\n plt.plot([0, 1], [0, 1], \"k--\")\n plt.axis([0, 1, 0, 1])\n plt.title(\"ROC curve for classifier, test set, class 1\") \n plt.xlabel(\"False Positive Rate (1 - Specificity)\")\n plt.ylabel(\"True Positive Rate (Sensitivity)\")\n plt.grid(True)\n plt.text(0.7, 0.1, r\"AUC = {AUC_test_class1}\")\n plt.tight_layout()\n plt.savefig(os.path.join(directory, \"ROC_curve_class1_\"+datestring+\".png\"), dpi = 600)\n plt.close()\n\n plot_roc_curve(fpr_1,\n tpr_1,\n self.output_dir)\n\n #plot ROC curves using scikit_plot method\n def plot_roc_curve_skplot(y_test, y_proba, directory):\n datestring = datetime.strftime(datetime.now(), \"%Y%m%d_%H%M\")\n skplt.metrics.plot_roc(y_test, y_proba, title = \"ROC curve\")\n plt.tight_layout()\n plt.savefig(os.path.join(directory, \"ROC_curve_skplt_class1_\"+datestring+\".png\"),\n dpi = 600)\n plt.close()\n\n plot_roc_curve_skplot(self.y_test,\n self.y_pred_proba,\n self.output_dir)\n\n # define a function that accepts a threshold and prints sensitivity and specificity\n def evaluate_threshold(tpr, fpr, thresholds, threshold):\n sensitivity = round(tpr[thresholds > threshold][-1], 4)\n specificity = round(1 - fpr[thresholds > threshold][-1], 4)\n \n logging.info(f\"Sensitivity for class 1 at threshold {threshold}: {sensitivity}\\n\"\n f\"Specificity for class 1 at threshold {threshold}: {specificity}\")\n\n evaluate_threshold(tpr_1, fpr_1, thresholds_1, 0.7)\n evaluate_threshold(tpr_1, fpr_1, thresholds_1, 0.6)\n evaluate_threshold(tpr_1, fpr_1, thresholds_1, 0.5)\n evaluate_threshold(tpr_1, fpr_1, thresholds_1, 0.4)\n evaluate_threshold(tpr_1, fpr_1, thresholds_1, 0.3)\n evaluate_threshold(tpr_1, fpr_1, thresholds_1, 0.2)\n\n # Try to copy log file if it was created in training.log\n try:\n shutil.copy(\"training.log\", self.output_dir)\n except FileExistsError:\n logging.warning(\"Could not find training.log to copy\")\n except Exception:\n logging.warning(\"Could not copy training.log to output directory\")\n\ndef run():\n args = parse_command_line()\n \n \n ###############################################################################\n\n #look at the imported data to get an idea what we are working with\n metrix = load_metrix_data(args.input)\n\n output_dir = make_output_folder(args.outdir)\n \n ###############################################################################\n\n random_forest_ada_rand_search = RandomForestAdaRandSearch(metrix, output_dir)\n\n","sub_path":"metrix_ml/obsolete/decisiontree/obsolete/decisiontree_ada_randomsearch_topFeatures_deployment_published.py","file_name":"decisiontree_ada_randomsearch_topFeatures_deployment_published.py","file_ext":"py","file_size_in_byte":34953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"1461160","text":"import os \nimport matplotlib\nimport re\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nimport seaborn as sns\n\nnames = [\n # 'logs/tetris_single_ppo_skip4_grid_large',\n # 'logs/tetris_single_ppo_skip4_grid_large_num8',\n # 'logs/tetris_single_ppo_skip4_grid_large_num128',]\n # 'logs/tetris_single_ppo_skip4_grid_large_mini32',]\n # 'logs/tetris_single_ppo_skip4_grid_large_ent0',]\n # 'logs/tetris_single_ppo_skip1_grid_large',]\n 'logs/tetris_single_ppo_IOL_{c,h,d}_224_frames12_2mins',\n 'logs/tetris_single_ppo_IOL_{c,h,d}_224_frames8_2mins']\n\nrewards = []\nline_sents = []\niterations = []\n\nmin_max_iteration = np.inf\n\nfor name in names:\n with open(name) as f:\n lines = f.readlines()\n rewards.append([])\n line_sents.append([])\n iterations.append([])\n for line in lines:\n line = re.split(\"[ ,/]+\", line)\n # print(line)\n if (len(line) > 5):\n if (line[0] == \"Updates\"):\n iterations[-1].append(int(line[4]))\n if (line[1] == \"Last\"):\n rewards[-1].append(float(line[8]))\n if (line[1] == \"lines\"):\n line_sents[-1].append(float(line[6]))\n\n min_max_iteration = min(min_max_iteration, iterations[-1][-1])\n\nfor i, name in enumerate(names):\n break_point = 0\n for j, iteration in enumerate(iterations[i]):\n if (iteration < min_max_iteration):\n break_point = j\n else:\n break\n \n iterations[i] = iterations[i][:j]\n rewards[i] = rewards[i][:j]\n line_sents[i] = line_sents[i][:j]\n\n## post-process data, set the iteration i ~ i + k to i\nfreq = 25\n\nfor i, name in enumerate(names):\n for j, iteration in enumerate(iterations[i]):\n if j % freq == 0:\n pre = iteration\n else:\n iterations[i][j] = pre\n\nstyles = [':', '-']\n\ncolors_light = ['lightblue', 'lightgreen', 'mistyrose', 'lightcyan', 'violet', \n 'lightyellow', 'lightgray', 'lightpink'] \ncolors = ['blue', 'green', 'red', 'cyan', 'magenta', 'yellow', 'gray', 'pink'] \n\n# fig, ax1 = plt.subplots()\nsns.set()\nfor i, name in enumerate(names):\n # df = pd.DataFrame(rewards[i])\n # print(rewards[i])\n x = np.asarray(iterations[i])\n y = np.asarray(rewards[i])\n\n ax = sns.lineplot(x=x, y=y, label=name)\n # ax1.plot(iterations[i], df, colors_light[i])\n # ax1.plot(iterations[i], df.rolling(50).mean(), colors[i], label=name)\n# ax1.tick_params(axis='y', labelcolor=color)\n\nax.set_xlabel('iterations')\nax.set_ylabel('rewards')\n\n# plt.legend()\n# fig.tight_layout() # otherwise the right y-label is slightly clipped\n\nplt.savefig(\"rewards.png\")\n\nplt.clf()\n\n# fig, ax2 = plt.subplots()\n\n# ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis\n\ncolor = 'tab:blue'\n\nfor i, name in enumerate(names):\n x = np.asarray(iterations[i])\n y = np.asarray(line_sents[i])\n\n ax = sns.lineplot(x=x, y=y, label=name)\n\nplt.legend()\n\nax.set_xlabel('iterations')\n\nax.set_ylabel('line_sents') # we already handled the x-label with ax1\n\nplt.savefig(\"line.png\")\n","sub_path":"plot_2.py","file_name":"plot_2.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"574377655","text":"\n\ndef make_shades(alley, k):\n a = alley\n b = a\n c = []\n for i in range(len(a)):\n if a[i] != 0:\n for j in range(a[i] * k):\n b.append(1)\n else:\n b[i] += 0\n # print(b)\n for i in b:\n if i == 0:\n c.append(False)\n else:\n c.append(True)\n return c\n\n","sub_path":"First year/Функция/Тень, знай своё место.py","file_name":"Тень, знай своё место.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"413124990","text":"# 有 N 个房间,开始时你位于 0 号房间。每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间。 \n# \n# 在形式上,对于每个房间 i 都有一个钥匙列表 rooms[i],每个钥匙 rooms[i][j] 由 [0,1,...,N-1] 中的一个整数表示,其中 \n# N = rooms.length。 钥匙 rooms[i][j] = v 可以打开编号为 v 的房间。 \n# \n# 最初,除 0 号房间外的其余所有房间都被锁住。 \n# \n# 你可以自由地在房间之间来回走动。 \n# \n# 如果能进入每个房间返回 true,否则返回 false。 \n# \n# \n# \n# \n# 示例 1: \n# \n# 输入: [[1],[2],[3],[]]\n# 输出: true\n# 解释: \n# 我们从 0 号房间开始,拿到钥匙 1。\n# 之后我们去 1 号房间,拿到钥匙 2。\n# 然后我们去 2 号房间,拿到钥匙 3。\n# 最后我们去了 3 号房间。\n# 由于我们能够进入每个房间,我们返回 true。\n# \n# \n# 示例 2: \n# \n# 输入:[[1,3],[3,0,1],[2],[0]]\n# 输出:false\n# 解释:我们不能进入 2 号房间。\n# \n# \n# 提示: \n# \n# \n# 1 <= rooms.length <= 1000 \n# 0 <= rooms[i].length <= 1000 \n# 所有房间中的钥匙数量总计不超过 3000。 \n# \n# Related Topics 深度优先搜索 图\n\n\nclass Solution:\n def canVisitAllRooms(self, rooms) -> bool:\n m = len(rooms)\n visited = [False for _ in range(m)]\n visited[0] = True\n from collections import deque\n q = deque()\n q.append(rooms[0])\n while q:\n keys = q.popleft()\n for key in keys:\n if not visited[key]:\n visited[key] = True\n q.append(rooms[key])\n\n for room in visited:\n if not room:\n return False\n\n return True\n\n\nif __name__ == '__main__':\n s = Solution()\n assert (not s.canVisitAllRooms([[1, 3], [3, 0, 1], [2], [0]]))\n","sub_path":"bfs_dfs/bfs/[841]钥匙和房间.py","file_name":"[841]钥匙和房间.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"371758937","text":"from BubotObj.OcfDevice.OcfDevice import OcfDevice\nfrom Bubot.Core.CatalogObjApi import CatalogObjApi\nfrom Bubot.Helpers.Action import async_action\nfrom Bubot.Helpers.ExtException import ExtException, KeyNotFound\n\n\nclass OcfDeviceApi(CatalogObjApi):\n handler = OcfDevice\n\n @async_action\n async def api_discover(self, view, **kwargs):\n handler, data = await self.prepare_json_request(view)\n result = []\n devices = await view.device.transport_layer.discovery_resource()\n await view.notify({'message': f'found {len(devices)}'})\n for _id in devices:\n di = devices[_id].di\n try:\n _device = await handler.find_by_id(di)\n except KeyNotFound:\n _device = devices[_id].to_object_data()\n\n result.append(_device)\n\n return self.response.json_response(result)\n\n @async_action\n async def api_mass_add(self, view, **kwargs):\n action = kwargs['_action']\n handler, data = await self.prepare_json_request(view)\n for device_data in data['items']:\n action.add_stat(await handler.update(device_data))\n return self.response.json_response({})\n\n @async_action\n async def api_mass_delete(self, view, **kwargs):\n action = kwargs['_action']\n handler, data = await self.prepare_json_request(view)\n for device_data in data['items']:\n action.add_stat(await handler.delete_one(device_data['_id']))\n return self.response.json_response({})\n","sub_path":"src/BubotObj/OcfDevice/OcfDeviceApi.py","file_name":"OcfDeviceApi.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"218042090","text":"from os import path\nimport unittest\nfrom ..env import EnvInspector, inspect_env_package\n\n\ndef data_path(filename):\n return path.join(path.dirname(__file__), 'data', filename)\n\n\nclass EnvInspectorTestCase(unittest.TestCase):\n def test_package_name(self):\n with open(data_path('environment.yml')) as fileobj:\n assert EnvInspector('environment.yml', fileobj).name == 'stats'\n\n def test_version(self):\n with open(data_path('environment.yml')) as fileobj:\n self.assertIsInstance(EnvInspector('environment.yml', fileobj).version, str)\n\n\nclass InspectEnvironmentPackageTest(unittest.TestCase):\n def test_inspect_env_package(self):\n with open(data_path('environment.yml')) as fileobj:\n package_data, release_data, file_data = inspect_env_package(\n 'environment.yml', fileobj)\n\n self.assertEqual({\n 'name': 'stats',\n 'summary': 'Environment file'\n }, package_data)\n\n self.assertEqual({\n 'basename': 'environment.yml',\n 'attrs': {}\n }, file_data)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"lib/python2.7/site-packages/binstar_client/inspect_package/tests/test_env.py","file_name":"test_env.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"574500305","text":"from random import random\nfrom math import sqrt\nimport time\nDATES = 2**20\nhits = 0.0\nt=time.perf_counter()\nfor i in range(1,DATES+1):\n x,y = random(),random()\n dist = sqrt(x**2+y**2)\n if dist <= 1.0:\n hits = hits +1\npi = 4*(hits/DATES)\nt -= time.perf_counter()\nprint(\"pi的值是{}\".format(pi))\nprint(\"运行时间是:{:.5f}s\".format(-t))\n","sub_path":"Python/代码/蒙特罗卡方法解决pi值.py","file_name":"蒙特罗卡方法解决pi值.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"99029225","text":"# -*- coding: utf-8 -*-\n\nimport xlrd\nimport jieba\nimport random\nimport requests\nimport simhash\nimport time\nimport json\n\nCITIES = {\n \"北京\": \"100001000\",\n \"成都市\": \"200002000\",\n \"广州市\": \"300003000\"\n}\n\n\nclass FeedIndex(dict):\n def __init__(self, row):\n self.__setitem__(\"cityid\", CITIES[row[0].encode(\"utf-8\")])\n keywords = list(jieba.cut(row[1]))\n self.__setitem__(\"title\", row[1])\n # self.__setitem__(\"poi_id\", row[2])\n self.__setitem__(\"cover_poi_info\", row[3])\n self.__setitem__(\"source_name\", row[5])\n self.__setitem__(\"publish_time\", row[6])\n self.__setitem__(\"update_time\", int(time.time()) - random.randint(0, 100000))\n self.__setitem__(\"top_start_time\", int(time.time()) - random.randint(-100000, 100000))\n self.__setitem__(\"top_end_time\", int(time.time()) - random.randint(-100000, 100000))\n self.__setitem__(\"status\", 2)\n self.__setitem__(\"is_splendid\", 1 if random.random() > 0.7 else 0)\n self.__setitem__(\"delete_flag\", 1 if random.random() > 0.9 else 0)\n self.__setitem__(\"merchant_top_flag\", 1 if random.random() > 0.9 else 0)\n self.__setitem__(\"feed_top_flag\", 1 if random.random() > 0.9 else 0)\n self.__setitem__(\"source_type\", random.randint(0, 2))\n self.__setitem__(\"type\", random.randint(1, 2))\n self.__setitem__(\"status\", 2)\n self.__setitem__(\"weight\", random.randint(1, 100))\n self.__setitem__(\"tags\", keywords)\n self.__setitem__(\"strategy_info\", {\n \"weighted_tags\": [{\"key\": k, \"weight\": int(random.randint(1, 100))} for k in keywords],\n \"posible_city\": [{\"key\": CITIES[row[0].encode(\"utf-8\")], \"weight\": int(random.randint(1, 100))}]\n })\n self.__setitem__(\"simhash\", str(simhash.Simhash(row[1] + row[5]).value))\n self.__setitem__(\"article_id\", str(simhash.Simhash(row[1] + row[5]).value))\n\n\ndef read_excel(filename):\n f = xlrd.open_workbook(filename)\n sheet = f.sheet_by_index(0)\n for i in range(1, sheet.nrows)[::-1]:\n row = sheet.row_values(i)\n # print(row)\n try:\n yield FeedIndex(row)\n except:\n pass\n\n\nif __name__ == \"__main__\":\n\n for i, feed in enumerate(read_excel(r\"D:\\fun\\github\\LearnPython\\feed\\nmh_spider_article1.xlsx\")):\n # print(json.dumps(feed))\n # raise\n response = requests.post(\n \"http://10.195.6.22:8100/feed/articles/\",\n # \"http://10.208.150.51:8181/feed/articles/\",\n data=json.dumps(feed),\n )\n # print(response.request.body)\n if i % 1000 == 100:\n print(\"Dealing with feed: %s\" % i)\n # raise\n # print(response.text)\n # raise\n","sub_path":"feed/es_data_faker.py","file_name":"es_data_faker.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"134000107","text":"import random\nimport imp\nimport matplotlib.pyplot as plt\nclass Perceptron:\n def __init__(self, input_number,step_size=0.1):\n self._ins = input_number # 3\n self._w = [random.random() for _ in range(input_number)] # Arreglo con numeros aleatorios\n self._eta = step_size # 0.1\n\n def predict(self, inputs):\n weighted_average = sum(w*elm for w,elm in zip(self._w,inputs))\n if weighted_average > 0:\n return 1\n return 0\n\n def train(self, inputs,ex_output):\n output = self.predict(inputs)\n error = ex_output - output\n if error != 0:\n self._w = [w+self._eta*error*x for w,x in zip(self._w,inputs)]\n return error\n\n#!/usr/bin/env python\n\n# Datos de hombres y mujeres\ninput_data = [[40, 38, 25000, 1],\n [25, 25, 10000, 0],\n [35, 30, 12000, 1],\n [23, 22, 8000, 0],\n [29, 28, 16000, 1],\n [28, 26, 5000, 0],\n [32, 28, 13500, 1],\n [20, 43, 7500, 0],\n [29, 25, 16000, 1]]\n\npr = Perceptron(4,0.1) # Perceptron con 3 entradas\nweights = [] # Lista con los pesos\nerrors = [] # Lista con los errores\n\n# Fase de entrenamiento\nfor _ in range(100):\n for person in input_data:\n output = person[-1]\n inp = [1] + person[0:-1]\n weights.append(pr._w)\n err = pr.train(inp,output)\n errors.append(err)\n\nh = float(input(\"Edad del hombre: \"))\nw = float(input(\"Edad de la mujer: \"))\ns = float(input(\"Salario entre ambos, mensual: \"))\n\nif pr.predict([1,h,w,s]) == 1: print(\"Exito\")\nelse: print(\"Fracaso\")\n\nprint([1,h,w,s])\n","sub_path":"simple_perceptron/fracaso.py","file_name":"fracaso.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"298914837","text":"\nrace_data = [\n\t# name str dex con int hairline shoulderline size\n\t('human', 1, 1, 1, 1, -2, 0, 'human'),\n\t('minotaur', 3, 0, 0, 0, -6, 0, None),\n\t('imp', 0, 3, 0, 0, 1, 0, None),\n\t#('treant', 0, 0, 3, 0, 0, 0),\n\t('mindflayer', 0, 0, 0, 3, -4, 0, 'human'),\n\t('orc', 2, 1, 0, 0, 0, 0, 'dwarf'),\n\t('ogre', 2, 0, 1, 0, -6, 0, None),\n\t('djinn', 2, 0, 0, 1, -3, 0, 'human'),\n\t('thiefling', 0, 2, 1, 0, -2, 0, 'human'),\n\t('elf', 0, 2, 0, 1, -4, 0, 'elf'),\n\t('goblin', 1, 2, 0, 0, 1, 0, 'gnome'),\n\t('mummy', 0, 0, 2, 1, -4, 0, 'human'),\n\t('dwarf', 1, 0, 2, 0, 1, 0, 'dwarf'),\n\t('werewolf', 0, 1, 2, 0, -2, 0, None),\n\t#('myconid', 1, 0, 0, 2, 0, 0),\n\t('gnome', 0, 1, 0, 2, 0, 0, 'gnome'),\n\t('vampire', 0, 0, 1, 2, -2, 0, 'human'),\n]\n\nclass Race:\n\tdef __init__(self, name, str, dex, con, int, hairline, shoulderline, armorsize):\n\t\tself.name = name\n\t\tself.base_str = str\n\t\tself.base_dex = dex\n\t\tself.base_con = con\n\t\tself.base_int = int\n\t\tself.hairline = hairline\n\t\tself.shoulderline = shoulderline\n\t\tself.armorsize = armorsize\n\nraces = {}\nfor name, str, dex, con, int, hairline, shoulderline, armorsize in race_data:\n\traces[name] = Race(name, str, dex, con, int, hairline, shoulderline, armorsize)\n\n","sub_path":"src/race.py","file_name":"race.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"480513035","text":"#encoding=utf-8\nfrom __future__ import unicode_literals\nimport sys\nimport locale\nimport gettext\nimport yaml\nimport os\nimport psutil\n\nimport logging\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\nlogfile = sys.stdout\ndef log(msg, newline = True):\n if newline:\n msg = msg + '\\n'\n logfile.write(msg.encode('utf-8'))\n logfile.flush()\n\ndef init_localization(cl = ''):\n '''prepare i18n'''\n if cl != '':\n if type(cl) != list:\n cl = [cl]\n #['nb_NO.UTF-8', 'nb_NO.utf8', 'no_NO']:\n for loc in cl:\n try:\n # print \"Trying (\", loc.encode('utf-8'), 'utf-8',\")\"\n locale.setlocale(locale.LC_ALL, (loc.encode('utf-8'), 'utf-8'))\n logger.info('Using locale %s', loc)\n #logger.info('Locale set to %s' % loc)\n break\n except locale.Error:\n try:\n locstr = (loc + '.UTF-8').encode('utf-8')\n # print \"Trying\",locstr\n locale.setlocale(locale.LC_ALL, locstr )\n logger.info('Using locale %s', loc)\n break\n except locale.Error:\n pass\n lang, charset = locale.getlocale()\n if lang == None:\n raise StandardError(\"Failed to set locale!\")\n t = gettext.translation('messages', 'locale', fallback=True, languages=[lang])\n return t, t.ugettext\n\n\nprocess = psutil.Process(os.getpid())\n\ndef get_mem_usage():\n \"\"\" Returns memory usage in MBs \"\"\"\n return process.memory_info().rss / 1024.**2\n","sub_path":"bot/ukcommon.py","file_name":"ukcommon.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"613207463","text":"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\nimport io\nimport pdqhash\nimport pathlib\nimport numpy as np\nfrom PIL import Image\nimport typing as t\n\n\nPDQOutput = t.Tuple[\n str, int\n] # hexadecimal representation of the Hash vector and a numerical quality value\n\n\ndef pdq_from_file(path: pathlib.Path) -> PDQOutput:\n \"\"\"\n Given a path to a file return the PDQ Hash string in hex.\n Current tested against: jpg\n \"\"\"\n img_pil = Image.open(path)\n image = _check_dimension_and_expand_if_needed(np.asarray(img_pil))\n return _pdq_from_numpy_array(image)\n\n\ndef pdq_from_bytes(file_bytes: bytes) -> PDQOutput:\n \"\"\"\n For the bytestream from an image file, compute PDQ Hash and quality.\n \"\"\"\n np_array = _check_dimension_and_expand_if_needed(\n np.asarray(Image.open(io.BytesIO(file_bytes)))\n )\n return _pdq_from_numpy_array(np_array)\n\n\ndef _pdq_from_numpy_array(array: np.ndarray) -> PDQOutput:\n hash_vector, quality = pdqhash.compute(array)\n\n bin_str = \"\".join([str(x) for x in hash_vector])\n\n # binary to hex using format string\n # '%0*' is for padding up to ceil(num_bits/4),\n # '%X' create a hex representation from the binary string's integer value\n hex_str = \"%0*X\" % ((len(bin_str) + 3) // 4, int(bin_str, 2))\n hex_str = hex_str.lower()\n\n return hex_str, quality\n\n\ndef _check_dimension_and_expand_if_needed(array: np.ndarray) -> np.ndarray:\n \"\"\"\n Convert 2 dim array to the 3 dim 'pdqhash' expects\n (without this black and white images result in errors).\n \"\"\"\n if array.ndim == 2:\n array = np.concatenate([array[..., np.newaxis]] * 3, axis=2)\n return array\n","sub_path":"python-threatexchange/threatexchange/signal_type/pdq/pdq_hasher.py","file_name":"pdq_hasher.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"344042338","text":"from typing import Any\nfrom typing import List\nfrom typing import Tuple\nfrom typing import Union\n\nimport numpy as np\nimport torch\n\nfrom tkdet.layers import interpolate\n\n__all__ = [\"Keypoints\", \"heatmaps_to_keypoints\"]\n\n\nclass Keypoints(object):\n def __init__(self, keypoints: Union[torch.Tensor, np.ndarray, List[List[float]]]):\n device = keypoints.device if isinstance(keypoints, torch.Tensor) else torch.device(\"cpu\")\n keypoints = torch.as_tensor(keypoints, dtype=torch.float32, device=device)\n assert keypoints.dim() == 3 and keypoints.shape[2] == 3, keypoints.shape\n self.tensor = keypoints\n\n def __len__(self) -> int:\n return self.tensor.size(0)\n\n def to(self, *args: Any, **kwargs: Any) -> \"Keypoints\":\n return type(self)(self.tensor.to(*args, **kwargs))\n\n @property\n def device(self) -> torch.device:\n return self.tensor.device\n\n def to_heatmap(self, boxes: torch.Tensor, heatmap_size: int) -> torch.Tensor:\n return _keypoints_to_heatmap(self.tensor, boxes, heatmap_size)\n\n def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> \"Keypoints\":\n if isinstance(item, int):\n return Keypoints([self.tensor[item]])\n return Keypoints(self.tensor[item])\n\n def __repr__(self) -> str:\n s = self.__class__.__name__ + \"(\"\n s += \"num_instances={})\".format(len(self.tensor))\n return s\n\n\ndef _keypoints_to_heatmap(\n keypoints: torch.Tensor,\n rois: torch.Tensor, heatmap_size: int\n) -> Tuple[torch.Tensor, torch.Tensor]:\n if rois.numel() == 0:\n return rois.new().long(), rois.new().long()\n offset_x = rois[:, 0]\n offset_y = rois[:, 1]\n scale_x = heatmap_size / (rois[:, 2] - rois[:, 0])\n scale_y = heatmap_size / (rois[:, 3] - rois[:, 1])\n\n offset_x = offset_x[:, None]\n offset_y = offset_y[:, None]\n scale_x = scale_x[:, None]\n scale_y = scale_y[:, None]\n\n x = keypoints[..., 0]\n y = keypoints[..., 1]\n\n x_boundary_inds = x == rois[:, 2][:, None]\n y_boundary_inds = y == rois[:, 3][:, None]\n\n x = (x - offset_x) * scale_x\n x = x.floor().long()\n y = (y - offset_y) * scale_y\n y = y.floor().long()\n\n x[x_boundary_inds] = heatmap_size - 1\n y[y_boundary_inds] = heatmap_size - 1\n\n valid_loc = (x >= 0) & (y >= 0) & (x < heatmap_size) & (y < heatmap_size)\n vis = keypoints[..., 2] > 0\n valid = (valid_loc & vis).long()\n\n lin_ind = y * heatmap_size + x\n heatmaps = lin_ind * valid\n\n return heatmaps, valid\n\n\n@torch.no_grad()\ndef heatmaps_to_keypoints(maps: torch.Tensor, rois: torch.Tensor) -> torch.Tensor:\n offset_x = rois[:, 0]\n offset_y = rois[:, 1]\n\n widths = (rois[:, 2] - rois[:, 0]).clamp(min=1)\n heights = (rois[:, 3] - rois[:, 1]).clamp(min=1)\n widths_ceil = widths.ceil()\n heights_ceil = heights.ceil()\n\n num_rois, num_keypoints = maps.shape[:2]\n xy_preds = maps.new_zeros(rois.shape[0], num_keypoints, 4)\n\n width_corrections = widths / widths_ceil\n height_corrections = heights / heights_ceil\n\n keypoints_idx = torch.arange(num_keypoints, device=maps.device)\n\n for i in range(num_rois):\n outsize = (int(heights_ceil[i]), int(widths_ceil[i]))\n roi_map = interpolate(\n maps[[i]],\n size=outsize,\n mode=\"bicubic\",\n align_corners=False\n ).squeeze(0)\n\n max_score, _ = roi_map.view(num_keypoints, -1).max(1)\n max_score = max_score.view(num_keypoints, 1, 1)\n tmp_full_resolution = (roi_map - max_score).exp_()\n tmp_pool_resolution = (maps[i] - max_score).exp_()\n roi_map_scores = tmp_full_resolution / tmp_pool_resolution.sum((1, 2), keepdim=True)\n\n w = roi_map.shape[2]\n pos = roi_map.view(num_keypoints, -1).argmax(1)\n\n x_int = pos % w\n y_int = (pos - x_int) // w\n\n assert (\n roi_map_scores[keypoints_idx, y_int, x_int]\n == roi_map_scores.view(num_keypoints, -1).max(1)[0]\n ).all()\n\n x = (x_int.float() + 0.5) * width_corrections[i]\n y = (y_int.float() + 0.5) * height_corrections[i]\n\n xy_preds[i, :, 0] = x + offset_x[i]\n xy_preds[i, :, 1] = y + offset_y[i]\n xy_preds[i, :, 2] = roi_map[keypoints_idx, y_int, x_int]\n xy_preds[i, :, 3] = roi_map_scores[keypoints_idx, y_int, x_int]\n\n return xy_preds\n","sub_path":"tkdet/structures/keypoints.py","file_name":"keypoints.py","file_ext":"py","file_size_in_byte":4363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"47997894","text":"import csv\nimport itertools\n\nfrom collections import namedtuple\n\n# Interface type for csvhelper. \n# Represents a column in a csv file.\n# Header = First line of column.\n# Content = List of subsequent lines in column.\nCSVColumn = namedtuple('CSVColumn', ['header', 'content'])\n\n\n# Sample code.\n'''\ndata1 = [1, 2, 3]\ndata2 = [\"hi\", \"hello\", \"bob\", \"frank\"]\ndata3 = [0]\n\ndata1 = CSVColumn(header = \"1\", content = data1)\ndata2 = CSVColumn(header = \"2\", content = data2)\ndata3 = CSVColumn(header = \"3\", content = data3)\ndata = [data1, data2, data3]\ncsvhelper.to_csv(\"out\", data)\n'''\n\ndef to_csv(filename, columns):\n '''\n Writes a list of CSVColumns to a file.\n \n Arguments:\n filename -- Desired filename, minus extensions.\n columns -- List of CSVColumns.\n '''\n headers = [c.header for c in columns]\n content = [c.content for c in columns]\n writer = csv.DictWriter(open(\"%s.csv\" % filename, 'w'), fieldnames = headers) \n \n writer.writeheader()\n \n for data_row in itertools.izip_longest(*content, fillvalue=\"\"):\n # Map header to data row element and then write to file.\n row_map = zip(headers, list(data_row))\n row_map = dict((x, y) for x, y in row_map)\n writer.writerow(row_map)\n \n","sub_path":"csvhelper.py","file_name":"csvhelper.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"466852779","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 29 13:05:33 2019\n\n@author: David\n\"\"\"\n\nimport sys, os\npath_tools = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) \nsys.path.insert(1, path_tools)\nfrom tools import *\n\n\n\n\n\n\ndef Representation_cv_angle_runsout_shuff(testing_activity, testing_behaviour, training_item, tr_st, tr_end, iterations, ref_angle=180):\n ####\n ####\n #### IEM: Inverted encoding model\n #### runsout: train in all the runs except one\n #### all: do it for all the Trs\n #### \n #### no cv: I use this for independent conditions (not training and testing in the same trials) \n ####\n #### I use this function for the conditions 1_7 and 2_7, because the adjacent TRs may be \"contaminated\"\n #### Instead of \"leave one out\" or kfold, I am spliting by run!\n #### \n #### Difference when runing the reconstruction between shared and not shared TRS with training\n #### Not shared: trained in the mean of the interval tr_st - tr_end\n #### Shared: trianed in each TR of the interval\n ####\n #### Training item (decide before where you train the model (it is a column in the beh file))\n ##### training_item = 'T_alone'\n ##### training_item = 'dist_alone' \n ####\n #### Get the Trs (no shared info, coming from different trials)\n list_wm_scans= range(nscans_wm) \n trs_shared = range(tr_st, tr_end)\n nope=[list_wm_scans.remove(tr_s) for tr_s in trs_shared]\n list_wm_scans2 = list_wm_scans\n ####\n ####\n ####\n #### Run the ones WITHOUT shared information the same way\n #testing_behaviour = testing_behaviour.reset_index()\n #training_behaviour = training_behaviour.reset_index()\n training_angles = np.array(testing_behaviour[training_item]) \n decode_item = 'T' ##irrelevant, it is going to be transformed to 0, 90.....\n testing_angles = np.array(testing_behaviour[decode_item]) \n #####\n Reconstructions_shuffled=[]\n for It in range(iterations):\n ###########\n ###########\n ########### not shared (mean activity in training)\n ###########\n ###########\n Recons_trs=[]\n for not_shared in list_wm_scans2:\n training_data = np.mean(testing_activity[:, tr_st:tr_end, :], axis=1) ## son los mismos siempre, pero puede haber time dependence!\n testing_data= testing_activity[:, not_shared, :] \n reconstrction_=[]\n ###########################################################################\n ########################################################################### Get the mutliple indexes to split in train and test\n ###########################################################################\n training_indexes = []\n testing_indexes = []\n for sess_run in testing_behaviour.session_run.unique():\n wanted = testing_behaviour.loc[testing_behaviour['session_run']==sess_run].index.values \n testing_indexes.append( wanted )\n #\n all_indexes = testing_behaviour.index.values\n other_indexes = all_indexes[~np.array([all_indexes[i] in wanted for i in range(len(all_indexes))])] #take the ones that are not in wanted\n training_indexes.append( other_indexes ) \n ###\n ### apply them to train and test\n ###\n for train_index, test_index in zip(training_indexes, testing_indexes):\n X_train, X_test = training_data[train_index], testing_data[test_index]\n y_train, y_test = training_angles[train_index], testing_angles[test_index]\n ## train\n WM2, Inter2 = Weights_matrix_LM(X_train, y_train)\n WM_t2 = WM2.transpose()\n ## Shuffle\n y_test = np.array([random.choice([0, 90, 180, 270]) for i in range(len(y_test))]) \n ## test\n rep_x = decoding_angle_sh_pvector(testing_data=X_test, testing_angles=y_test, Weights=WM2, Weights_t=WM_t2, ref_angle=ref_angle, intercept=Inter2)\n reconstrction_.append(rep_x)\n ###\n reconstrction_ = pd.concat(reconstrction_, axis = 1) ##una al lado de la otra, de lo mismo, ahora un mean manteniendo indice\n reconstrction_mean = reconstrction_.mean(axis = 1) #solo queda una columna con el mean de cada channel \n Recons_trs.append(reconstrction_mean)\n #\n ###########\n ###########\n ########### shared TRS (not mean activity in training)\n ###########\n ###########\n Recons_trs_shared=[]\n for shared_TR in trs_shared:\n testing_data= testing_activity[:, shared_TR, :] \n reconstrction_=[]\n ###########################################################################\n ########################################################################### Get the mutliple indexes to split in train and test\n ###########################################################################\n training_indexes = []\n testing_indexes = []\n for sess_run in testing_behaviour.session_run.unique():\n wanted = testing_behaviour.loc[testing_behaviour['session_run']==sess_run].index.values \n testing_indexes.append( wanted )\n #\n all_indexes = testing_behaviour.index.values\n other_indexes = all_indexes[~np.array([all_indexes[i] in wanted for i in range(len(all_indexes))])] #take the ones that are not in wanted\n training_indexes.append( other_indexes ) \n ###\n ### apply them to train and test\n ###\n for train_index, test_index in zip(training_indexes, testing_indexes):\n X_train, X_test = testing_data[train_index], testing_data[test_index]\n y_train, y_test = training_angles[train_index], testing_angles[test_index]\n ## train\n WM2, Inter2 = Weights_matrix_LM(X_train, y_train)\n WM_t2 = WM2.transpose()\n ## Shuffle\n y_test = np.array([random.choice([0, 90, 180, 270]) for i in range(len(y_test))]) \n ## test\n rep_x = decoding_angle_sh_pvector(testing_data=X_test, testing_angles=y_test, Weights=WM2, Weights_t=WM_t2, ref_angle=ref_angle, intercept=Inter2)\n reconstrction_.append(rep_x)\n ###\n reconstrction_ = pd.concat(reconstrction_, axis = 1) ##una al lado de la otra, de lo mismo, ahora un mean manteniendo indice\n reconstrction_mean = reconstrction_.mean(axis = 1) #solo queda una columna con el mean de cada channel \n Recons_trs_shared.append(reconstrction_mean)\n ####\n ####\n ####\n Reconstruction_not_shared = pd.concat(Recons_trs, axis=1)\n Reconstruction_not_shared.columns = [str(i * TR) for i in list_wm_scans2 ] \n #\n Reconstruction_shared = pd.concat(Recons_trs_shared, axis=1)\n Reconstruction_shared.columns = [str(i * TR) for i in trs_shared ] \n ##\n ##\n Reconstruction = pd.concat([Reconstruction_shared, Reconstruction_not_shared], axis=1)\n #\n Reconstructions_shuffled.append(Reconstruction) \n #\n #\n #####\n df_shuffle = pd.concat(Reconstructions_shuffled).mean(level=0) ###dimensions (720, TRs) (mean shuffle!) (average of shuffled reconstructions)\n ##\n return df_shuffle\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"scripts/wm_representation/functions/IEM/tools/Representation_cv_angle_runsout_shuff.py","file_name":"Representation_cv_angle_runsout_shuff.py","file_ext":"py","file_size_in_byte":7558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"400666771","text":"# import the os module\r\nimport os, os.path\r\nfrom os import path\r\nfrom pathlib import Path\r\n\r\n# import the shutil module (move directory)\r\nimport shutil\r\n\r\n# import the numpy module (for array)\r\nimport numpy as np\r\n\r\n# define the name of the directory to be created\r\ncgss_win_path = os.getcwd()\r\npath_orig = np.array([\"bgm/\", \"sound/\", \"solo/\", \"se/\"])\r\npath_moved = np.array([\"bgm_acb\", \"sound_acb\", \"solo_acb\", \"se_acb\"])\r\nf=Path(\"Static_version\")\r\nf=open(f, 'r')\r\ncgss_manifest_ver=f.read()\r\nf.close()\r\npath_backup = cgss_win_path+\"//\"+cgss_manifest_ver+\"//\"\r\n\r\n# define move all files to specific directory command\r\ni = 0\r\nwhile i < 4:\r\n files = os.listdir(path_backup+path_orig[i])\r\n os.mkdir(path_backup+path_moved[i])\r\n try:\r\n shutil.copytree(path_backup+path_orig[i], path_backup+path_moved[i], dirs_exist_ok=True)\r\n except OSError:\r\n print(\"\\tCopy files from %s to static directory failed\" % path_moved[i])\r\n else:\r\n print(\"\\tMoving files from %s to static directory success\" % path_moved[i])\r\n i += 1\r\n \r\nprint(\"\\tScript done, finally :p\")\r\n","sub_path":"bak.py","file_name":"bak.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"458090459","text":"def get_next(pokemon, dictionary):\r\n\ttry:\r\n\t\tnext_letter = pokemon[len(pokemon) - 1]\r\n\t\treturn dictionary[next_letter]\r\n\texcept:\r\n\t\treturn []\r\n\r\npokedex = \"\"\"audino bagon baltoy banette bidoof braviary bronzor carracosta\r\n charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute\r\n gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff\r\n kangaskhan kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass\r\n petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 porygonz registeel relicanth remoraid rufflet\r\n sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko\r\n tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask\r\n\"\"\"\r\n\r\nlist_of_pokemons = pokedex.split(\" \")\r\n\r\nfor index in range(len(list_of_pokemons)):\r\n\tlist_of_pokemons[index] = list_of_pokemons[index].replace(\"\\n\", \"\")\r\n\t\r\npokemons_dictionary = {}\r\nfor pokemon in list_of_pokemons:\r\n\ttry:\r\n\t\tpokemons_dictionary[pokemon[0]].append(pokemon)\r\n\texcept:\r\n\t\tpokemons_dictionary[pokemon[0]] = []\r\n\t\tpokemons_dictionary[pokemon[0]].append(pokemon)\r\n\r\n\t\t\r\nrecord = 0\r\nchain = []\t\r\ncurrent_length = 0\r\ncurrent_chain = []\r\n\r\ndef play_game(name, dictionary):\r\n\tglobal current_chain\r\n\tglobal current_length\r\n\tglobal record \r\n\tglobal chain\r\n\tcurrent_chain.append(name)\r\n\tcurrent_length += 1\r\n\tnext_list = get_next(name, dictionary)\r\n\ttry:\r\n\t\tdictionary[name[0]].remove(name)\r\n\texcept:\r\n\t\tpass\r\n\tif len(next_list) == 0:\r\n\t\tif current_length >= record:\r\n\t\t\trecord = current_length\r\n\t\t\tchain = current_chain\r\n\t\tprint(\"{}: {}\".format(current_length, current_chain))\r\n\t\tcurrent_chain = []\r\n\t\tcurrent_length = 0\r\n\telse:\r\n\t\tfor i in next_list:\r\n\t\t\tplay_game(i, pokemons_dictionary)\r\n\r\nfor i in list_of_pokemons:\r\n\tprint(i)\r\n\tplay_game(i, pokemons_dictionary)\r\n","sub_path":"8/answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"332773555","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport pandas as pd\nimport os\nimport tensorflow as tf\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.core import *\nfrom keras.layers import *\nfrom keras.models import Model\nfrom keras.layers.wrappers import Bidirectional\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers.pooling import AveragePooling2D\nfrom keras.layers.core import Reshape\nfrom keras.callbacks import TensorBoard\nfrom sklearn.model_selection import train_test_split\nimport keras.backend as K\nimport time\n\nprint(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\ndef get_session(gpu_fraction=0.4):\n \"\"\"\n This function is to allocate GPU memory a specific fraction\n Assume that you have 6GB of GPU memory and want to allocate ~2GB\n \"\"\"\n\n num_threads = os.environ.get('OMP_NUM_THREADS')\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_fraction)\n\n if num_threads:\n return tf.Session(config=tf.ConfigProto(\n gpu_options=gpu_options, intra_op_parallelism_threads=num_threads))\n else:\n return tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\n\n\n# get_session(gpu_fraction=0.4)\n\n\n# vocabulary_size = 27545\n# pos_size = 54\n\n\"\"\"\ndef build_char_input(input_dim, output_dim, shape):\n inputs = Input(shape=[shape[0], shape[1]])\n x = Conv1D(filters=shape[1] * 2, kernel_size=2, padding=\"same\", input_shape=(shape[0], shape[1]), activation=\"relu\")(inputs)\n x = AveragePooling1D(pool_size=2)(x)\n x = Reshape((shape[0], shape[1]))(x)\n x = Reshape((shape[0] * shape[1],))(x)\n x = Embedding(output_dim=output_dim, input_dim=input_dim + 1, mask_zero=False,\n input_length=shape[0] * shape[1])(x)\n x = Reshape((shape[0], shape[1], output_dim))(x)\n return inputs, x\n\"\"\"\n\n\nclass AttLayer(Layer):\n def __init__(self, attention_dim):\n self.init = initializers.get('normal')\n self.supports_masking = True\n self.attention_dim = attention_dim\n super(AttLayer, self).__init__()\n\n def build(self, input_shape):\n assert len(input_shape) == 3\n self.W = K.variable(self.init((input_shape[-1], self.attention_dim)))\n self.b = K.variable(self.init((self.attention_dim,)))\n self.u = K.variable(self.init((self.attention_dim, 1)))\n self.trainable_weights = [self.W, self.b, self.u]\n super(AttLayer, self).build(input_shape)\n\n def compute_mask(self, inputs, mask=None):\n return mask\n\n def call(self, x, mask=None):\n # size of x :[batch_size, sel_len, attention_dim]\n # size of u :[batch_size, attention_dim]\n # uit = tanh(xW+b)\n uit = K.tanh(K.bias_add(K.dot(x, self.W), self.b))\n ait = K.dot(uit, self.u)\n ait = K.squeeze(ait, -1)\n\n ait = K.exp(ait)\n\n if mask is not None:\n # Cast the mask to floatX to avoid float64 upcasting in theano\n ait *= K.cast(mask, K.floatx())\n ait /= K.cast(K.sum(ait, axis=1, keepdims=True) + K.epsilon(), K.floatx())\n ait = K.expand_dims(ait)\n weighted_input = x * ait\n output = K.sum(weighted_input, axis=1)\n\n return output\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], input_shape[-1])\n\n\ndef build_input(input_dim, output_dim, shape):\n inputs = Input(shape=[shape[0], shape[1]])\n x = Reshape((shape[0] * shape[1],))(inputs)\n x = Embedding(output_dim=output_dim, input_dim=input_dim + 1, mask_zero=False,\n input_length=shape[0] * shape[1])(x)\n # x = BatchNormalization()(x)\n x = Reshape((shape[0], shape[1], output_dim))(x)\n\n return inputs, x\n\n\ndef concat_output(x_train, x_train_pos, vocab_dimension, pos_dimension, shape):\n x = Concatenate()([x_train, x_train_pos])\n # x = BatchNormalization()(x)\n x = AveragePooling2D(data_format='channels_last', pool_size=(1, shape[1]))(x)\n # x = BatchNormalization()(x)\n x = Reshape((shape[0], vocab_dimension + pos_dimension))(x)\n x = Dropout(0.3)(x)\n # x = BatchNormalization()(x)\n x = Bidirectional(GRU(300, return_sequences=True))(x)\n x = AttLayer(300)(x)\n return x\n\n\ndef total_pad_seq(train_dialogues, length=60):\n tra = []\n for a in train_dialogues:\n a_1 = pad_sequences(a, maxlen=length, value=vocabulary_size - 1)\n tra.append(a_1)\n return np.array(tra)\n\n# train_dialogues, train_dialogues_pos, testA_dialogues, testA_dialogues_pos, train_dialogues_original, train_dialogues_pos_original, \\\n# unlabeled_dialogues, unlabele`d_dialogues_pos = pd.read_pickle(\"xxxxxxxx.pkl\")\ntrain_dialogues, train_dialogues_pos, train_dialogues_original, train_dialogues_pos_original, testA_dialogues, testA_dialogues_pos,\\\ntestB_dialogues, testB_dialogues_pos, testC_dialogues, testC_dialogues_pos, testD_dialogues, testD_dialogues_pos,\\\nunlabeled_dialogues, unlabeled_dialogues_pos = pd.read_pickle(\"14x.pkl\")\ny_class, y1_class, train_y, train_y1, ori_train_y, ori_train_y1, test_y, test_y1, unlabeled_y, unlabeled_y1 = pd.read_pickle(\"yyyyyyyy_encoder.pkl\")\nvocab_dim = 300\npos_dim = int(vocab_dim/5)\nvocabulary_size = 67893\n\n\nX_train = total_pad_seq(train_dialogues)\nX_pos_train = total_pad_seq(train_dialogues_pos)\n\n\nX_testA = total_pad_seq(testA_dialogues)\nX_pos_testA = total_pad_seq(testA_dialogues_pos)\n\nX_testD = total_pad_seq(testD_dialogues)\nX_pos_testD = total_pad_seq(testD_dialogues_pos)\n\n\nX_train_original = total_pad_seq(train_dialogues_original)\nX_pos_train_original = total_pad_seq(train_dialogues_pos_original)\n\nX_unlabeled = total_pad_seq(unlabeled_dialogues)\nX_pos_unlabeled = total_pad_seq(unlabeled_dialogues_pos)\n\n\n\nX_train_60 = pad_sequences(X_train, maxlen=60, value=vocabulary_size)\nX_train_ori_60 = pad_sequences(X_train_original, maxlen=60, value=vocabulary_size)\nX_testA_60 = pad_sequences(X_testA, maxlen=60, value=vocabulary_size)\nX_testD_60 = pad_sequences(X_testD, maxlen=60, value=vocabulary_size)\nX_unlabeled_60 = pad_sequences(X_unlabeled, maxlen=60, value=vocabulary_size)\n\nX_pos_train_60 = pad_sequences(X_pos_train, maxlen=60, value=vocabulary_size)\nX_pos_train_ori_60 = pad_sequences(X_pos_train_original, maxlen=60, value=vocabulary_size)\nX_pos_testA_60 = pad_sequences(X_pos_testA, maxlen=60, value=vocabulary_size)\nX_pos_testD_60 = pad_sequences(X_pos_testD, maxlen=60, value=vocabulary_size)\nX_pos_unlabeled_60 = pad_sequences(X_pos_unlabeled, maxlen=60, value=vocabulary_size)\n\nX_train_40 = pad_sequences(X_train, maxlen=40, value=vocabulary_size)\nX_train_ori_40 = pad_sequences(X_train_original, maxlen=40, value=vocabulary_size)\nX_testA_40 = pad_sequences(X_testA, maxlen=40, value=vocabulary_size)\nX_testD_40 = pad_sequences(X_testD, maxlen=40, value=vocabulary_size)\nX_unlabeled_40 = pad_sequences(X_unlabeled, maxlen=40, value=vocabulary_size)\n\nX_pos_train_40 = pad_sequences(X_pos_train, maxlen=40, value=vocabulary_size)\nX_pos_train_ori_40 = pad_sequences(X_pos_train_original, maxlen=40, value=vocabulary_size)\nX_pos_testA_40 = pad_sequences(X_pos_testA, maxlen=40, value=vocabulary_size)\nX_pos_testD_40 = pad_sequences(X_pos_testD, maxlen=40, value=vocabulary_size)\nX_pos_unlabeled_40 = pad_sequences(X_pos_unlabeled, maxlen=40, value=vocabulary_size)\n\ninputs_a, x_a = build_input(vocabulary_size, vocab_dim, X_train_60[0].shape)\ninputs_b, x_b = build_input(vocabulary_size, pos_dim, X_pos_train_60[0].shape)\n# inputs_c, x_c = build_input(vocabulary_size, vocab_dim, X_train_ori_60[0].shape)\n# inputs_d, x_d = build_input(vocabulary_size, vocab_dim, X_pos_train_ori_60[0].shape)\n\ninputs_e, x_e = build_input(vocabulary_size, vocab_dim, X_train_40[0].shape)\ninputs_f, x_f = build_input(vocabulary_size, pos_dim, X_pos_train_40[0].shape)\n# inputs_g, x_g = build_input(vocabulary_size, vocab_dim, X_train_ori_40[0].shape)\n# inputs_h, x_h = build_input(vocabulary_size, vocab_dim, X_pos_train_ori_40[0].shape)\n\n\nx_1 = concat_output(x_a, x_b, vocab_dim, pos_dim, X_train_60[0].shape)\nx_2 = concat_output(x_e, x_f, vocab_dim, pos_dim, X_train_40[0].shape)\n# x_1 = BatchNormalization()(x_1)\n# x_2 = BatchNormalization()(x_2)\n\npredictions_a = Dense(5, activation='softmax')(x_1)\nx_1_with_prediction_a = Concatenate()([x_1, predictions_a])\npredictions_b = Dense(38, activation='softmax')(x_1_with_prediction_a)\n\n\npredictions_c = Dense(5, activation='softmax')(x_2)\nx_2_with_prediction_c = Concatenate()([x_1, predictions_a])\npredictions_d = Dense(38, activation='softmax')(x_2_with_prediction_c)\n\nx = Concatenate()([x_1, x_2])\nx = Dropout(0.3)(x)\n# x = BatchNormalization()(x)\n\npredictions_e = Dense(5, activation='softmax')(x)\nx_with_prediction_e = Concatenate()([x, predictions_e])\npredictions_f = Dense(38, activation='softmax')(x_with_prediction_e)\n\nmodel = Model(inputs=[inputs_a, inputs_b, inputs_e, inputs_f],\n outputs=[predictions_a, predictions_b, predictions_c, predictions_d, predictions_e, predictions_f])\n\nprint(\"训练...\")\nfrom keras import optimizers\nsgd = optimizers.SGD(lr=0.02, decay=1e-6, momentum=0.9, nesterov=True)\nbatch_size = 32\ntensorboard = TensorBoard(log_dir=\"./log/10\")\nx_train_60, x_val_60, x_pos_train_60, x_val_pos_60, x_train_ori_60, x_val_ori_60, x_pos_ori_60, x_val_pos_ori_60, \\\nx_train_40, x_val_40, x_pos_train_40, x_val_pos_40, x_train_ori_40, x_val_ori_40, x_pos_ori_40, x_val_pos_ori_40,\\\ny, y_val, y1, y1_val = train_test_split(X_train_60, X_pos_train_60, X_train_ori_60, X_pos_train_ori_60, X_train_40, X_pos_train_40, X_train_ori_40, X_pos_train_ori_40, train_y, train_y1, test_size=0.1, random_state=30)\n\nprint('**×*×*×*×*×*×*×*×*×*×*×*×*×*×*')\nmodel.load_weights('model_new_leo.h5')\nmodel.compile(loss='categorical_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'], loss_weights=[0.2, 1.0, 0.2, 1.0, 0.2, 1.0])\n\nfor i in range(10):\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n history1 = model.fit([X_unlabeled_60, X_pos_unlabeled_60, X_unlabeled_40, X_pos_unlabeled_40],\n [unlabeled_y, unlabeled_y1, unlabeled_y, unlabeled_y1, unlabeled_y, unlabeled_y1],\n batch_size=batch_size, epochs=1, verbose=1)\n history = model.fit([x_train_60, x_pos_train_60, x_train_40, x_pos_train_40],\n [y, y1, y, y1, y, y1],\n validation_data=([x_val_60, x_val_pos_60, x_val_40, x_val_pos_40], [y_val, y1_val, y_val, y1_val, y_val, y1_val]),\n batch_size=batch_size, epochs=2, verbose=1, callbacks=[tensorboard])\n\n for i in history.history.keys():\n if \"acc\" in i:\n print(i, history.history[i])\nmodel.save(\"model_new_leo+10.h5\")\n\nexit()\npredict_label_test = model.predict(x=[X_testD_60, X_pos_testD_60, X_testD_40, X_pos_testD_40])\n\npredict_label_test_y = predict_label_test[0]\npredict_label_test_y1 = predict_label_test[1]\n\nimport pickle\nwith open('predicted_test_9_26_23_00.pkl', 'wb') as f:\n pickle.dump((predict_label_test_y, predict_label_test_y1), f)\n\n\n[0.509500003695488, 0.5260000022649765, 0.5215000004768372, 0.5369999985098839, 0.534000002026558, 0.5210000008940697, 0.5340000013113022, 0.5390000005364418, 0.5305000009536743, 0.5290000017881393, 0.5410000007748604, 0.5250000022649765, 0.5385000007748604, 0.5380000039339066, 0.5370000001192093, 0.5534999990463256, 0.53549999833107, 0.5440000005960465, 0.5385000015497208, 0.5415000011920929]\n[0.49600000321865084, 0.5245000038146973, 0.5195000010728836, 0.5075000039935113, 0.5280000011920929, 0.5355000025033951, 0.5265000001192093, 0.543500003695488, 0.5220000010728836, 0.5265000026226043, 0.5145000023841858, 0.5290000005960465, 0.5279999994039536, 0.5335000010728836, 0.5270000015497207, 0.5375000033378601, 0.5295000001192093, 0.5335000016689301, 0.5270000040531159, 0.5315000011920928]\n","sub_path":"intend/fasttext+bilstm+att+load.py","file_name":"fasttext+bilstm+att+load.py","file_ext":"py","file_size_in_byte":11741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"105264260","text":"from rest_framework import serializers\nfrom common.models.arrangement import AccountRelatedParty\n\n\nclass AccountRelatedPartiesSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = AccountRelatedParty\n fields = \"__all__\"\n depth = 2\n\n def to_representation(self, instance):\n representation = super().to_representation(instance)\n\n to_represent = {\n \"id\": representation[\"AccountRelatedPartyId\"],\n \"relatedPartyName\": representation['RelatedPartyName'],\n \"relationTypeStringed\": representation[\"RelationType\"][\"Description\"] if \"RelationType\" in representation and representation[\"RelationType\"] is not None else None,\n \"isPrimaryAccountOwnerStringed\": representation[\"IsPrimaryAccountOwner\"][\"Description\"] if \"IsPrimaryAccountOwner\" in representation and representation[\"IsPrimaryAccountOwner\"] is not None else None,\n \"startDate\": representation[\"StartDate\"],\n \"endDate\": representation[\"EndDate\"],\n \"print\": representation[\"PrintFlag\"]\n }\n\n return to_represent\n","sub_path":"common/serializers/arrangement/account/account_related_parties.py","file_name":"account_related_parties.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"246274881","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-# enable debugging\nimport sys\ntry:\n import urllib.request as urllib2\nexcept ImportError:\n import urllib2\n\nimport re\nimport pandas as pd\nfrom sklearn.preprocessing import Imputer\nimport numpy as np\nfrom pandas import Series\nsys.path.append(\"/Users/user/PycharmProjects/DeepLearningPy\")\n#url1 = 'https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data'\nhttp_regex = re.compile(\"http[s]?\")\nlocal_regex = re.compile(\"static\\/uploaded?\")\n\nparam0 = {\n 'shape': None,\n 'head': None,\n 'url': '/Users/user/PycharmProjects/DeepLearningPy/static/uploaded/iris.data.csv',\n 'status': True,\n 'message': 'Data Preprocessing..\\n',\n 'header_is': 0,\n 'null_treatment': 0\n}\n\nclass DataPreProcess(object):\n\n def __init__(self):\n\n self.param = {\n 'shape': None,\n 'head': None,\n 'column':None,\n 'url': '',\n 'status': True,\n 'message': '',\n 'header_is': False,\n 'null_treatment': False,\n 'null_num':0\n }\n\n def validate_url(self, param=param0):\n print(param)\n self.df = pd.DataFrame()\n\n self.param['url'] = param['url']\n self.param['status'] = param['status']\n self.param['message'] = param['message']\n self.param['header_is'] = param['header_is']\n self.param['null_treatment'] = param['null_treatment']\n\n # 正しくhttpで始まっているかどうか\n if http_regex.search(self.param['url']) is not None:\n try:\n urllib2.urlopen(self.param['url'], timeout=10)\n except:\n pass\n # except urllib2.URLError, e:\n #\n # # 接続テスト失敗\n # print e\n # self.param['status'] = False\n # self.param['message'] += str(e)\n\n # URLも存在し、ローカルにもありそうかどうか\n if self.param['status'] or local_regex.search(self.param['url']) is not None:\n\n header_is = 0 if self.param['header_is'] else None\n print(\"df = pd.read_csv(self.param['url'], header=header_is)\")\n self.df = pd.read_csv(self.param['url'], header=header_is)\n\n # DataFrameにNullがあるかどうかを判別\n s = 0\n for i, d in enumerate(self.df.isnull().sum()):\n s += d\n\n if s > 0:\n print(\"null_s is %d\" % s)\n self.param['null_num']=s\n # 要素に一つでもNullがある場合\n if self.param['null_treatment']:\n #NULLはDeleteして処理する場合\n self.df = self.df.dropna()\n self.param['message'] += \"NULL Deleted.\\n\"\n else:\n #NULLは平均をImpute して処理する場合\n print(\"impute with mean values\")\n try:\n imr = Imputer(missing_values='NaN', strategy='mean', axis=0)\n imr.fit(self.df)\n except:\n pass\n # except UnboundLocalError, e:\n # pass\n\n columns = self.df.columns\n self.df = pd.DataFrame(imr.transform(self.df.values), columns=columns)\n self.param['message'] += \"NULL Imputed.\\n\"\n else:\n print(\"null is 0\")\n\n self.param['shape'] = self.df.shape\n self.param['column'] = Series(self.df.columns).to_json()\n self.df = self.df.iloc[np.unique(np.random.randint(0, self.df.shape[0]-1, 8))]\n self.param['head'] = self.df.T.to_json()\n self.param['head_t'] = self.df.to_json()\n\n else:\n self.param['status'] = False\n self.param['message'] += \"invalid data / data not found\\n\"\n\n return self.param\n\n def target_modify(self, param=param0):\n param = self.validate_url(param);\n print(param)\n\n#\n#\n# from sklearn.cross_validation import train_test_split\n# X,y = df_wine.iloc[:, 1:].values, df_wine.iloc[:,0].values\n# X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.3, random_state=0)\n#\n#\n# #normalization\n# from sklearn.preprocessing import MinMaxScaler\n# mms = MinMaxScaler()\n# X_train_norm=mms.fit_transform(X_train)\n# X_test_norm=mms.fit_transform(X_test)\n#\n# #standardization : Z-value\n# from sklearn.preprocessing import StandardScaler\n# stdsc = StandardScaler()\n# X_train_std = stdsc.fit_transform(X_train)\n# X_test_std = stdsc.fit_transform(X_test)\n#\n# from lib.sbs import *\n# from sklearn.neighbors import KNeighborsClassifier\n# import matplotlib.pyplot as plt\n#\n# knn = KNeighborsClassifier(n_neighbors=2)\n# sbs = SBS(knn,k_features=1)\n# sbs.fit(X_train_std, y_train)\n#\n# k_feat = [len(k) for k in sbs.subsets_]\n# plt.plot(k_feat, sbs.scores_, marker='o')\n# plt.ylim([0.7, 1.1])\n# plt.ylabel('Accuracy')\n# plt.xlabel('Number of features')\n# plt.grid()\n# plt.show()\n#\n# k5 = list(sbs.subsets_[8])\n# print (\"k5:\")\n# print k5\n# print (df_wine.columns[1:][k5])\n# knn.fit(X_train_std[:, k5], y_train)\n# print('Training accurary:', knn.score(X_train_std[:,k5], y_train))\n# print('Test accuracy:', knn.score(X_test_std[:,k5], y_test))df\n\n","sub_path":"model/DataPreprocessing.py","file_name":"DataPreprocessing.py","file_ext":"py","file_size_in_byte":5346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"520056796","text":"import MapReduce\nimport sys\n\n\"\"\"\nAssume you have two matrices A and B in a sparse matrix format, where each record is of the form i, j, value. Design a MapReduce algorithm to compute the matrix multiplication A x B\n\"\"\"\n\nmr = MapReduce.MapReduce()\n\n# =============================\n# Do not modify above this line\n\nfrom collections import defaultdict\nN = 100\n\ndef mapper(record):\n matrix = record[0]\n if matrix == 'a':\n for k in range(0, N):\n mr.emit_intermediate((record[1], k), (matrix, record[2], record[3]))\n else:\n for k in range(0, N):\n mr.emit_intermediate((k, record[2]), (matrix, record[1], record[3]))\n\ndef reducer(key, list_of_values):\n hash_ab = defaultdict(list)\n for item in list_of_values:\n hash_ab[item[1]].append(item[2])\n \n result = sum([v[0] * v[1] for k, v in hash_ab.iteritems() if len(v) >= 2])\n if result != 0:\n mr.emit((key[0], key[1], result))\n\n# Do not modify below this line\n# =============================\nif __name__ == '__main__':\n inputdata = open(sys.argv[1])\n mr.execute(inputdata, mapper, reducer)\n","sub_path":"assignment3/multiply.py","file_name":"multiply.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"607295124","text":"import numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\nimport pandas as pd\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.metrics import accuracy_score\nimport time\nimport constant\n\ndef NotScaleNN():\n file = open(constant.Iris_Not_Scale_NN,\"w\")\n start_time = time.time()\n classifier = MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(5, 5), random_state=3)\n classifier.fit(X_train, y_train)\n y_pred = classifier.predict(X_test)\n end_time = time.time()\n file.write(\"------Confusion Matrix------\\n\"+np.array2string(confusion_matrix(y_test, y_pred), separator=', '))\n file.write(\"\\n\\n------Report------\\n\"+classification_report(y_test, y_pred))\n file.write('\\n\\n-------------\\n* Accuracy is: '+ accuracy_score(y_pred, y_test).__str__())\n file.write(\"\\n\\n* Running time: %.2f (s)\" % (end_time - start_time))\n\ndef ScaleNN():\n file = open(constant.Iris_Scale_NN,\"w\")\n scaler = MinMaxScaler((-1,1))\n X_train_scaled = scaler.fit_transform(X_train)\n X_test_scaled = scaler.transform(X_test)\n start_time = time.time()\n classifier = MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(5, 2), random_state=1)\n classifier.fit(X_train_scaled, y_train)\n y_pred = classifier.predict(X_test_scaled)\n end_time = time.time()\n file.write(\"------Confusion Matrix------\\n\"+np.array2string(confusion_matrix(y_test, y_pred), separator=', '))\n file.write(\"\\n\\n------Report------\\n\"+classification_report(y_test, y_pred))\n file.write('\\n\\n-------------\\n* Accuracy is: '+ accuracy_score(y_pred, y_test).__str__())\n file.write(\"\\n\\n* Running time: %.2f (s)\" % (end_time - start_time))\nif __name__ == \"__main__\":\n dataTrain = pd.read_csv('../dataset/Iris/irisTrain.csv')\n dataTest = pd.read_csv('../dataset/Iris/irisTest.csv')\n X_train = dataTrain.iloc[:, :-1].values # tach data\n y_train = dataTrain.iloc[:, -1].values # tach nhan\n X_test = dataTest.iloc[:, :-1].values\n y_test = dataTest.iloc[:, -1].values\n NotScaleNN()\n ScaleNN()\n","sub_path":"iris/NN.py","file_name":"NN.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"411359843","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.metrics import r2_score\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import Normalizer\nimport matplotlib.pyplot as plt\nimport CarlosLib\nimport operator\n\ndf=pd.read_csv(\"datasets\\\\properati_caballito.csv\",encoding=\"utf8\")\n#print(\"cant. registros antes de limpiar basura:\", len(df))\n\n#regs_train=round((len(df)/100)*80,0)\n#df_train=df.loc[:regs_train,:]\n#df_test=df.loc[regs_train:len(df),:]\ndf_train=pd.read_csv(\"datasets\\\\properati_caballito_train.csv\",encoding=\"utf8\")\ndf_test=pd.read_csv(\"datasets\\\\properati_caballito_test.csv\",encoding=\"utf8\")\n\n#FILTRAR OUTLIERS\nqryFiltro=\"(price_aprox_usd >= 50000 and price_aprox_usd <= 250000)\"\nqryFiltro+=\" and (surface_total_in_m2 >= 25 and surface_total_in_m2 <= 120)\"\n#qryFiltro+=\" and (surface_total_in_m2 >= surface_covered_in_m2)\"\n#qryFiltro+=\" and (precio_m2_usd <= 3750 and precio_m2_usd >= 2000)\"\nqryFiltro+=\" and (price_usd_per_m2 <= 7000 and price_usd_per_m2 >= 2000)\"\n\n\ndf_train=df_train.query(qryFiltro)\ndf_test=df_test.query(qryFiltro)\n\n#print(df_train.describe())\n#print(df_test.describe())\n\n#dummy_cols = [col for col in df_train if col.startswith('dummy_')]\ndummy_cols=[\"dummy_property_type__apartment\"]\ndummy_cols2=[\"dummy_frente\",\"dummy_profesional\",\"dummy_parrilla\",\"dummy_solarium\"]\ndummy_cols3=[\"dummy_living\",\"dummy_luminoso\",\"dummy_terraza\",\"dummy_laundry\",\"dummy_cochera\",\n \"dummy_split\",\"dummy_piscina\",\"dummy_spa\",\"dummy_acondicionado\",\n \"dummy_subte\",\"dummy_pozo\",\"dummy_balcon\",\"dummy_sum\",\"dummy_vigilancia\"]\n#dummy_cols2=[]\n#dummy_cols3=[]\ndistance_cols = [col for col in df_train if col.startswith('dist')]\n#distance_cols=[]\n\ncols=dummy_cols + dummy_cols2 + dummy_cols3 + distance_cols + ['surface_total_in_m2','expenses','rooms']\n#\nscaler = Normalizer()\nscalercols=cols + [\"price_usd_per_m2\"]\ndf_train[scalercols]=scaler.fit_transform(df_train[scalercols])\ndf_test[scalercols]=scaler.fit_transform(df_test[scalercols])\n\nX_train=df_train[cols]\ny_train=df_train[\"price_usd_per_m2\"]\nX_test=df_test[cols]\ny_test=df_test[\"price_usd_per_m2\"]\n#print(\"X:\",X)\n#print(\"y:\",y)\n\n\nv = CarlosLib.PolyDictVectorizer(sparse=False)\n#print(X_train.T.to_dict())\n\n#hasher = CarlosLib.PolyFeatureHasher()\nX_train.reset_index(drop=True,inplace = True)\n#print(\"X_train:\")\n#print(X_train)\ndict_train=X_train.T.to_dict()\n#print(dict_train.values())\n\nX_train_v=v.fit_transform(dict_train.values())\nprint(\"v_train feature names:\",v.get_feature_names())\n##print(X_train_v)\n##\npoly_features = PolynomialFeatures(degree=1)\n###\n#### transforms the existing features to higher degree features.\nX_train_poly = poly_features.fit_transform(X_train_v)\n###\n#### fit the transformed features to Linear Regression\npoly_model = LinearRegression()\npoly_model.fit(X_train_poly, y_train)\n###\n### predicting on training data-set\ny_train_predicted = poly_model.predict(X_train_poly)\n##\n#### predicting on test data-set\nX_test.reset_index(drop=True,inplace = True)\ndict_test=X_test.T.to_dict()\nX_test_v=v.fit_transform(dict_test.values())\n#print(\"v_test feature names:\",v.get_feature_names())\nX_test_poly=poly_features.fit_transform(X_test_v)\ny_test_predict = poly_model.predict(X_test_poly)\n###\n### evaluating the model on training dataset\nrmse_train = np.sqrt(mean_squared_error(y_train, y_train_predicted))\nr2_train = r2_score(y_train, y_train_predicted)\n###\n###\n##print(\"y_test.max:\", max(y_test))\n##print(\"y_test_predict.max:\", max(y_test_predict))\n###\n##print(\"y_test.avg:\", np.average(y_test))\n##print(\"y_test_predict.avg:\", np.average(y_test_predict))\n###\n###print(\"y_test.std:\", np.std(y_test))\n###print(\"y_test_predict.std:\", np.std(y_test_predict))\n###\n###\n### evaluating the model on test dataset\nrmse_test = np.sqrt(mean_squared_error(y_test, y_test_predict))\nr2_test = r2_score(y_test, y_test_predict)\n#\nprint(\"The model performance for the training set\")\nprint(\"-------------------------------------------\")\nprint(\"RMSE of training set is {}\".format(rmse_train))\nprint(\"R2 score of training set is {}\".format(r2_train))\n\nprint(\"\\n\")\n\nprint(\"The model performance for the test set\")\nprint(\"-------------------------------------------\")\nprint(\"RMSE of test set is {}\".format(rmse_test))\nprint(\"R2 score of test set is {}\".format(r2_test))\n\nx=X_train[\"surface_total_in_m2\"]\ny=y_train\nplt.title(\"Trained R2:\" + str(r2_train))\nplt.scatter(x, y, s=20)\n# sort the values of x before line plot\nsort_axis = operator.itemgetter(0)\nsorted_zip = sorted(zip(x,y_test_predict), key=sort_axis)\nx, y_poly_pred = zip(*sorted_zip)\nplt.plot(x, y_poly_pred, color='m')\nplt.show()\n\nx=X_test[\"surface_total_in_m2\"]\ny=y_test\nplt.title(\"Predicted R2:\" + str(r2_test))\nplt.scatter(x, y, s=20)\n# sort the values of x before line plot\nsort_axis = operator.itemgetter(0)\nsorted_zip = sorted(zip(x,y_test_predict), key=sort_axis)\nx, y_poly_pred = zip(*sorted_zip)\nplt.plot(x, y_poly_pred, color='m')\nplt.show()\n","sub_path":"TP1y2/TP_ModeloDS_Poly2.py","file_name":"TP_ModeloDS_Poly2.py","file_ext":"py","file_size_in_byte":5034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"273661925","text":"\"\"\"\nAuthor: Stergios Mekras\nEmail: stergios.mekras@gmail.com\n\"\"\"\n\nfrom interface.components import *\nfrom logic import lore\n\n\nclass GeneralPanel(Frame):\n def __init__(self, master, **kw):\n super().__init__(master, **kw)\n self.frame = Labelframe(master, text=\"General Information\", padding=10)\n\n self.player = LabeledEntry(self.frame)\n self.player.label.configure(text=\"Player\")\n self.player.frame.pack()\n self.name = LabeledEntry(self.frame)\n self.name.label.configure(text=\"Name\")\n self.name.frame.pack()\n self.concept = LabeledEntry(self.frame)\n self.concept.label.configure(text=\"Concept\")\n self.concept.frame.pack()\n self.genus = LabeledDropMenu(self.frame)\n self.genus.label.configure(text=\"Genus\")\n self.genus.combo.configure(values=lore.genii)\n self.genus.combo.bind(\"<>\", self.update_species)\n self.genus.frame.pack()\n self.species = LabeledDropMenu(self.frame)\n self.species.label.configure(text=\"Species\")\n self.species.combo.bind(\"<>\")\n self.species.frame.pack()\n self.aspect = LabeledDropMenu(self.frame)\n self.aspect.label.configure(text=\"Aspect\")\n self.aspect.combo.configure(values=lore.aspects)\n self.aspect.combo.bind(\"<>\")\n self.aspect.frame.pack()\n self.bearing = LabeledDropMenu(self.frame)\n self.bearing.label.configure(text=\"Bearing\")\n self.bearing.combo.configure(values=lore.bearings)\n self.bearing.combo.bind(\"<>\")\n self.bearing.frame.pack()\n self.persona = LabeledDropMenu(self.frame)\n self.persona.label.configure(text=\"Persona\")\n self.persona.combo.configure(values=lore.personae)\n self.persona.combo.bind(\"<>\")\n self.persona.frame.pack()\n\n def update_species(self, event):\n if self.genus.combo.current() == -1:\n self.species.combo.configure(values=lore.species)\n else:\n species = []\n for k, v in lore.races['Species'][self.genus.var.get()].items():\n species.append(k)\n self.species.combo.configure(values=species)\n\n\nclass AttributesPanel(object):\n def __init__(self, master):\n self.frame = Labelframe(master, text=\"Core Attributes\", padding=10)\n\n self.agility = LabeledAttribute(self.frame)\n self.awareness = LabeledAttribute(self.frame)\n self.charisma = LabeledAttribute(self.frame)\n self.intellect = LabeledAttribute(self.frame)\n self.resilience = LabeledAttribute(self.frame)\n self.strength = LabeledAttribute(self.frame)\n self.vitality = LabeledAttribute(self.frame)\n self.wits = LabeledAttribute(self.frame)\n\n attribute_list = [self.agility, self.awareness, self.charisma, self.intellect, self.resilience, self.strength,\n self.vitality, self.wits]\n # TODO: Get attributes from sheet\n label_list = [\"Agility\", \"Awareness\", \"Charisma\", \"Intellect\", \"Resilience\", \"Strength\", \"Vitality\", \"Wits\"]\n\n for _ in range(len(attribute_list)):\n attribute_list[_].label.configure(text=label_list[_])\n attribute_list[_].frame.pack()\n\n\nclass SecondaryPanel(object):\n def __init__(self):\n self.secondary = Labelframe(self, text=\"Secondary Traits\", padding=10)\n\n self.defence = LabeledNumber(self.secondary)\n self.defence.label.configure(text=\"Defence\")\n self.mass = LabeledNumber(self.secondary)\n self.mass.label.configure(text=\"Mass\")\n self.initiative = LabeledNumber(self.secondary)\n self.initiative.label.configure(text=\"Initiative\")\n self.actions = LabeledNumber(self.secondary)\n self.actions.label.configure(text=\"Actions\")\n\n self.health = Label(self.secondary, text=\"Health Points\", justify='center')\n self.body = LabeledConsumable(self.secondary)\n self.body.label.configure(text=\"Body\")\n self.will = LabeledConsumable(self.secondary)\n self.will.label.configure(text=\"Will\")\n self.points = LabeledConsumable(self.secondary)\n self.points.label.configure(text=\"Build Points\")\n self.experience = LabeledConsumable(self.secondary)\n self.experience.label.configure(text=\"Experience\")\n self.movement = Label(self.secondary, text=\"Movement (m/s)\", justify='center')\n self.walking = LabeledNumber(self.secondary)\n self.walking.label.configure(text=\"Walking\")\n self.running = LabeledNumber(self.secondary)\n self.running.label.configure(text=\"Running\")\n self.swimming = LabeledNumber(self.secondary)\n self.swimming.label.configure(text=\"Swimming\")\n self.jumping = LabeledNumber(self.secondary)\n self.jumping.label.configure(text=\"Jumping\")\n\n self.defence.frame.grid(row=0, column=0)\n self.mass.frame.grid(row=1, column=0)\n self.initiative.frame.grid(row=2, column=0)\n self.actions.frame.grid(row=3, column=0)\n self.health.grid(row=5, column=0)\n self.body.frame.grid(row=6, column=0)\n self.will.frame.grid(row=7, column=0)\n self.points.frame.grid(row=0, column=1, padx=(10, 0))\n self.experience.frame.grid(row=1, column=1, padx=(10, 0))\n self.movement.grid(row=3, column=1, padx=(10, 0))\n self.walking.frame.grid(row=4, column=1, padx=(10, 0))\n self.running.frame.grid(row=5, column=1, padx=(10, 0))\n self.jumping.frame.grid(row=6, column=1, padx=(10, 0))\n self.swimming.frame.grid(row=7, column=1, padx=(10, 0))\n","sub_path":"interface/windows.py","file_name":"windows.py","file_ext":"py","file_size_in_byte":5671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"25926046","text":"# https://www.learnopencv.com/homography-examples-using-opencv-python-c/\nimport cv2\nimport numpy as np\n\n\nclass Common:\n x = 0\n y = 0\n pts = []\n\n\ndef do_warp(img_src):\n pts_src = np.array([[141, 131], [480, 159], [493, 630],[64, 601]])\n pts_dst = np.array([[141, 131], [480, 159], [493, 630],[64, 601]])\n # Calculate Homography\n h, status = cv2.findHomography(pts_src, pts_dst)\n # Warp source image to destination based on homography\n im_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1],im_dst.shape[0]))\n \ndef get_xy(event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONDOWN:\n Common.x, Common.y = x,y\n pts.append([x,y])\n\n\ndef main():\n cv2.namedWindow('res', cv2.WINDOW_NORMAL)\n cv2.setMouseCallback('res', get_xy)\n img = cv2.imread('scanned-form.jpg')\n\n while True:\n cv2.imshow('res', img)\n if cv2.waitKey(0) & 0xFF == ord('q'):\n break\n\n do_warp()\n\n cv2.destroyAllWindows()\n\nif __name__=='__main__':\n main()\n","sub_path":"document_scanner/img_transform.py","file_name":"img_transform.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"499286768","text":"largest = 0\n\ndef IsPalindrome( s ):\n for i in range( 0 , len(s) ):\n if ( s[i] != s[len(s)-i-1] ):\n return False\n return True\n\n\n\nfor a in range( 999 , 900 , -1 ):\n for b in range( 999 , 900 , -1 ):\n if ( a * b % 11 == 0):\n print ( a * b , IsPalindrome(str(a*b)))\n if(IsPalindrome(str(a*b))):\n if( a*b > largest):\n largest = a*b\nprint(largest)\n","sub_path":"Project Euler_4.py","file_name":"Project Euler_4.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"648730900","text":"from pytest import fixture\n\npytest_plugins = \"kotti\"\n\n\ndef settings():\n from kotti import _resolve_dotted\n from kotti import conf_defaults\n settings = conf_defaults.copy()\n settings['kotti.secret'] = 'secret'\n settings['kotti.secret2'] = 'secret2'\n settings['kotti.configurators'] = \\\n 'kotti_navigation.kotti_configure kotti_settings.kotti_configure'\n settings['kotti.populators'] = 'kotti.testing._populator'\n _resolve_dotted(settings)\n return settings\n\n\ndef setup_app():\n from kotti import base_configure\n return base_configure({}, **settings()).make_wsgi_app()\n\n\n@fixture\ndef kn_populate(db_session):\n from kotti_navigation.populate import populate\n populate()\n\n\n@fixture\ndef kn_setup():\n setup_app()\n\n\n@fixture\ndef kn_request(dummy_request):\n setattr(dummy_request, 'kotti_slot', 'left')\n return dummy_request\n","sub_path":"kotti_navigation/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"23267304","text":"#coding=utf-8\n'''\nCreated on 2015-9-29\n\n@author: duanfugao\n'''\n\nimport pymongo\nfrom collections import defaultdict\nimport jieba \nfrom datetime import *\nimport time\nimport sys\ndef readmongo(ip,port):\n #连接mongo\n client=pymongo.MongoClient(ip,port)\n db=client.kb\n collection=db.knowledgedoc \n collection1=db.keywords\n #读取collection\n posts=collection.find()\n\n #存储字典 key:关键词/省/市 value:知识点名称 (关键词是对知识点名称进行逐字拆分组合形成 +分词)\n indices=defaultdict(list)\n\n for post in posts:\n #注意name有空的情况\n name=post['name'] \n province=post['province']\n #注意city有空的情况\n city=post['city']\n \n #开始处理key \n #如果name为空 该数据则不进行处理了\n if not name.strip():\n continue\n #把词进行逐字拆分\n list1=list(name) \n for i in range(1,len(list1)+1):\n key=name[0:i]+\"/\"+province+\"/\"+city\n value=name \n if not key in indices.keys():\n indices[key].append(value)\n elif(value in indices[key]):\n break\n else:\n indices[key].append(value)\n break \n \n #利用结巴分词 精确模式\n default_mode=jieba.cut(name)\n str1 =\"/\".join(default_mode)\n str2=str1.split(\"/\")\n \n\n for str3 in str2:\n #判断字典中是否已存在key值了\n key2=str3+\"/\"+province+\"/\"+city\n value2=name\n #if not key2 in indices.keys():这样判断value会少结果 只能在查询时去重了\n #indices[key2].append(value2)\n if not key2 in indices.keys():\n indices[key2].append(value2)\n elif(value2 in indices[key2]):\n break\n else:\n indices[key2].append(value2)\n break \n \n #保存数据结构到mongo中\n savemongo(indices,collection1)\n \ndef savemongo(listdict,dbcollection):\n table_list = []\n systime= str(datetime.now()).split(\".\")[0]\n for k,v in listdict.items():\n\n res = dbcollection.find({\"_id\":k})\n if (res.count()==1):\n dbcollection.remove({\"_id\":k})\n\n one_row = {}\n one_row[\"_id\"] = k\n one_row[\"val\"] = list(set(v))\n one_row[\"uptime\"] = systime\n table_list.append(one_row)\n\n dbcollection.insert(table_list)\n print(\"插入数据成功完成!\")\n \n\nif __name__ == '__main__':\n \n #readmongo(\"localhost\",27017)\n #python readmongo.py localhost 27017\n readmongo(sys.argv[1],int(sys.argv[2]))\n","sub_path":"kbelementbylucene/shell/searchMogo/duan/readMongo.py","file_name":"readMongo.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"450893571","text":"\"\"\"\nDeprecated, most likely broken, to be removed\n\"\"\"\n\nfrom pathlib import Path\nfrom string import ascii_uppercase\nfrom typing import Tuple, Any, Union\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom alphafold.common import protein\nfrom alphafold.data import pipeline\nfrom alphafold.data import templates\nfrom alphafold.data.tools import hhsearch\nfrom colabfold.colabfold import run_mmseqs2\nfrom colabfold.utils import DEFAULT_API_SERVER\n\n\ndef mk_mock_template(query_sequence):\n # since alphafold's model requires a template input\n # we create a blank example w/ zero input, confidence -1\n ln = len(query_sequence)\n output_templates_sequence = \"-\" * ln\n output_confidence_scores = np.full(ln, -1)\n templates_all_atom_positions = np.zeros(\n (ln, templates.residue_constants.atom_type_num, 3)\n )\n templates_all_atom_masks = np.zeros((ln, templates.residue_constants.atom_type_num))\n templates_aatype = templates.residue_constants.sequence_to_onehot(\n output_templates_sequence, templates.residue_constants.HHBLITS_AA_TO_ID\n )\n template_features = {\n \"template_all_atom_positions\": templates_all_atom_positions[None],\n \"template_all_atom_masks\": templates_all_atom_masks[None],\n \"template_sequence\": [f\"none\".encode()],\n \"template_aatype\": np.array(templates_aatype)[None],\n \"template_confidence_scores\": output_confidence_scores[None],\n \"template_domain_names\": [f\"none\".encode()],\n \"template_release_date\": [f\"none\".encode()],\n }\n return template_features\n\n\ndef mk_template(query_sequence, a3m_lines, template_paths):\n template_featurizer = templates.TemplateHitFeaturizer(\n mmcif_dir=template_paths,\n max_template_date=\"2100-01-01\",\n max_hits=20,\n kalign_binary_path=\"kalign\",\n release_dates_path=None,\n obsolete_pdbs_path=None,\n )\n\n hhsearch_pdb70_runner = hhsearch.HHSearch(\n binary_path=\"hhsearch\", databases=[f\"{template_paths}/pdb70\"]\n )\n\n hhsearch_result = hhsearch_pdb70_runner.query(a3m_lines)\n hhsearch_hits = pipeline.parsers.parse_hhr(hhsearch_result)\n templates_result = template_featurizer.get_templates(\n query_sequence=query_sequence, hits=hhsearch_hits\n )\n return templates_result.features\n\n\ndef predict_structure(\n prefix, feature_dict, Ls, model_runner_and_params, do_relax=False, random_seed=0\n):\n \"\"\"Predicts structure using AlphaFold for the given sequence.\"\"\"\n\n # Minkyung's code\n # add big enough number to residue index to indicate chain breaks\n idx_res = feature_dict[\"residue_index\"]\n L_prev = 0\n # Ls: number of residues in each chain\n for L_i in Ls[:-1]:\n idx_res[L_prev + L_i :] += 200\n L_prev += L_i\n chains = list(\"\".join([ascii_uppercase[n] * L for n, L in enumerate(Ls)]))\n feature_dict[\"residue_index\"] = idx_res\n\n # Run the models.\n plddts, paes = [], []\n unrelaxed_pdb_lines = []\n relaxed_pdb_lines = []\n\n for model_name, (model_runner, params) in model_runner_and_params.items():\n print(f\"running {model_name}\")\n # swap params to avoid recompiling\n # note: models 1,2 have diff number of params compared to models 3,4,5 (this was handled on construction)\n model_runner.params = params\n\n processed_feature_dict = model_runner.process_features(\n feature_dict, random_seed=random_seed\n )\n prediction_result = model_runner.predict(processed_feature_dict)\n unrelaxed_protein = protein.from_prediction(\n processed_feature_dict, prediction_result\n )\n unrelaxed_pdb_lines.append(protein.to_pdb(unrelaxed_protein))\n plddts.append(prediction_result[\"plddt\"])\n paes.append(prediction_result[\"predicted_aligned_error\"])\n\n if do_relax:\n from alphafold.relax import relax\n from alphafold.common import residue_constants\n\n residue_constants.stereo_chemical_props_path = \"stereo_chemical_props.txt\"\n\n # Relax the prediction.\n amber_relaxer = relax.AmberRelaxation(\n max_iterations=0,\n tolerance=2.39,\n stiffness=10.0,\n exclude_residues=[],\n max_outer_iterations=20,\n )\n relaxed_pdb_str, _, _ = amber_relaxer.process(prot=unrelaxed_protein)\n relaxed_pdb_lines.append(relaxed_pdb_str)\n\n # rerank models based on predicted lddt\n lddt_rank = np.mean(plddts, -1).argsort()[::-1]\n out = {}\n print(\"reranking models based on avg. predicted lDDT\")\n for n, r in enumerate(lddt_rank):\n print(f\"model_{n + 1} {np.mean(plddts[r])}\")\n\n unrelaxed_pdb_path = f\"{prefix}_unrelaxed_model_{n + 1}.pdb\"\n with open(unrelaxed_pdb_path, \"w\") as f:\n f.write(unrelaxed_pdb_lines[r])\n set_bfactor(unrelaxed_pdb_path, plddts[r], idx_res, chains)\n\n if do_relax:\n relaxed_pdb_path = f\"{prefix}_relaxed_model_{n + 1}.pdb\"\n with open(relaxed_pdb_path, \"w\") as f:\n f.write(relaxed_pdb_lines[r])\n set_bfactor(relaxed_pdb_path, plddts[r], idx_res, chains)\n\n out[f\"model_{n + 1}\"] = {\"plddt\": plddts[r], \"pae\": paes[r]}\n return out\n\n\ndef handle_homooligomer(deletion_matrix, homooligomer, msa, query_sequence):\n if homooligomer == 1:\n msas = [msa]\n deletion_matrices = [deletion_matrix]\n else:\n # make multiple copies of msa for each copy\n # AAA------\n # ---AAA---\n # ------AAA\n #\n # note: if you concat the sequences (as below), it does NOT work\n # AAAAAAAAA\n msas = []\n deletion_matrices = []\n Ln = len(query_sequence)\n for o in range(homooligomer):\n L = Ln * o\n R = Ln * (homooligomer - (o + 1))\n msas.append([\"-\" * L + seq + \"-\" * R for seq in msa])\n deletion_matrices.append(\n [[0] * L + mtx + [0] * R for mtx in deletion_matrix]\n )\n return deletion_matrices, msas\n\n\ndef get_msa(\n query_sequence: str,\n jobname: str,\n homooligomer: int,\n use_templates: bool,\n use_msa: bool,\n use_env: bool,\n a3m_file: str,\n host_url: str = DEFAULT_API_SERVER,\n) -> Tuple[Any, Any, Any]:\n if use_templates:\n a3m_lines, template_paths = run_mmseqs2(\n query_sequence, jobname, use_env, use_templates=True, host_url=host_url\n )\n if template_paths is None:\n template_features = mk_mock_template(query_sequence * homooligomer)\n else:\n template_features = mk_template(query_sequence, a3m_lines, template_paths)\n elif use_msa:\n a3m_lines = run_mmseqs2(query_sequence, jobname, use_env, host_url=host_url)\n with open(a3m_file, \"w\") as text_file:\n text_file.write(a3m_lines)\n template_features = mk_mock_template(query_sequence * homooligomer)\n else:\n template_features = mk_mock_template(query_sequence * homooligomer)\n a3m_lines = \"\".join(open(a3m_file, \"r\").read())\n\n # parse MSA\n msa, deletion_matrix = pipeline.parsers.parse_a3m(a3m_lines)\n\n return msa, deletion_matrix, template_features\n\n\ndef plot_plddt_legend():\n thresh = [\n \"plDDT:\",\n \"Very low (<50)\",\n \"Low (60)\",\n \"OK (70)\",\n \"Confident (80)\",\n \"Very high (>90)\",\n ]\n plt.figure(figsize=(1, 0.1), dpi=100)\n for c in [\"#FFFFFF\", \"#FF0000\", \"#FFFF00\", \"#00FF00\", \"#00FFFF\", \"#0000FF\"]:\n plt.bar(0, 0, color=c)\n plt.legend(\n thresh,\n frameon=False,\n loc=\"center\",\n ncol=6,\n handletextpad=1,\n columnspacing=1,\n markerscale=0.5,\n )\n plt.axis(False)\n return plt\n\n\ndef plot_confidence(outs, homooligomer: int, query_sequence: str, model_num=1):\n model_name = f\"model_{model_num}\"\n plt.figure(figsize=(10, 3), dpi=100)\n \"\"\"Plots the legend for plDDT.\"\"\"\n\n plt.subplot(1, 2, 1)\n plt.title(\"Predicted lDDT\")\n plt.plot(outs[model_name][\"plddt\"])\n for n in range(homooligomer + 1):\n x = n * (len(query_sequence))\n plt.plot([x, x], [0, 100], color=\"black\")\n plt.ylabel(\"plDDT\")\n plt.xlabel(\"position\")\n\n plt.subplot(1, 2, 2)\n plt.title(\"Predicted Aligned Error\")\n plt.imshow(outs[model_name][\"pae\"], cmap=\"bwr\", vmin=0, vmax=30)\n plt.colorbar()\n plt.xlabel(\"Scored residue\")\n plt.ylabel(\"Aligned residue\")\n\n return plt\n\n\ndef set_bfactor(pdb_filename: Union[str, Path], bfac, idx_res, chains):\n in_file = open(pdb_filename, \"r\").readlines()\n out_file = open(pdb_filename, \"w\")\n for line in in_file:\n if line[0:6] == \"ATOM \":\n seq_id = int(line[22:26].strip()) - 1\n # FIXME: This is broken somehow but I don't understand how\n # seq_id = np.where(idx_res == seq_id)[0][0]\n out_file.write(\n f\"{line[:21]}{chains[seq_id]}{line[22:60]}{bfac[seq_id]:6.2f}{line[66:]}\"\n )\n out_file.close()\n","sub_path":"colabfold/single_sequence.py","file_name":"single_sequence.py","file_ext":"py","file_size_in_byte":9045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"640488838","text":"import numpy as np\nfrom scipy import signal\nimport matplotlib.pyplot as plt\n\n\ndef SingleSidedFFT(y, fs, scale = True):\n \"\"\" len(y) must be even \"\"\"\n l = len(y)\n Y = np.fft.fft(y) # fft\n Y = np.abs(Y) # abs to get magnitude\n Y = Y[:l//2+1] # only positive frequencies\n if scale:\n Y = Y/l # to scale it back\n Y[1:] = Y[1:]*2 # scale for single sided spectrum\n l = len(y)\n f = np.arange(0,l//2+1)*fs/l # from 0 to Nyquist\n return f, Y\n\ndef SquareSignal(f, fs, number_periods):\n period_len = fs // f\n high = np.ones(period_len // 2)\n low = np.ones(period_len // 2) * -1\n # square = np.concatenate((high,low))\n square = np.empty(0)\n for i in range(number_periods):\n square = np.concatenate((square,high))\n square = np.concatenate((square,low))\n t = np.arange(number_periods * period_len) / fs\n return t, square\n\ndef AddGaps(signal, gap_period, gap_len):\n i = 0\n while i < len(signal):\n signal[i:i+gap_len] = 0\n i += gap_period\n return signal\n\ndef Demodulate(signal, half_period_len):\n output_signal = np.copy( signal )\n i = 0\n count = 0\n while i < len(signal):\n output_signal[i:i+half_period_len] = signal[i:i+half_period_len] * ( (-1)**count )\n count += 1\n i += half_period_len\n return output_signal\n\n\n# constants\nFS_Hz = 800\n# print('Frequency resolution: {}Hz'.format(FS_Hz/L) )\n\n# ideal square signal\nF0 = 10\nF0_PERIOD = FS_Hz // F0\nF0_HALF_PERIOD = F0_PERIOD // 2\nPERIODS = 13\nL = PERIODS * F0_PERIOD\n\nt, sig_ideal = SquareSignal(F0, FS_Hz, PERIODS)\n# t = np.arange(PERIODS * FS_Hz / F0) / FS_Hz\n# sig_ideal = 3 + np.sin(2*np.pi*F0*t)\nf_sig_ideal, Y_sig_ideal = SingleSidedFFT(sig_ideal[-FS_Hz:], FS_Hz)\n# print('Frequency resolution: {}Hz'.format(FS_Hz/len(sig_ideal[:FS_Hz]) ))\nY_sig_ideal_dB = 20 * np.log10(Y_sig_ideal)\n\n# real square signal\noffset = -4\ngain = 10\nsig_real = sig_ideal + (gain*t) + offset\nsig_real = AddGaps(sig_real, F0_HALF_PERIOD, 8)\nf_sig_real, Y_sig_real = SingleSidedFFT(sig_real[-FS_Hz:], FS_Hz)\n\n# comb filter\ncomb1=np.zeros(L)\ncomb1[0] = 1\ncomb1[40] = -1\ncomb1 = comb1 / 2\nf_comb1, Y_comb1 = SingleSidedFFT(comb1, FS_Hz, False)\n\n# signal filtered comb1\nsig_filt1 = signal.convolve(sig_real, comb1)\nsig_filt1 = sig_filt1[0:L]\nf_sig_filt1, Y_sig_filt1 = SingleSidedFFT(sig_filt1[-FS_Hz:], FS_Hz)\n\n# signal filtered comb2\nsig_filt2 = signal.convolve(sig_filt1, comb1)\nsig_filt2 = sig_filt2[0:L]\nf_sig_filt2, Y_sig_filt2 = SingleSidedFFT(sig_filt2[-FS_Hz:], FS_Hz)\n\n# signal filtered comb3\nsig_filt3 = signal.convolve(sig_filt2, comb1)\nsig_filt3 = sig_filt3[0:L]\nf_sig_filt3, Y_sig_filt3 = SingleSidedFFT(sig_filt3[-FS_Hz:], FS_Hz)\n\n# demodulate\nsig_dem = Demodulate(sig_filt3, F0_HALF_PERIOD)\nf_sig_dem, Y_sig_dem = SingleSidedFFT(sig_dem[-FS_Hz:], FS_Hz)\n\n# LPF1\nlpf1 = np.ones(F0_PERIOD) / F0_PERIOD\nlpf1 = np.concatenate( (lpf1, np.zeros(L-F0_PERIOD)) )\nf_lpf1, Y_lpf1 = SingleSidedFFT(lpf1, FS_Hz, False)\n\n# signal filtered LPF1\nsig_lpf1 = signal.convolve(sig_dem, lpf1)\nsig_lpf1 = sig_lpf1[0:L]\nf_sig_lpf1, Y_sig_lpf1 = SingleSidedFFT(sig_lpf1[-FS_Hz:], FS_Hz)\n\n# plots\nfig, axes = plt.subplots(4, 3)\n\naxes[0][0].plot(t, sig_ideal, '.-', label ='ideal')\naxes[0][0].plot(t, sig_real, '.-', label ='real')\n\naxes[0][2].plot(f_sig_ideal, Y_sig_ideal, '-', label ='ideal FFT')\naxes[0][2].plot(f_sig_real, Y_sig_real, '-', label ='real FFT')\n\naxes[1][0].plot(t, sig_filt1, '.-', label ='filt1')\naxes[1][0].plot(t, sig_filt2, '.-', label ='filt2')\naxes[1][0].plot(t, sig_filt3, '.-', label ='filt3')\n\naxes[1][1].plot(f_comb1, Y_comb1, '-', label ='comb1 FFT')\n\naxes[1][2].plot(f_sig_ideal, Y_sig_ideal, '-', label ='ideal FFT')\naxes[1][2].plot(f_sig_filt1, Y_sig_filt1, '-', label ='filt1 FFT')\naxes[1][2].plot(f_sig_filt2, Y_sig_filt2, '-', label ='filt2 FFT')\naxes[1][2].plot(f_sig_filt3, Y_sig_filt3, '-', label ='filt3 FFT')\n\naxes[2][0].plot(t, sig_dem, '.-', label ='dem')\n\naxes[2][2].plot(f_sig_dem, Y_sig_dem, '-', label ='dem FFT')\n\naxes[3][0].plot(t, sig_lpf1, '.-', label ='sig_lpf1')\n\naxes[3][1].plot(f_lpf1, Y_lpf1, '-', label ='lpf1 FFT')\n\naxes[3][2].plot(f_sig_lpf1, Y_sig_lpf1, '-', label ='sig_lpf1 FFT')\n\n\nfor ax_r in axes:\n for ax_c in ax_r:\n ax_c.legend()\n ax_c.grid()\nplt.subplots_adjust(wspace=0.15, hspace=0.15)\nplt.show()","sub_path":"python/comb_a_square_wave.py","file_name":"comb_a_square_wave.py","file_ext":"py","file_size_in_byte":4413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"413671535","text":"import sys\n\n# Let's setup two operation instructions for our simple machine: PRINT_BEEJ and HALT\nPRINT_BEEJ = 1\nHALT = 2\nPRINT_NUM = 3\nSAVE = 4\nPRINT_REGISTER = 5\nADD = 6\n\n# This sets our program's memory for what it will do, print 4 times and halt\nmemory = [\n PRINT_BEEJ,\n SAVE, # SAVE 62 to register 2\n 65,\n 2,\n SAVE, # Save 20 to register 3\n 20,\n 3,\n ADD, # add register 3 to register 2, R2 += R3\n 2,\n 3,\n PRINT_REGISTER, # prints value at register 2\n 2,\n HALT # We should always halt to prevent memory leaks\n]\n\n# Creates an array of 8 0's\nregister = [0] * 8\n\n# Sets a pointer to the instructions we're currently running on\n\npc = 0\n\n# Tells us our program is running\nrunning = True\n\nwhile running:\n # Looks at where we are in the memory\n command = memory[pc]\n\n # Then we process it to handle the command\n if command == PRINT_BEEJ:\n print(\"BEEJ\")\n\n elif command == HALT:\n running = False\n\n elif command == PRINT_NUM:\n num = memory[pc + 1]\n print(num)\n pc += 2\n\n elif command == SAVE:\n # The number to save is the next value in memory\n num = memory[pc + 1]\n # The register place to save it is the following value in memory\n reg = memory[pc + 2]\n # Sets these to the register\n register[reg] = num\n # Increment by 3\n pc += 3\n \n elif command == ADD:\n # Sets first adding register index to the next value in memory\n reg_a = memory[pc + 1]\n # Sets second adding register index to the following value in memory\n reg_b = memory[pc + 2]\n\n # Adds the second register index value to the first\n register[reg_a] += register[reg_b]\n # Increments by 3\n pc += 3\n \n elif command == PRINT_REGISTER:\n # Sets the register index to print to the next value in memory\n reg_index = memory[pc + 1]\n # Prints the register at that place\n print(register[reg_index])\n # Increments by 2\n pc += 2\n\n else:\n print(f\"Unknown instruction: {command}\")\n sys.exit(1)\n\n # Increment our program pointer by one\n pc += 1","sub_path":"7-assets/past-student-repos/_Individual-Projects/Computer-Architecture-Notes-master/lectureI/lectureI.py","file_name":"lectureI.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"321970991","text":"import pylab\nimport tables\nimport math\nimport numpy\npylab.rc('text', usetex=True)\n\nNT = 100\nEy_tx = numpy.zeros( (NT+1, 400), numpy.float )\nfor i in range(NT+1):\n fh = tables.openFile(\"s69-plasmabeach_q_%d.h5\" % i)\n q = fh.root.StructGridField\n Ey = q[:,11]\n Ey_tx[i,:] = Ey\n\ndx = 1/400.0\nX = pylab.linspace(0.5*dx, 1-0.5*dx, 400)\nT = pylab.linspace(0, 5e-9, NT+1)\nTT, XX = pylab.meshgrid(T, X)\n\n# compute cutoff location\ndx100 = 1/100.\ndeltaT = dx100/2.99792458e8\ndriveOmega = 3.14159265358979323846264338328/10/deltaT\nxcutoff = 1-math.pow(driveOmega/25*deltaT, 1/5.0)\n\npylab.pcolormesh(TT, XX, Ey_tx.transpose())\npylab.plot([0, 5e-9], [xcutoff, xcutoff], 'k--', linewidth=2)\npylab.xlabel('Time [s]')\npylab.ylabel('X [m]')\npylab.title(r'$E_y(t,x)$')\npylab.savefig('s69-plasmabeach_Ey.png')\npylab.show()\n","sub_path":"source/sims/s69/plt-plasmabeach.py","file_name":"plt-plasmabeach.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"499161247","text":"# Databricks notebook source\n# MAGIC %run /Shared/churn-model/utils\n\n# COMMAND ----------\n\n# Workspace config\nworkspace_name = ''\nresource_group = ''\nsubscription_id = ''\n\n# Model\nmodel_name = 'churn-model'\nmodel_description = 'Model to predict churn'\nmodel_path = '/dbfs/models/churn-prediction'\n\n# Environment\nenvironment_name = 'xgboost_env'\nconda_dep_file = '/dbfs/models/churn-prediction/conda.yaml'\nentry_script = '/dbfs/models/churn-prediction/score.py'\n\n#Endpoint - PROD\nendpoint_name = 'api-churn-prod'\naks_name = 'aks-e2e-1'\n\nworkspace = get_workspace(workspace_name, resource_group, subscription_id)\n\nmodel_azure = register_model(workspace, model_name, model_description, model_path)\n\ninference_config = get_inference_config(environment_name, conda_dep_file, entry_script)\nservice = deploy_aks(workspace, model_azure, endpoint_name, inference_config, aks_name)","sub_path":"mlops/src/deploy-aks.py","file_name":"deploy-aks.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"85681989","text":"with open('./08data.txt') as f:\n cipher_txts = [bytes.fromhex(line.strip()) for line in f]\n\ndef has_repeated_block(txt, block_size = 16):\n if len(txt) % 16 != 0:\n return\n else:\n num_blocks = len(txt)//block_size\n\n blocks = [txt[i*block_size:(i+1)*block_size] for i in range(num_blocks)]\n if (len(set(blocks)) != num_blocks):\n return True\n else:\n return False\n\nECB_encrypted = list()\nfor (line_num, cipher_txt) in enumerate(cipher_txts):\n if has_repeated_block(cipher_txt):\n line = line_num\n txt = cipher_txt\n candidate = {\"line\":line, \"txt\":txt}\n ECB_encrypted.append(candidate)\n\nprint('ECB encoded ciphertext:')\nfor candidate in ECB_encrypted:\n line = candidate['line']\n txt = candidate['txt']\n print(f'line: {line}\\nciphertext: {txt}')\n\n","sub_path":"8/code/problem8.py","file_name":"problem8.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"279763046","text":"from glob import glob\nfrom PIL import Image\nfrom random import choice\nimport pandas as pd\nfrom tqdm import tqdm\nfrom time import time\nimport torch\nfrom apex import amp\nfrom maskrcnn_benchmark.config import cfg\nfrom torchvision import transforms as T\nfrom maskrcnn_benchmark.modeling.detector import build_detection_model\nfrom maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer\nfrom maskrcnn_benchmark.utils.model_serialization import load_state_dict\nfrom maskrcnn_benchmark.structures.image_list import to_image_list\n\n\namp.init(enabled=True)\n\nclass Detector():\n def __init__(self, cfg_path, weights_path, input_shape=(608, 608)):\n cfg.merge_from_file(cfg_path)\n cfg.merge_from_list(['DTYPE', 'float16'])\n self._cfg = cfg.clone()\n self._model = build_detection_model(self._cfg)\n self._model.eval()\n self._device = 'cuda'\n self._model.to(self._device)\n self.shape = input_shape\n\n save_dir = cfg.OUTPUT_DIR\n checkpoint = torch.load(weights_path, map_location=torch.device(\"cpu\"))\n load_state_dict(self._model, checkpoint.pop(\"model\"))\n\n self._transform = self._build_transform()\n\n #self._model.half()\n\n\n def __call__(self, frame):\n return self.infer(frame)\n\n def infer(self, frames):\n\n #print(frames)\n tik = time()\n transformed_frame = [self._transform(f) for f in frames]\n tok = time()\n print(\"elapsed {:d}ms for preprocessing {} crops\".format(int(1000*(tok-tik)), len(frames)))\n image_list = to_image_list(transformed_frame, self._cfg.DATALOADER.SIZE_DIVISIBILITY)\n image_list = image_list.to(self._device)\n\n # compute predictions\n with torch.no_grad():\n predictions = self._model(image_list)\n predictions = [o.to('cpu') for o in predictions]\n\n # bboxes = prediction.bbox.numpy()\n # labels = prediction.get_field('labels').numpy()\n # scores = prediction.get_field('scores').numpy()\n #\n # return list(zip(bboxes, labels, scores))\n\n\n def _build_transform(self):\n \"\"\"\n Creates a basic transformation that was used to train the models\n \"\"\"\n if self._cfg.INPUT.TO_BGR255:\n to_bgr_transform = T.Lambda(lambda x: x * 255)\n else:\n to_bgr_transform = T.Lambda(lambda x: x[[2, 1, 0]])\n\n normalize_transform = T.Normalize(\n mean=self._cfg.INPUT.PIXEL_MEAN, std=self._cfg.INPUT.PIXEL_STD\n )\n\n transform = T.Compose(\n [\n # T.Resize(self._cfg.INPUT.MIN_SIZE_TEST),\n T.ToTensor(),\n to_bgr_transform,\n normalize_transform,\n ]\n )\n return transform\n\n\ndef get_crops(img, x_from, y_from, x_to, y_to, size):\n width, height = x_to - x_from, y_to - y_from\n\n x_count = width // size + 1\n step_x = max(int(0.5 + (width - size) / x_count), 1)\n x_to = x_from + width - size + 1\n\n y_count = height // size + 1\n step_y = max(int(0.5 + (height - size) / y_count), 1)\n y_to = y_from + height - size + 1\n# print(y_count, y_from ,y_to, step_y)\n\n crops = []\n shifts = []\n for y in range(y_from, y_to, step_y):\n for x in range(x_from, x_to, step_x):\n crops.append(img.crop((x, y, x+size, y+size)))\n shifts.append((x, y))\n\n return crops, shifts\n\n\npath = '/data/ice/images/2018-03-07_1336_right/025520.jpg'\nimg = Image.open(path)\ncrops, shifts = get_crops(img, 0, 0, 2448, 1208, 608)\n\nmodel = Detector('configs/efnet_retina.yaml', '/data/mask_ckpts/rc_608/model_final.pth')\n\n\n\nfor c in crops:\n tik = time()\n predictions = model([c])\n print(predictions)\n tok = time()\n\n print(\"elapsed {:d}ms for one crop\".format(int(1000*(tok-tik)), len(crops)))\n\ntik = time()\n\nmodel(crops)\n\ntok = time()\nprint(\"elapsed {:d}ms for {} crops\".format(int(1000*(tok-tik)), len(crops)))\n","sub_path":"predict_hires.py","file_name":"predict_hires.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"418377003","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom . import models, forms\nfrom django.views import View\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import user_passes_test\n# Create your views here.\n\n\n@login_required\ndef cursos(request):\n\tcursos = models.Curso.objects.all()\n\treturn render(request, 'cursos.html', { 'cursos':cursos })\n\n@login_required\ndef descripcion_curso(request, id_curso):\n\tcurso = models.Curso.objects.get(pk=id_curso)\n\treturn render(request, 'descripcion_curso.html', { 'curso':curso })\n\n@login_required\n@user_passes_test(lambda u: u.is_superuser)\ndef borrar_curso(request, id_curso):\n\tmodels.Curso.objects.get(pk=id_curso).delete()\n\treturn redirect('lista_cursos')\n\n@method_decorator(login_required, name='dispatch')\nclass AgregarCurso(View):\n\ttemplate='agregar_curso.html'\n\tdef get(self, request):\n\t\tif request.user.is_superuser:\n\t\t\treturn render(request, self.template, {'form': forms.AgregarCurso()})\n\t\telse:\n\t\t\treturn redirect('lista_cursos')\n\n\tdef post(self, request):\n\t\tif request.user.is_superuser:\n\t\t\tprint(request.POST)\n\t\t\tnuevo_curso = forms.AgregarCurso(request.POST)\n\t\t\tif nuevo_curso.is_valid():\n\t\t\t\tnuevo_curso.save()\n\n\t\treturn redirect('lista_cursos')\n\n@login_required\ndef editar_curso(request, id_curso):\n\tcurso = models.Curso.objects.get(pk=id_curso)\n\tpreguntas = models.Pregunta.objects.filter(curso=curso)\n\treturn render(request, 'editar_curso.html', {'curso':curso, 'preguntas':preguntas})\n\n@method_decorator(login_required, name='dispatch')\nclass EditarCursoDetalles(View):\n\ttemplate='editar_curso_detalle.html'\n\tdef get(self, request, id_curso):\n\t\tif request.user.is_superuser:\n\t\t\tcurso = models.Curso.objects.get(pk=id_curso)\n\t\t\treturn render(request, self.template, {'curso':curso, 'form': forms.AgregarCurso(instance=curso)})\n\t\telse:\n\t\t\treturn redirect('lista_cursos')\n\n\tdef post(self, request, id_curso):\n\t\tif request.user.is_superuser:\n\t\t\tprint(request.POST)\n\t\t\tcurso = forms.AgregarCurso(request.POST, instance=models.Curso.objects.get(pk=id_curso))\n\t\t\tif curso.is_valid():\n\t\t\t\tcurso.save()\n\t\t\t\treturn redirect('editar_curso', id_curso=id_curso)\n\t\treturn redirect('lista_cursos')\n\n\n@method_decorator(login_required, name='dispatch')\nclass Preguntas(View):\n\ttemplate = 'preguntas.html'\n\tTIPO_PREGUNTA = {\n\t\t'LE': forms.PreguntaGeneral,\n\t\t'OM': forms.PreguntaOpcionMultiple,\n\t}\n\n\tdef get(self, request, id_curso, id_pagina):\n\t\tuser = User.objects.get(pk=request.user.pk)\n\t\tcurso = models.Curso.objects.get(pk=id_curso)\n\t\tquery_preguntas = models.Pregunta.objects.filter(curso=curso)\n\n\t\tif int(id_pagina) < query_preguntas.count():\n\t\t\tpregunta = query_preguntas[int(id_pagina)]\n\t\t\tcontext = {\n\t\t\t\t'pregunta': pregunta,\n\t\t\t\t'form': self.TIPO_PREGUNTA[pregunta.tipo](instance=pregunta)\n\t\t\t}\n\t\t\tprint(context)\n\t\t\treturn render(request, self.template, context)\n\t\telse:\n\t\t\treturn redirect('home')\n\n\tdef post(self, request, id_curso, id_pagina):\n\t\tuser = User.objects.get(pk=request.user.pk)\n\t\tcurso = models.Curso.objects.get(pk=id_curso)\n\t\tpregunta = models.Pregunta.objects.get(pk=request.POST['pregunta_pk'])\n\n\t\trespuesta ,_ = models.RespuestaUsuario.objects.get_or_create(usuario=user, curso=curso, pregunta=pregunta)\n\n\n\t\tresultado = False\n\t\tif pregunta.tipo == 'OM':\n\t\t\trespuesta_usuario = models.PreguntaOpciónMultiple.objects.get(pk=request.POST['resultado']) \n\t\t\trespuesta_correcta = models.PreguntaOpciónMultiple.objects.get(pregunta=pregunta, resultado=True)\n\t\t\tif respuesta_usuario.pk == respuesta_correcta.pk:\n\t\t\t\tresultado = True\n\t\telif pregunta.tipo == 'LE':\n\t\t\trespuesta_usuario = request.POST['resultado']\n\t\t\trespuesta_correcta = models.PreguntaOpciónMultiple.objects.get(pregunta=pregunta, resultado=True)\n\t\t\tif respuesta_usuario.lower() == respuesta_correcta.texto.lower():\n\t\t\t\tresultado = True\n\n\t\trespuesta.resultado = resultado\n\t\trespuesta.save()\n\n\t\tcalificaciones_preguntas_curso = models.RespuestaUsuario.objects.filter(usuario=user, curso=curso)\n\n\t\tcalificacion_curso = 0\n\t\tfor calificacion in calificaciones_preguntas_curso:\n\t\t\tif calificacion.resultado:\n\t\t\t\tcalificacion_curso += 1\n\n\t\tcalificacion_curso = (calificacion_curso/calificaciones_preguntas_curso.count())*100\n\n\n\t\tcalificacion_perfil_usuario,_ = models.ResultadoExamenUsuario.objects.get_or_create(usuario=user, curso=curso)\n\t\tcalificacion_perfil_usuario.puntaje = calificacion_curso\n\t\tcalificacion_perfil_usuario.save()\n\n\n\t\treturn redirect('preguntas', id_curso=id_curso, id_pagina=int(id_pagina)+1)\n\n\n@method_decorator(login_required, name='dispatch')\nclass AgregarPregunta(View):\n\ttemplate = 'agregar_pregunta.html'\n\tdef get(self, request, id_curso):\n\t\tif request.user.is_superuser:\n\t\t\tcurso = models.Curso.objects.get(pk=id_curso)\n\t\t\treturn render(request, self.template, {'curso':curso, 'form':forms.AgregarPregunta()})\n\t\treturn redirect('lista_cursos')\n\n\tdef post(self, request, id_curso):\n\t\tif request.user.is_superuser:\n\t\t\tcurso = models.Curso.objects.get(pk=id_curso)\n\t\t\tpregunta = forms.AgregarPregunta(request.POST)\n\t\t\tif pregunta.is_valid():\n\t\t\t\tnueva_pregunta = pregunta.save(commit=False)\n\t\t\t\tnueva_pregunta.curso = curso\n\t\t\t\tnueva_pregunta.save()\n\t\t\treturn redirect('editar_curso', id_curso=id_curso)\n\t\treturn redirect('lista_cursos')\n\n@login_required\n@user_passes_test(lambda u: u.is_superuser)\ndef borrar_pregunta(request, id_curso, id_pregunta):\n\tmodels.Pregunta.objects.get(pk=id_pregunta).delete()\n\treturn redirect('editar_curso', id_curso=id_curso)\n\n@login_required\n@user_passes_test(lambda u: u.is_superuser)\ndef editar_pregunta(request, id_curso, id_pregunta):\n\tcurso = models.Curso.objects.get(pk=id_curso)\n\tpregunta = models.Pregunta.objects.get(pk=id_pregunta)\n\trespuestas = models.PreguntaOpciónMultiple.objects.filter(pregunta=pregunta)\n\treturn render(request, 'descripcion_pregunta.html', {'curso':curso, 'pregunta':pregunta, 'respuestas':respuestas})\n\n\n\n@method_decorator(login_required, name='dispatch')\nclass AgregarRespuesta(View):\n\ttemplate = 'agregar_respuesta.html'\n\tdef get(self, request, id_curso, id_pregunta):\n\t\tif request.user.is_superuser:\n\t\t\tcurso = models.Curso.objects.get(pk=id_curso)\n\t\t\tpregunta = models.Pregunta.objects.get(pk=id_pregunta)\n\t\t\treturn render(request, self.template, {'curso':curso, 'pregunta':pregunta, 'form':forms.AgregarRespuesta()})\n\t\treturn redirect('editar_pregunta')\n\n\tdef post(self, request, id_curso, id_pregunta):\n\t\tif request.user.is_superuser:\n\t\t\tcurso = models.Curso.objects.get(pk=id_curso)\n\t\t\tpregunta = models.Pregunta.objects.get(pk=id_pregunta)\n\t\t\tprint(request.POST)\n\t\t\trespuesta = forms.AgregarRespuesta(request.POST)\n\t\t\tprint(respuesta.is_valid())\n\t\t\tif respuesta.is_valid():\n\t\t\t\tnueva_respuesta = respuesta.save(commit=False)\n\t\t\t\tnueva_respuesta.pregunta = pregunta\n\t\t\t\tnueva_respuesta.save()\n\t\t\treturn redirect('editar_pregunta', id_curso=id_curso, id_pregunta=id_pregunta)\n\t\treturn redirect('lista_cursos')\n\ndef borrar_pregunta(request, id_curso, id_pregunta, id_respuesta):\n\tmodels.PreguntaOpciónMultiple.objects.get(pk=id_respuesta).delete()\n\treturn redirect('editar_pregunta', id_curso=id_curso, id_pregunta=id_pregunta)","sub_path":"encuesta_curso/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"192896367","text":"import sympy as sy\n\n##from sympy.printing import print_rcode\n##from sympy.functions import sin, cos, Abs, sqrt\n##from sympy import Lambda\n## from sympy.abc import x\n\nsy.init_printing()\n\n## criando variavel simbolica\nx = sy.var('x')\n\n## definindo uma função\nf = sy.Lambda(x, 2 - sy.sqrt(x**2 - 1))\n\n## f de 1\nsy.print_rcode(f(1))\n\n## imprimindo o grafico da função f\nsy.plot(f(x))\n\n\n","sub_path":"src/funcoes.py","file_name":"funcoes.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"280865337","text":"from collections import OrderedDict\n# implement with ordered Dictionary\nclass LRUCache:\n def __init__(self, Capacity):\n self.size = Capacity\n self.cache = OrderedDict()\n\n def get(self, key):\n if key not in self.cache: return -1\n val = self.cache[key]\n self.cache.move_to_end(key)\n return val\n\n def put(self, key, val):\n if key in self.cache: del self.cache[key]\n self.cache[key] = val\n if len(self.cache) > self.size:\n self.cache.popitem(last=False)\n\nfrom collections import deque\n\nclass LRUCache:\n def __init__(self, capacity):\n self.cap = capacity\n self.d = {}\n self.lrqueue = deque(maxlen=self.cap)\n \n def get(self, key):\n if key in self.d:\n self.lrqueue.remove(key)\n self.lrqueue.append(key)\n return self.d[key]\n else:\n return -1\n\n def put(self, key, value):\n if key in self.d:\n self.d[key] = value\n self.lrqueue.remove(key)\n self.lrqueue.append(key)\n elif len(self.d) < self.cap:\n self.d[key] = value\n self.lrqueue.append(key)\n else:\n lr = self.lrqueue.popleft()\n self.d.pop(lr)\n self.lrqueue.append(key)\n self.d[key] = value\n","sub_path":"LRU.py","file_name":"LRU.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"525084460","text":"import requests\nfrom requests_html import HTML\nfrom multiprocessing import Pool\nimport urllib.parse\n\nbillboard = ''\ndef fetch(url):\n response = requests.get(url)\n response = requests.get(url, cookies={'over18': '1'})\n return response\n\ndef parse_article_entries(doc):\n html = HTML(html=doc)\n post_entries = html.find('div.r-ent')\n return post_entries\n\ndef parse_content_entries(doc):\n html = HTML(html=doc)\n post_entries = html.find('div.bbs-screen', first=True).text.split(\"\\n\")\n content = post_entries[4]\n billboard = post_entries[1].split(\"看板\")[-1]\n messages = []\n for val in post_entries:\n if val.find('推') != -1 or val.find('→') != -1 or val.find('噓')!= -1:\n messages.append(val)\n pass\n pass\n return content, messages, billboard\n\n\ndef findContentHtml(entry):\n urls = list(entry.links)\n for url in urls:\n if url.find('html') != -1:\n return url\n\ndef parse_article_meta(entry):\n '''\n 每筆資料都存在 dict() 類型中:key-value paird data\n '''\n # contentUrl = list(entry.links)\n contentUrl = findContentHtml(entry)\n url = urllib.parse.urljoin(\"https://www.ptt.cc/\", contentUrl)\n # resp = requests.get(url)\n resp = fetch(url)\n content, messages, billboard = parse_content_entries(resp.text)\n return {\n 'date': entry.find('div.date', first=True).text,\n 'title': entry.find('div.title', first=True).text,\n 'author': entry.find('div.author', first=True).text,\n 'content': content,\n 'push': entry.find('div.nrec', first=True).text,\n 'messages': messages,\n 'billboard': billboard,\n }\n\ndef main():\n url = 'https://www.ptt.cc/bbs/Soft_Job/index.html'\n resp = fetch(url)\n post_entries = parse_article_entries(resp.text)\n # print(post_entries)\n for entry in post_entries:\n meta = parse_article_meta(entry)\n print(\"-----------------------\")\n print('date:')\n print(meta['date'])\n print('author:')\n print(meta['author'])\n print('title:')\n print(meta['title'])\n print('content:')\n print(meta['content'])\n print('billboard:')\n print(meta['billboard'])\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"part2_pttScrapy.py","file_name":"part2_pttScrapy.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"474265196","text":"import cv2\nimport datetime\nimport os\nimport numpy as np\n#these are the cascades: thay are already present in the opencv\ncascade_face = cv2.CascadeClassifier(cv2.data.haarcascades +'haarcascade_frontalface_default.xml') \ncascade_smile = cv2.CascadeClassifier(cv2.data.haarcascades +'haarcascade_smile.xml')\n\n#function ot detect the face\n\n# gray image of our face, original image:\ndef detection(grayscale, img):\n \n #1.3 is the scale factor , 5 is te min neighbours\n face = cascade_face.detectMultiScale(grayscale, 1.3, 5)\n \n #4 corrdinates in faces\n for (x_face, y_face, w_face, h_face) in face:\n \n #draw rectangle\n #cv2.rectangle(img, (x_face, y_face), (x_face+w_face, y_face+h_face), (255, 130, 0), 2)\n \n \n #area of intreset in gray image\n ri_grayscale = grayscale[y_face:y_face+h_face, x_face:x_face+w_face]\n \n #area of intrest in coloured image\n ri_color = img[y_face:y_face+h_face, x_face:x_face+w_face] \n \n # smile detection , 1.7 is the scale factor , 20 is the min neighbour\n smile = cascade_smile.detectMultiScale(ri_grayscale, 1.7, 30)\n \n #draw rectangle on smile ## uncomment to add rectangle to smile\n for (x_smile, y_smile, w_smile, h_smile) in smile: \n #cv2.rectangle(ri_color,(x_smile, y_smile),(x_smile+w_smile, y_smile+h_smile), (255, 0, 130), 2)\n \n #import image of tongue\n img_tongue= cv2.imread('tongue.png',-1)\n #cv2.imshow('image', img_tongue) \n \n #rectngle of smile , uncomment it to see rectangle of smile\n #cv2.rectangle(ri_color,(x_smile, y_smile),(x_smile+w_smile, y_smile+h_smile), (255, 0,225), 2) \n\n #depth of tongue, width\n dept_tong, width_tong= img_tongue.shape[:2]\n \n #make width to that of 1/3rd of smile\n width_for_tongue= w_smile/3\n scale= width_for_tongue/width_tong\n \n #adjust dept to same but maintining te aspect ratio\n depth_for_tongue= scale* dept_tong\n width_for_tongue = int(width_for_tongue)\n depth_for_tongue = int(depth_for_tongue)\n \n \n ##roi tongue\n img_tongue= cv2.resize(img_tongue, (width_for_tongue, depth_for_tongue))\n\n\n # white to black\n frame= img_tongue\n frame[np.where((frame == [255,255,255]).all(axis = 2))] = [0,0,0] # it works\n img_tongue= frame\n \n #finding centre of smile\n centre_smile_x= int(x_smile+ w_smile/2)\n centre_smile_y= int(y_smile+ h_smile/2)\n \n #finding the corrdinates for tongue\n x_tongue=int( centre_smile_x- width_for_tongue/2)\n y_tongue= int(centre_smile_y)\n \n #region of intrest for tongue\n roi_tongue= ri_color[y_tongue: y_tongue+depth_for_tongue, x_tongue: x_tongue+width_for_tongue]\n \n #making dimensions equal\n min_d= min(roi_tongue.shape[0], img_tongue.shape[0])\n min_w= min(roi_tongue.shape[1], img_tongue.shape[1])\n roi_tongue= ri_color[y_tongue: y_tongue+min_d, x_tongue: x_tongue+min_w]\n img_tongue= img_tongue[0: min_d,0: min_w]\n \n \n #adding htem \n dst = cv2.addWeighted(roi_tongue, 0.9,img_tongue,0.5, 0)\n ri_color[y_tongue: y_tongue+depth_for_tongue, x_tongue: x_tongue+width_for_tongue] = dst\n\n\n # ears\n ear_width= w_face\n img_ear= cv2.imread('bunny4.png',-1)\n h,w,c= img_ear.shape\n ratio= ear_width/w\n w= int(w*ratio)\n d= int(h*ratio)\n img_ear= cv2.resize(img_ear, (w,d))\n\n \n roi_ear= img[y_face-d: y_face,x_face:x_face+w]\n \n min_d= min(roi_ear.shape[0], img_ear.shape[0])\n min_w= min(roi_ear.shape[1], img_ear.shape[1])\n roi_ear= img[y_face-min_d: y_face,x_face:x_face+min_w]\n img_ear= img_ear[0: min_d,0: min_w]\n \n dst = cv2.addWeighted(roi_ear, 0.8, img_ear, 0.9, 0)\n img[y_face-min_d: y_face,x_face:x_face+min_w]= dst\n cv2.imshow('Video', img)\n #cv2.waitKey(0) \n #cv2.destroyAllWindows()\n \n #return image \n return img \n\n\n\n\n\nvc = cv2.VideoCapture(0) \n#path\npath= os.getcwd()\n\n# Create directory\ndirName = 'tempimage_folder'\ntry:\n os.mkdir(dirName)\nexcept FileExistsError:\n print(\"Directory \" , dirName , \" already exists\")\npath= path+'/'+dirName\ncnt=0\nwhile cnt<500:\n #read status of camera and frame\n _, img = vc.read() \n \n #convert image ot grayscale\n grayscale = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) \n \n #reuslt from detection function\n final = detection(grayscale, img) \n \n #showing captured image\n cv2.imshow('Video', final) \n \n #name of our image, wiht current time , so that it has new name each time.\n string = \"pic\"+str(datetime.datetime.now())+\".jpg\"\n \n \n #save image\n cv2.imwrite(os.path.join(path, string),final)\n \n if cv2.waitKey(1) & 0xFF == ord('q'):\n break \n \n cnt+=1\n\nvc.release() \ncv2.destroyAllWindows() \n","sub_path":"code/sticker/sticker_ ear_and_tongue.py","file_name":"sticker_ ear_and_tongue.py","file_ext":"py","file_size_in_byte":5344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"33930129","text":"from math import factorial as fact\nimport numpy as np\nimport pickle\nimport timeit\nimport PCE_functions as fn\nfrom sklearn.linear_model import LinearRegression\nimport os\nfrom time import time\n\n### define input parameters\n# number of input variables (model dimension), tv and tr for test\nM = 41\n# max total degree\np = 1\n# oversampling rate\nk = 2\n# the dimension as basis\nM1 = 16\n# bounds for distribution\nbound_uni = [0.01, 0.2]\n\n# cardinality (number of coefficients)\nP = fact(M+p)/(fact(M)*fact(p))\n# total runs of experimental design (input number of each variable)\nn = int(k*P)\n# sampling (initial thickness, to be scaled later)\nts_samp = fn.sampling('uniform', bound_uni, M, n, M1=M1) # shape=M*n\n\n# ### evaluate experimental design with ts_samp (to create PCE model)\n# # scaled thickness of all panels for all experimental designs\n# ts_scaled = np.zeros((M,n))\n# # start evaluating\n# Y_ED = np.zeros(n)\n# for i in range(n):\n# print('\\n********** start evaluating the ' + str(i + 1) + 'th of ' + str(n) + ' experimental designs **********')\n# start = timeit.default_timer()\n#\n# Y_ED[i],t_scaled = fn.evaluate_response(ts_samp[:,i],scale=False,l2d=15)\n# ts_scaled[:,i] = t_scaled\n#\n# if i%10 == 9:\n# with open('D:/Master_Thesis/code_data/footfall_analysis_optimization_PCE/data/M' + str(M) + '_p' + str(\n# p) + '_k' + str(k) + '_temp_n'+str(i+1)+'_samp_uniform_thickness.pkl', 'wb') as data:\n# pickle.dump([Y_ED, ts_scaled], data)\n# try:\n# os.remove(\n# 'D:/Master_Thesis/code_data/footfall_analysis_optimization_PCE/data/M' + str(\n# M) + '_p' + str(\n# p) + '_k' + str(k) + '_temp_n' + str(i - 9) + '_samp_uniform_thickness.pkl')\n# except:\n# pass\n#\n# stop = timeit.default_timer()\n# print('********** evaluation of the ' + str(i + 1) + 'th experimental design finished, time = '+str(stop-start)+' s\\n')\n#\n# with open('D:/Master_Thesis/code_data/footfall_analysis_optimization_PCE/data/Y_t_M' + str(M) + '_p' + str(\n# p) + '_k' + str(k) + '_uniformThickness_0.01_0.2_l2d15.pkl', 'wb') as data:\n# pickle.dump([Y_ED, ts_scaled], data)\n\n# ### approximation with polynomials\n# ## load Y_ED and t_scaled if not generated from aboce\n# # p=2\n# # file_name = 'D:/Master_Thesis/code_data/footfall_analysis_optimization_PCE/data/Y_t_M' + str(M) + '_p' + str(\n# # p) + '_k' + str(k) + '.pkl'\n# # Y_ED, ts_scaled = pickle.load(open(file_name,'rb'))\n#\n# ## p=1\n# # file_name = 'D:/Master_Thesis/code_data/footfall_analysis_optimization_PCE/data/M'+str(M)+'_p'+str(p)+'_k'+str(k)+'_actualThickness_logUniform.pkl'\n# # Y_ED = pickle.load(open(file_name,'rb'))[7]\n# # ts_scaled = pickle.load(open(file_name,'rb'))[8]\n#\n# ## p=1, uniform sampling\n# file_name = 'D:/Master_Thesis/code_data/footfall_analysis_optimization_PCE/data/M41_p1_k2_uniformThickness.pkl'\n# Y_ED, ts_scaled = pickle.load(open(file_name,'rb'))\n\n# ## p=1,k=3 uniform sampling\n# file_name = 'D:/Master_Thesis/code_data/footfall_analysis_optimization_PCE/data/Y_t_M' + str(M) + '_p' + str(\n# p) + '_k' + str(k) + '_uniformThickness.pkl'\n# Y_ED, ts_scaled = pickle.load(open(file_name,'rb'))\n\n# ## p=1,k=2 uniform sampling,[0.01,0.3]\n# file_name = 'D:/Master_Thesis/code_data/footfall_analysis_optimization_PCE/data/Y_t_M' + str(M) + '_p' + str(\n# p) + '_k' + str(k) + '_uniformThickness_0.01_0.3.pkl'\n# Y_ED, ts_scaled = pickle.load(open(file_name,'rb'))\n\n## p=1,k=2 uniform sampling,l/d=15,[0.01,0.2]\nfile_name = 'D:/Master_Thesis/code_data/footfall_analysis_optimization_PCE/data/Y_t_M' + str(M) + '_p' + str(\n p) + '_k' + str(k) + '_uniformThickness_0.01_0.2_l2d15.pkl'\nY_ED, ts_scaled = pickle.load(open(file_name,'rb'))\n#\n# obtain degree index\nindex = fn.create_degreeIndex(M,p)\n\n### PCE in standard space\n# create Psi matrix, input is transferred to [-1,1]\nxi = (2 * ts_scaled - (bound_uni[0] + bound_uni[1])) / (bound_uni[1] - bound_uni[0])\nstart = time()\nPsi_std = fn.create_Psi(index, xi, 'legendre')\nstop = time()\nprint('time for Psi_std = '+str(stop-start)+' s')\n\n# calculate polynomial coefficients with lest square and recalculate\ny_alpha_LS_std = np.linalg.inv(np.transpose(Psi_std) @ Psi_std) @ np.transpose(Psi_std) @ Y_ED\nY_rec_LS_std = y_alpha_LS_std @ np.transpose(Psi_std)\n\n# # calculate polynomial coefficients with linear regression and recalculate\n# reg = LinearRegression()\n# reg.fit(Psi,Y_ED)\n# y_alpha_LR = reg.coef_\n# Y_rec_LR = reg.predict(Psi)\n\n### PCE in actual space\n# keep actual thickness\nstart = time()\nPsi_act = fn.create_Psi(index,ts_scaled,'normal')\nstop = time()\nprint('time for Psi_act = '+str(stop-start)+' s')\n# calculate polynomial coefficients with lest square and recalculate\ny_alpha_LS_act = np.linalg.inv(np.transpose(Psi_act)@Psi_act)@np.transpose(Psi_act)@Y_ED\nY_rec_LS_act = y_alpha_LS_act @ np.transpose(Psi_act)\n\n# # calculate polynomial coefficients with linear regression and recalculate\n# reg_act = LinearRegression()\n# reg_act.fit(Psi_act,Y_ED)\n# y_alpha_LR_act = reg_act.coef_\n# Y_rec_LR_act = reg_act.predict(Psi_act)\n\n\n### calculate response with new scaled data\nbound_log = [1/5,5]\nts_samp_new_k2 = fn.sampling('log_uniform', bound_log, M, n,M1=M1)\nareas = fn.get_areas()\nts_scaled_new_k2 = np.zeros((M, n))\nfor i in range(n):\n ts_scaled_new_k2[:,i] = fn.get_scaledThickness(areas, ts_samp_new_k2[:, i])\n\n# in standard space\nxi_new_k2 = (2 * ts_scaled_new_k2 - (bound_uni[0] + bound_uni[1])) / (bound_uni[1] - bound_uni[0])\nPsi_new_k2 = fn.create_Psi(index, xi_new_k2, 'legendre')\nY_new_k2_LS = y_alpha_LS_std @ np.transpose(Psi_new_k2)\n\n# in actual space\nPsi_new_k2_act = fn.create_Psi(index, ts_scaled_new_k2, 'normal')\nY_new_k2_LS_act = y_alpha_LS_act @ np.transpose(Psi_new_k2_act)\n# predict with coefficients from least square\n\n\n# predict with coefficients from linear regression\n\n\n\n\n# ### calculate response with more sampling data\n# k_new = 10\n# n_new_k10 = int(k_new*fact(M+p)/(fact(M)*fact(p)))\n#\n# ts_samp_new_k10 = fn.sampling('log_uniform', bound_log, M, n_new_k10,M1=M1)\n#\n# ts_scaled_new_k10 = np.zeros((M, n_new_k10))\n# for i in range(n_new_k10):\n# ts_scaled_new_k10[:,i] = fn.get_scaledThickness(areas, ts_samp_new_k10[:, i])\n#\n# xi_new_k10 = (2 * ts_scaled_new_k10 - (bound_uni[0] + bound_uni[1])) / (bound_uni[1] - bound_uni[0])\n# Psi_new_k10 = fn.create_Psi(index, xi_new_k10, 'legendre')\n#\n# # predict with coefficients from least square\n# Y_new_k10_LS = y_alpha_LS @ np.transpose(Psi_new_k10)\n#\n# # predict with coefficients from linear regression\n# Y_new_k10_LR = reg.predict(Psi_new_k10)\n\nprint('Y_ED=')\nprint(Y_ED)\nprint('y_alpha_LS_std=')\nprint(y_alpha_LS_std)\nprint('Y_rec_LS_std=')\nprint(Y_rec_LS_std)\nprint('y_alpha_LS_act=')\nprint(y_alpha_LS_act)\nprint('Y_rec_LS_act=')\nprint(Y_rec_LS_act)\n\nprint('Y_new_k2_LS=')\nprint(Y_new_k2_LS)\nprint('Y_new_k2_LS_act=')\nprint(Y_new_k2_LS_act)\n\n\n\nwith open ('D:/Master_Thesis/code_data/footfall_analysis_optimization_PCE/data/PCE_M'+str(M)+'_p'+str(p)+'_k'+str(k)+'_uni_0.01_0.2_l2d15.pkl','wb') as data:\n pickle.dump([y_alpha_LS_std, y_alpha_LS_act, index, bound_uni], data)\n # pickle.dump([M, p, k, bounds, P, n, Y_ED, ts_scaled, index, Psi, reg, y_alpha, Y_rec], data)\n","sub_path":"footfall_analysis_optimization_PCE/PCE_main_M41.py","file_name":"PCE_main_M41.py","file_ext":"py","file_size_in_byte":7272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"382293661","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n ImageConvert: convert png, gif image to jpeg image.\n create_image: use buf create image.\n\"\"\"\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from StringIO import StringIO\n\nfrom PIL import Image\n\n\nclass ImageConvert(object):\n\n @classmethod\n def _png_to_jpeg(cls, im):\n _im = create_image('JPEG', 'RGBA', im.size)\n _im.paste(im, im)\n _im = _im.convert('RGB')\n return _im\n\n @classmethod\n def _gif_to_jpeg(cls, im):\n _im = cls._gif_to_png(im)\n _im = cls._png_to_jpeg(_im)\n return _im\n\n @classmethod\n def _gif_to_png(cls, im):\n _im = create_image('PNG', 'RGBA', im.size)\n _im.paste(im)\n return _im\n\n @classmethod\n def convert(cls, im):\n if im.format == 'PNG' and im.mode == 'RGBA':\n im = cls._png_to_jpeg(im)\n elif im.format == 'GIF':\n im = cls._gif_to_jpeg(im)\n elif im.mode != 'RGB':\n im = im.convert('RGB')\n return im\n\n\ndef create_image(_format, *a, **kw):\n buf = StringIO()\n Image.new(*a, **kw).save(buf, _format)\n buf.seek(0)\n return Image.open(buf)\n","sub_path":"nobody/nobody/libs/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"365076862","text":"import gym\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom itertools import product\n\ndef random_episode(env):\n \"\"\" This is an example performing random actions on the environment\"\"\"\n while True:\n env.render()\n action = env.action_space.sample()\n print(\"do action: \", action)\n observation, reward, done, info = env.step(action)\n print(\"observation: \", observation)\n print(\"reward: \", reward)\n print(\"\")\n if done:\n break\n\n\ndef plot_V(Q, env, x, v):\n \"\"\" This is a helper function to plot the state values from the Q function\"\"\"\n fig = plt.figure()\n dims = Q.shape[:2]\n V = np.zeros(dims)\n for i in range(len(x)):\n for j in range(len(v)):\n V[i,j] = -np.min(Q[i,j,:])\n \n plt.imshow(V, origin='upper', \n extent=[0,dims[0],0,dims[1]], vmin=.0, vmax=.6, \n cmap=plt.cm.RdYlGn, interpolation='none')\n x_ = ['%.2f'%oi for oi in x]\n v_ = ['%.2f'%oi for oi in v]\n plt.xticks(np.arange(21), x_, rotation=75)\n plt.yticks(np.arange(21), v_)\n \n\ndef e_greedy(env, Q, s, epsilon):\n random = np.random.random_sample()\n if random <= epsilon:\n return np.random.choice(np.argwhere(Q[s[0], s[1],:]==np.max(Q[s[0], s[1],:])).reshape(-1))\n else:\n return np.random.randint(env.action_space.n)\n\n\ndef Q_lambda(env, alpha, gamma, lambda_, num_ep):\n x = np.arange(-0.6, 1.201, 0.09)\n v = np.arange(-0.07, 0.0701, 0.007)\n S = []\n for s in x:\n S_ = []\n for v_ in v:\n S_.append([s, v_])\n S.append(S_)\n S = np.array(S)\n Q = np.zeros((S.shape[0], S.shape[1], env.action_space.n))\n\n for episode in range(num_ep):\n #env.render()\n s = env.reset()\n index_x = (np.abs(x-s[0])).argmin()\n index_v = (np.abs(v-s[1])).argmin()\n z = np.zeros((S.shape[0], S.shape[1], env.action_space.n))\n a = e_greedy(env, Q, (index_x, index_v), 0.9) # 0, 1, 2\n done = False\n while not done:\n s_, r, done, _ = env.step(a)\n index_x = (np.abs(x-s[0])).argmin()\n index_v = (np.abs(v-s[1])).argmin()\n index_x_ = (np.abs(x-s_[0])).argmin()\n index_v_ = (np.abs(v-s_[1])).argmin()\n\n a_ = e_greedy(env, Q, (index_x_, index_v_), 0.9)\n a_max = e_greedy(env, Q, (index_x_, index_v_), 1)\n delta = r + (gamma * Q[index_x_, index_v_, a_max]) - Q[index_x, index_v, a]\n z[index_x, index_v, a] += 1\n for i in range(len(x)):\n for j in range(len(v)):\n for k in range(env.action_space.n):\n Q[i,j,k] += alpha * delta * z[i,j,k]\n if a_ == a_max:\n z[i,j,k] *= gamma*lambda_\n else:\n z[i,j,k] = 0\n s = s_\n a = a_\n if episode % 20 == 0:\n plot_V(Q, env, x, v)\n return Q\n\ndef sarsa_lambda_LFA(env, alpha, gamma, lambda_, epsilon, num_ep):\n x = np.arange(-0.6, 1.201, 0.09)\n v = np.arange(-0.07, 0.0701, 0.007)\n S = []\n for s in x:\n S_ = []\n for v_ in v:\n S_.append([[s, v_, 1]]*3)\n S.append(S_)\n S = np.array(S)\n w = np.zeros(S.shape)\n Q = np.zeros((len(x), len(v), env.action_space.n))\n\n for episode in range(num_ep):\n #env.render()\n z = np.zeros(S.shape)\n s = env.reset()\n index_x = (np.abs(x-s[0])).argmin()\n index_v = (np.abs(v-s[1])).argmin()\n a = e_greedy(env, Q, (index_x, index_v), 0.9) # 0, 1, 2\n F_a = S[index_x, index_v, a, :]\n done = False\n while not done:\n z[index_x, index_v, a, :] += 1 # accumulating traces\n s, r, done, _ = env.step(a)\n index_x = (np.abs(x-s[0])).argmin()\n index_v = (np.abs(v-s[1])).argmin()\n\n #a_ = e_greedy(env, Q, (index_x_, index_v_), 0.9)\n delta = r - np.sum(w[index_x, index_v, a, :])\n if not done:\n random = np.random.random_sample()\n if random <= epsilon:\n for i in range(env.action_space.n):\n F_a = S[index_x, index_v, i, :]\n Q[index_x, index_v, i] = np.sum(w[index_x, index_v, i, :])\n a = np.random.choice(np.argwhere(Q[index_x,index_v,:]==np.max(Q[index_x,index_v,:])).reshape(-1))\n else:\n a = np.random.randint(env.action_space.n)\n F_a = S[index_x, index_v, a, :]\n Q[index_x, index_v, a] = np.sum(w[index_x, index_v, a, :])\n delta += gamma * Q[index_x, index_v, a]\n w += alpha * delta * z\n z *= gamma * lambda_\n return Q\n\ndef main():\n env = gym.make('MountainCar-v0')\n env.reset()\n Q_lambda(env, 0.9, 0.9, 0.5, 1000)\n plt.show()\n #random_episode(env)\n env.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"ex07-fa/ex07-fa.py","file_name":"ex07-fa.py","file_ext":"py","file_size_in_byte":5013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"343716348","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport numpy as np\nimport gym\nfrom gym import spaces\nfrom gym.utils import seeding\nimport sys\nimport itertools\nimport bisect \nfrom scipy.stats import norm\nimport matplotlib.pyplot as plt\nimport random\nimport pickle\n\nclass StochStormyGridWorldEnv(gym.Env):\n '''Creates the Stochastic Windy GridWorld Environment\n NOISE_CASE = 1: the noise is a scalar added to the wind tiles, i.e,\n all wind tiles are changed by the same amount \n NOISE_CASE = 2: the noise is a vector added to the wind tiles, i.e,\n wind tiles are changed by different amounts.\n '''\n def __init__(self, GRID_HEIGHT=7, GRID_WIDTH=10,\n WIND = [0, 0, 0, 1, 1, 1, 2, 2, 1, 0], \n WIND_DIR = [0, 1, 2, 3],\n WIND_V = [0, 0, 1, 1, 1, 1, 0],\n START_CELL = (3, 0), GOAL_CELL = (3, 9),\n REWARD = -1, RANGE_RANDOM_WIND=1,\n PROB=[1./3., 1./3., 1./3.],\n PROB_WDIR = [0.5, 1./6., 1./6., 1./6.], \n NOISE_CASE = 1,\n SIMULATOR_SEED = 3323,\n GAMMA = 0.95):\n self.prng_simulator = np.random.RandomState(SIMULATOR_SEED) #Pseudorandom number generator\n self.grid_height = GRID_HEIGHT\n self.grid_width = GRID_WIDTH\n self.grid_dimensions = (self.grid_height, self.grid_width)\n \n self.wind = np.array(WIND)\n \n self.windv = np.array(WIND_V)\n self.wind_dir = np.array( WIND_DIR)\n \n self.realized_wind = self.wind\n self.start_cell = START_CELL\n self.goal_cell = GOAL_CELL \n self.start_state = self.dim2to1(START_CELL)\n self.goal_state = self.dim2to1(GOAL_CELL) \n self.reward = REWARD\n self.range_random_wind = RANGE_RANDOM_WIND\n self.w_range = np.arange(-self.range_random_wind, self.range_random_wind + 1 )\n \n \n\n \n self.nw = RANGE_RANDOM_WIND *2 +1\n self.nwd = self.wind_dir.shape[0]\n #probabilites\n self.probabilities = PROB #probability of wind strength\n self.prob_wd = PROB_WDIR #probability of wind direction\n \n\n \n self.w_prob = dict(zip(self.w_range, self.probabilities))\n self.action_space = spaces.Discrete(4)\n self.observation_space = spaces.Tuple((\n spaces.Discrete(self.grid_height),\n spaces.Discrete(self.grid_width)))\n self.seed()\n self.actions = { 'U':0, #up\n 'R':1, #right\n 'D':2, #down\n 'L':3 } #left\n self.nA = len(self.actions)\n self.nS = self.dim2to1((self.grid_height-1,self.grid_width-1)) + 1\n #self.num_wind_tiles = np.count_nonzero(self.wind)\n self.noise_case = NOISE_CASE\n self.noise = list(itertools.product(self.w_range, self.wind_dir, range(self.nS)))\n self.nE = len(self.noise) #RANGE_RANDOM_WIND *2 +1\n \n #prb = np.array(self.probabilities)[:,None] * np.array(self.prob_wd)\n p1=np.array(self.probabilities)\n p2=np.array(self.prob_wd)\n p3=np.ones(self.nS)/self.nS\n \n# x = np.arange(0, 70)\n# xU, xL = x + 0.5, x - 0.5 \n# prob = norm.cdf(xU, loc=35, scale = 10) - norm.cdf(xL, loc=35, scale = 10)\n# prob = prob / prob.sum() #normalize the probabilities so their sum is 1\n rainy_states=[22, 23, 24, 25, 26, 27, 32, 33, 34, 35, 36, 37, 42, 43, 44, 45, 46, 47 ]\n prob=np.zeros(70)\n prob[rainy_states]= 1./len(rainy_states)\n p3=prob\n A = [p1,p2,p3] # list of all input arrays\n self.p=np.multiply.reduce(np.ix_(*A)) \n self.pravel = self.p.ravel()\n self.P=[]\n #self.all_possible_wind_values = np.unique(self.w_range[:, None] + self.wind)\n # create transition function\n self.f = np.zeros((self.nS, self.nA, len(self.w_range), len(self.wind_dir) ), dtype=int)\n for s in range(self.nS):\n for wd in self.wind_dir: \n for w in (self.w_range + self.range_random_wind): \n # note that when w_range=[-1,0,1] then w_range + 1=[0,1,2] \n # so we can map w values to indices by adding 1 to the value\n if s == self.goal_state: \n self.f[s,self.actions['U'], w, wd] = self.goal_state\n self.f[s,self.actions['R'], w, wd] = self.goal_state \n self.f[s,self.actions['D'], w, wd] = self.goal_state\n self.f[s,self.actions['L'], w, wd] = self.goal_state \n else:\n i, j = self.dim1to2(s)\n # print(i,j)\n if wd == 0: # wind direction up \n if self.wind[j] != 0: \n wind = self.wind[j] + w - self.range_random_wind\n # print('wind=',wind)\n else: \n wind = 0\n self.f[s,self.actions['U'], w, wd] = self.dim2to1((min(max(i - 1 - wind, 0),self.grid_height - 1), j))\n self.f[s,self.actions['R'], w, wd] = self.dim2to1((min(max(i - wind, 0),self.grid_height - 1),\\\n min(j + 1, self.grid_width - 1)))\n self.f[s,self.actions['D'], w, wd] = self.dim2to1((max(min(i + 1 - wind, \\\n self.grid_height - 1), 0), j))\n self.f[s,self.actions['L'], w, wd] = self.dim2to1((min(max(i - wind, 0),self.grid_height - 1),\\\n max(j - 1, 0)))\n elif wd == 2: # wind direction down \n if self.wind[j] != 0: \n wind = self.wind[j] + w - self.range_random_wind\n # print('wind=',wind)\n else: \n wind = 0\n self.f[s,self.actions['U'], w, wd] = self.dim2to1((min(max(i - 1 + wind, 0),self.grid_height - 1), j))\n self.f[s,self.actions['R'], w, wd] = self.dim2to1((min(max(i + wind, 0),self.grid_height - 1),\\\n min(j + 1, self.grid_width - 1)))\n self.f[s,self.actions['D'], w, wd] = self.dim2to1((max(min(i + 1 + wind, \\\n self.grid_height - 1), 0), j))\n self.f[s,self.actions['L'], w, wd] = self.dim2to1((min(max(i + wind, 0),self.grid_height - 1),\\\n max(j - 1, 0)))\n elif wd == 3: # <== wind direction left\n if self.windv[i] != 0: \n wind = self.windv[i] + w - self.range_random_wind\n # print('wind=',wind)\n else: \n wind = 0\n self.f[s,self.actions['U'], w, wd] = self.dim2to1((min(max(i - 1 , 0),self.grid_height - 1), min(max(j- wind,0),self.grid_width - 1)))\n self.f[s,self.actions['R'], w, wd] = self.dim2to1((min(max(i , 0),self.grid_height - 1),\\\n min(max(j + 1 - wind,0), self.grid_width - 1)))\n self.f[s,self.actions['D'], w, wd] = self.dim2to1((max(min(i + 1 , \\\n self.grid_height - 1), 0), min(max(j - wind,0), self.grid_width - 1)))\n self.f[s,self.actions['L'], w, wd] = self.dim2to1((min(max(i , 0),self.grid_height - 1),\\\n min(max(j - 1 - wind, 0),self.grid_width - 1) ))\n elif wd == 1: # ==> wind direction right\n if self.windv[i] != 0: \n wind = self.windv[i] + w - self.range_random_wind\n # print('wind=',wind)\n else: \n wind = 0\n self.f[s,self.actions['U'], w, wd] = self.dim2to1((min(max(i - 1 , 0),self.grid_height - 1), min(max(j+ wind,0),self.grid_width - 1)))\n self.f[s,self.actions['R'], w, wd] = self.dim2to1((min(max(i , 0),self.grid_height - 1),\\\n min(max(j + 1 + wind,0), self.grid_width - 1)))\n self.f[s,self.actions['D'], w, wd] = self.dim2to1((max(min(i + 1 , \\\n self.grid_height - 1), 0), min(max(j + wind,0), self.grid_width - 1)))\n self.f[s,self.actions['L'], w, wd] = self.dim2to1((min(max(i , 0),self.grid_height - 1),\\\n min(max(j - 1 + wind, 0),self.grid_width - 1) )) \n \n \n # create transition probabilities \n self.P=np.zeros((self.nS,self.nA,self.nS)) \n for s in range(self.nS):\n for a in range(self.nA):\n ns =[]\n prob =[]\n for w in (self.w_range + self.range_random_wind):\n for wd in self.wind_dir:\n ns.append(self.f[s,a,w, wd])\n prob.append(self.probabilities[w]*self.prob_wd[wd] )\n out_array = [np.where(ns == element)[0].tolist() for element in np.unique(ns)] \n prob=np.array(prob)\n probb = [sum(prob[i]) for i in out_array]\n self.P[s,a][np.unique(ns)]= probb\n# # absorption formulation gamma\n self.gamma = GAMMA\n \n X= self.grid_height\n Y= self.grid_width\n neighbors_func = lambda x, y : [(x2, y2) for x2 in range(x-1, x+2)\n for y2 in range(y-1, y+2)\n if (-1 < x < X and\n -1 < y < Y and\n (0 <= x2 < X) and\n (0 <= y2 < Y))]\n \n \n \n self.trans = np.empty((self.nS, self.nA), dtype=object)\n self.r=np.zeros((self.nS,self.nA, self.nw, self.nwd, self.nS))\n for s in range(self.nS):\n for a in range(self.nA):\n t=[]\n for w in (self.w_range + self.range_random_wind):\n for wd in self.wind_dir:\n if self.P[s,a,self.f[s,a,w,wd]] != 0:\n if self.f[s,a,w,wd] == self.goal_state:\n r = 0.0\n self.r[s,a,w, wd,:] = r\n d = 1 #done\n else:\n for loc in rainy_states:#range(self.nS): \n i,j=self.dim1to2(loc)\n neighbors = np.array(neighbors_func(i,j))\n neighbors= self.dim2to1([neighbors[:,0], neighbors[:,1]])\n if self.f[s,a,w,wd] in neighbors:\n r = -10.0 ################################## puddle reward\n else:\n r = -1.0\n self.r[s,a,w,wd, loc] = r\n d = 0\n t.append([self.P[s,a,self.f[s,a,w,wd]],self.f[s,a,w,wd],r, d])\n self.trans[s,a]=np.unique(np.array(t), axis=0) \n \n self.mean_r = np.zeros((self.nS,self.nA))\n \n \n for s in range(self.nS):\n for a in range(self.nA):\n self.mean_r[s,a]=np.sum(self.p*self.r[s,a,:,:,:])\n Rmax = max(np.max(self.r), abs(np.min(self.r))) \n self.r_max = Rmax #np.max(self.r)#np.max(self.mean_r) \n self.r_min =-Rmax #np.min(self.r)#np.min(self.mean_r) \n \n \n def f(self, s, a, w, wd):\n return self.f[s, a, w + self.range_random_wind, wd]\n \n\n \n def simulate_sample_path(self):\n '''TODO'''\n tau = self.prng_simulator.geometric(p=1-self.gamma, size=1)[0] \n sample_path = self.prng_simulator.choice(self.w_range, tau, p=self.probabilities)\n return sample_path\n \n \n \n def dim2to1(self, cell):\n '''Transforms the 2 dim position in a grid world to 1 state'''\n return np.ravel_multi_index(cell, self.grid_dimensions)\n \n def dim1to2(self, state):\n '''Transforms the state in a grid world back to its 2 dim cell'''\n return np.unravel_index(state, self.grid_dimensions)\n \n\n def _virtual_step_f(self, state, action, force_noise=None):\n '''Set up destinations for each action in each state only works with case 1\n and use the lookup table self.f. Much faster than _virtual_step.\n '''\n if force_noise is None:\n # case 1 where all wind tiles are affected by the same noise scalar, \n # noise1 is a scalar value added to wind\n noise_idx = self.np_random.choice(self.nE, 1, p=self.pravel)[0] \n noise = self.noise[noise_idx]\n #noise = random.choice(self.noise, 1, p=self.pravel)\n else: \n noise = force_noise \n #print('noise=', noise)\n wind = np.copy(self.wind)\n wind[np.where( wind > 0 )] += noise[0] \n destination = self.f[state, action, noise[0] + self.range_random_wind, noise[1]]\n #if destination == self.goal_state:\n if state ==self.goal_state and destination == self.goal_state:\n #reward = 0.0 ########################################### 0 before\n isdone = True\n elif state !=self.goal_state and destination == self.goal_state:\n #reward = 0.0\n isdone = True\n else:\n #reward = -1.0\n isdone = False\n reward = self.r[state, action, noise[0] + self.range_random_wind, noise[1], noise[2]] \n return destination, reward, isdone, wind, noise\n \n def step(self, action, force_noise=None):\n \"\"\"\n Parameters\n ----------\n action : 0 = Up, 1 = Right, 2 = Down, 3 = Left\n\n Returns\n -------\n ob, reward, episode_over, info : tuple\n ob (object) :\n Agent current position in the grid.\n reward (float) :\n Reward is -1 at every step except at goal state.\n episode_over (bool) :\n True if the agent reaches the goal, False otherwise.\n info (dict) :\n Contains the realized noise that is added to the wind in each \n step. However, official evaluations of your agent are not \n allowed to use this for learning.\n \"\"\"\n assert self.action_space.contains(action)\n self.observation, reward, isdone, wind, noise = self._virtual_step_f(self.observation, action, force_noise)\n self.realized_wind = wind\n # noise = (wind_value, wind_dir, rain_location)\n return self.observation, reward, isdone, {'noise':noise}\n \n def reset(self):\n ''' resets the agent position back to the starting position'''\n self.observation = self.start_state\n self.realized_wind = self.wind\n return self.observation \n\n def render(self, mode='human', close=False):\n ''' Renders the environment. Code borrowed and them modified \n from https://github.com/dennybritz/reinforcement-learning'''\n if close:\n return\n\n outfile = StringIO() if mode == 'ansi' else sys.stdout\n\n for s in range(self.nS):\n position = self.dim1to2(s)\n # print(self.s)\n if self.observation == s:\n output = \" x \"\n elif position == self.goal_cell:\n output = \" T \"\n else:\n output = \" o \"\n\n if position[1] == 0:\n output = output.lstrip()\n if position[1] == self.grid_dimensions[1] - 1:\n output = output.rstrip()\n output += \"\\n\"\n\n outfile.write(output)\n for i in range(len(self.realized_wind)):\n output =' ' + str(self.realized_wind[i]) + ' '\n if i == 0:\n output = output.lstrip()\n if i == len(self.realized_wind) - 1:\n output = output.rstrip()\n output += \"\\n\"\n \n outfile.write(output)\n \n outfile.write(\"\\n\")\n \n def seed(self, seed=None):\n ''' sets the seed for the envirnment'''\n self.np_random, seed = seeding.np_random(seed)\n #random.seed(seed)\n return [seed]\n \n\ndef QIteration(env, tol=1e-12, max_iters=1e10):\n '''Q-iteration, finds Qstar'''\n Q = np.zeros((env.nS, env.nA)) \n new_Q=np.copy(Q)\n iters = 0\n while True:\n for state in range(env.nS):\n for action in range(env.nA):\n val = 0\n for (prob, newState, reward, isterminal) in env.trans[state,action]:\n newState = int(newState)\n if not isterminal:\n val += prob * (reward + env.gamma * np.max(Q[newState,:]))\n else: \n val += prob * reward \n new_Q[state, action] = val\n if np.sum(np.abs(new_Q - Q)) < tol:\n Q = new_Q.copy()\n break \n Q = new_Q.copy()\n iters += 1 \n return iters, Q\n \nif __name__=='__main__':\n env = StochStormyGridWorldEnv()\n env.reset()\n iters, Qstar = QIteration(env)\n with open(\"Qstar.pkl\", 'wb') as f:\n pickle.dump(Qstar, f,protocol=2) \n","sub_path":"src/SG/stoch_stormy_gridworld.py","file_name":"stoch_stormy_gridworld.py","file_ext":"py","file_size_in_byte":18367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"543555968","text":"# Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# 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\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\nfrom __future__ import absolute_import\n\nfrom sagemaker.amazon.amazon_estimator import AmazonAlgorithmEstimatorBase, registry\nfrom sagemaker.amazon.common import numpy_to_record_serializer, record_deserializer\nfrom sagemaker.amazon.hyperparameter import Hyperparameter as hp # noqa\nfrom sagemaker.amazon.validation import gt\nfrom sagemaker.predictor import RealTimePredictor\nfrom sagemaker.model import Model\nfrom sagemaker.session import Session\nfrom sagemaker.vpc_utils import VPC_CONFIG_DEFAULT\n\n\nclass LDA(AmazonAlgorithmEstimatorBase):\n\n repo_name = 'lda'\n repo_version = 1\n\n num_topics = hp('num_topics', gt(0), 'An integer greater than zero', int)\n alpha0 = hp('alpha0', gt(0), 'A positive float', float)\n max_restarts = hp('max_restarts', gt(0), 'An integer greater than zero', int)\n max_iterations = hp('max_iterations', gt(0), 'An integer greater than zero', int)\n tol = hp('tol', gt(0), 'A positive float', float)\n\n def __init__(self, role, train_instance_type, num_topics,\n alpha0=None, max_restarts=None, max_iterations=None, tol=None, **kwargs):\n \"\"\"Latent Dirichlet Allocation (LDA) is :class:`Estimator` used for unsupervised learning.\n\n Amazon SageMaker Latent Dirichlet Allocation is an unsupervised learning algorithm that attempts to describe\n a set of observations as a mixture of distinct categories. LDA is most commonly used to discover\n a user-specified number of topics shared by documents within a text corpus.\n Here each observation is a document, the features are the presence (or occurrence count) of each word, and\n the categories are the topics.\n\n This Estimator may be fit via calls to\n :meth:`~sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase.fit`. It requires Amazon\n :class:`~sagemaker.amazon.record_pb2.Record` protobuf serialized data to be stored in S3.\n There is an utility :meth:`~sagemaker.amazon.amazon_estimator.AmazonAlgorithmEstimatorBase.record_set` that\n can be used to upload data to S3 and creates :class:`~sagemaker.amazon.amazon_estimator.RecordSet` to be passed\n to the `fit` call.\n\n To learn more about the Amazon protobuf Record class and how to prepare bulk data in this format, please\n consult AWS technical documentation: https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-training.html\n\n After this Estimator is fit, model data is stored in S3. The model may be deployed to an Amazon SageMaker\n Endpoint by invoking :meth:`~sagemaker.amazon.estimator.EstimatorBase.deploy`. As well as deploying an Endpoint,\n deploy returns a :class:`~sagemaker.amazon.lda.LDAPredictor` object that can be used\n for inference calls using the trained model hosted in the SageMaker Endpoint.\n\n LDA Estimators can be configured by setting hyperparameters. The available hyperparameters for\n LDA are documented below.\n\n For further information on the AWS LDA algorithm,\n please consult AWS technical documentation: https://docs.aws.amazon.com/sagemaker/latest/dg/lda.html\n\n Args:\n role (str): An AWS IAM role (either name or full ARN). The Amazon SageMaker training jobs and\n APIs that create Amazon SageMaker endpoints use this role to access\n training data and model artifacts. After the endpoint is created,\n the inference code might use the IAM role, if accessing AWS resource.\n train_instance_type (str): Type of EC2 instance to use for training, for example, 'ml.c4.xlarge'.\n num_topics (int): The number of topics for LDA to find within the data.\n alpha0 (float): Optional. Initial guess for the concentration parameter\n max_restarts (int): Optional. The number of restarts to perform during the Alternating Least Squares (ALS)\n spectral decomposition phase of the algorithm.\n max_iterations (int): Optional. The maximum number of iterations to perform during the\n ALS phase of the algorithm.\n tol (float): Optional. Target error tolerance for the ALS phase of the algorithm.\n **kwargs: base class keyword argument values.\n \"\"\"\n # this algorithm only supports single instance training\n if kwargs.pop('train_instance_count', 1) != 1:\n print('LDA only supports single instance training. Defaulting to 1 {}.'.format(train_instance_type))\n\n super(LDA, self).__init__(role, 1, train_instance_type, **kwargs)\n self.num_topics = num_topics\n self.alpha0 = alpha0\n self.max_restarts = max_restarts\n self.max_iterations = max_iterations\n self.tol = tol\n\n def create_model(self, vpc_config_override=VPC_CONFIG_DEFAULT):\n \"\"\"Return a :class:`~sagemaker.amazon.LDAModel` referencing the latest\n s3 model data produced by this Estimator.\n\n Args:\n vpc_config_override (dict[str, list[str]]): Optional override for VpcConfig set on the model.\n Default: use subnets and security groups from this Estimator.\n * 'Subnets' (list[str]): List of subnet ids.\n * 'SecurityGroupIds' (list[str]): List of security group ids.\n \"\"\"\n return LDAModel(self.model_data, self.role, sagemaker_session=self.sagemaker_session,\n vpc_config=self.get_vpc_config(vpc_config_override))\n\n def _prepare_for_training(self, records, mini_batch_size, job_name=None):\n # mini_batch_size is required, prevent explicit calls with None\n if mini_batch_size is None:\n raise ValueError(\"mini_batch_size must be set\")\n\n super(LDA, self)._prepare_for_training(records, mini_batch_size=mini_batch_size, job_name=job_name)\n\n\nclass LDAPredictor(RealTimePredictor):\n \"\"\"Transforms input vectors to lower-dimesional representations.\n\n The implementation of :meth:`~sagemaker.predictor.RealTimePredictor.predict` in this\n `RealTimePredictor` requires a numpy ``ndarray`` as input. The array should contain the\n same number of columns as the feature-dimension of the data used to fit the model this\n Predictor performs inference on.\n\n :meth:`predict()` returns a list of :class:`~sagemaker.amazon.record_pb2.Record` objects, one\n for each row in the input ``ndarray``. The lower dimension vector result is stored in the ``projection``\n key of the ``Record.label`` field.\"\"\"\n\n def __init__(self, endpoint, sagemaker_session=None):\n super(LDAPredictor, self).__init__(endpoint, sagemaker_session, serializer=numpy_to_record_serializer(),\n deserializer=record_deserializer())\n\n\nclass LDAModel(Model):\n \"\"\"Reference LDA s3 model data. Calling :meth:`~sagemaker.model.Model.deploy` creates an Endpoint and return\n a Predictor that transforms vectors to a lower-dimensional representation.\"\"\"\n\n def __init__(self, model_data, role, sagemaker_session=None, **kwargs):\n sagemaker_session = sagemaker_session or Session()\n repo = '{}:{}'.format(LDA.repo_name, LDA.repo_version)\n image = '{}/{}'.format(registry(sagemaker_session.boto_session.region_name, LDA.repo_name), repo)\n super(LDAModel, self).__init__(model_data, image, role, predictor_cls=LDAPredictor,\n sagemaker_session=sagemaker_session, **kwargs)\n","sub_path":"source/sagemaker-python-sdk/src/sagemaker/amazon/lda.py","file_name":"lda.py","file_ext":"py","file_size_in_byte":8010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"456806595","text":"from django.shortcuts import render\nfrom .models import xss,ccpa\n# Create your views here.\nfrom django.http import HttpResponse, Http404\n\ndef index(request):\n return HttpResponse(\"不要说话\")\n\ndef detail(request,num,num2):\n return HttpResponse(\"detail-%s-%s\"%(num,num2))\n\n\ndef printLogin(request):\n\n print('request',request)\n if request.method == \"POST\":\n name = request.POST.get('name')\n icc = request.POST.get('icc')\n card_no = request.POST.get('card_no')\n qry = xss.objects.filter(name=name,icc=icc,status='通过')\n print('qry',qry)\n for q in qry:\n if q.card_no == card_no:\n return render(request, 'print_card.html', {\"qry\": q,'verbose_name':'薪税师项目'})\n\n\n qry = ccpa.objects.filter(name=name,icc=icc,status='通过')\n print('qry',qry)\n for q in qry:\n if q.card_no == card_no:\n kskm = q.kskm.all()\n return render(request, 'print_card.html', {\"qry\": q,'verbose_name':'CCPA项目','kskm':kskm})\n\n return render(request, 'stulogin.html', {\"error\": '无信息,请核实'})\n\n else:\n return render(request, 'stulogin.html')\n #testResult_surnfu\n\n # qry = xss.objects.all()\n # print('qry',qry,request)\n # return render(request, 'stulogin.html', {\"qry\": qry})","sub_path":"demo_app/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"107913305","text":"import csv\r\nimport docx\r\nfrom docx import Document\r\n\r\nnames = []\r\nwith open('export.csv') as csv_file:\r\n csv_reader = csv.reader(csv_file, delimiter=',')\r\n for row in csv_reader:\r\n names.append (row[1] + \" \" + row[2])\r\n\r\nrow = 0;\r\ncol = 0;\r\ndocument = Document()\r\ntable = document.add_table (rows = 1, cols = 3)\r\n\r\nfor i in range (1,len(names),2): \r\n row = table.add_row().cells\r\n name1 = names [i]\r\n name2 = names [i+1]\r\n row[0].text = name1 + \"\\nHouse of Commons \\nOttawa, Ontario \\nCanada \\nK1A 0A6 \" \r\n row[2].text = name2 + \"\\nHouse of Commons \\nOttawa, Ontario \\nCanada \\nK1A 0A6 \" \r\n\r\ndocument.save('labels_template.docx')\r\n","sub_path":"label_generator.py","file_name":"label_generator.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"535494783","text":"\"\"\"\n자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.\n\n- 1부터 N까지 자연수 중에서 중복 없이 M개를 고른 수열\n- 고른 수열은 오름차순이어야 한다.\n\"\"\"\n\nimport itertools as it\n\nn, m = map(int, input().split())\nli = [i for i in range(1, n+1)]\nc_li = list(it.combinations(li, m))\n\nfor each_tuple in c_li:\n for i in each_tuple:\n print(i, end=\" \")\n print()","sub_path":"n_and_m/15650.py","file_name":"15650.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"9364215","text":"import torch\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom collections import OrderedDict\n# Local imports\nfrom isonet.models import *\nfrom isonet.models.resnet import BasicBlock\n\n# Taken from\n# The Singular Values of Convolutional Layers, Sedghi et al., ICLR 2019\n# https://arxiv.org/pdf/1805.10408.pdf\ndef singular_values(kernel, input_shape):\n transforms = np.fft.fft2(kernel, input_shape, axes=[0, 1])\n return np.linalg.svd(transforms, compute_uv=False)\n\n\ndef conv_lipschitz(conv_layer, input_shape):\n kernel = conv_layer.weight.permute(2, 3, 0, 1).cpu().detach().numpy()\n # For the input shape, say [3, 32, 32] just pass [32, 32]\n sing_vals = singular_values(kernel, input_shape[1:])\n lip_const = sing_vals.max()\n\n rand_input = torch.randn((1,*input_shape), device=conv_layer.weight.device)\n output_shape = list(conv_layer(rand_input).shape[1:])\n return lip_const, output_shape\n\n\ndef resblock_lipschitz(block, input_shape):\n inn_consts = OrderedDict()\n # Conv1\n lip_const, output_shape = conv_lipschitz(block.f.a, input_shape)\n inn_consts.update({ 'l_conv1' : lip_const })\n # Conv2\n lip_const, output_shape = conv_lipschitz(block.f.b, output_shape)\n inn_consts.update({ 'l_conv2' : lip_const })\n # Create DataFrame for printint individual Lipschitz constants\n df = pd.DataFrame({\n 'layer_name' : list(inn_consts.keys()), \n 'lipschitz_constant' : list(inn_consts.values())\n })\n print('Inner Lipschitz constant of the block:\\n', df.to_string(index=False))\n return inn_consts, output_shape\n\n\ndef basicblock_lipschitz(block, input_shape):\n inn_consts = OrderedDict()\n # Conv1\n lip_const, output_shape = conv_lipschitz(block.conv1, input_shape)\n inn_consts.update({ 'l_conv1' : lip_const })\n # BatchNorm1\n inn_consts.update({ 'l_bn1' : bn_lipschitz(block.bn1) })\n # Conv2\n lip_const, output_shape = conv_lipschitz(block.conv2, output_shape)\n inn_consts.update({ 'l_conv2' : lip_const })\n # BatchNorm2\n inn_consts.update({ 'l_bn2' : bn_lipschitz(block.bn2) })\n # Compute 'total' Lipschitz constant up until now\n inn_consts.update({ 'before_shortcut' : np.prod( list(inn_consts.values()) ) })\n # If there is a short cut there also a residual connection!\n if len(block.shortcut) != 0:\n lip_const, output_shape = conv_lipschitz(block.shortcut[0], input_shape)\n inn_consts.update({ 'l_shortcut_conv1' : lip_const })\n\n inn_consts.update({ 'l_shortcut_bn1' : bn_lipschitz(block.shortcut[1]) })\n # for residual connection\n shortcut_lip = inn_consts['l_shortcut_conv1'] * inn_consts['l_shortcut_bn1']\n\n else:\n # no residual connection\n shortcut_lip = 0\n\n inn_consts.update({ 'after_shortcut' : inn_consts['before_shortcut'] + shortcut_lip } )\n # Create DataFrame for printint individual Lipschitz constants\n df = pd.DataFrame({\n 'layer_name' : list(inn_consts.keys()), \n 'lipschitz_constant' : list(inn_consts.values())\n })\n print('Inner Lipschitz constant of the block:\\n', df.to_string(index=False))\n return inn_consts, output_shape\n\n'''\nLipschitz constant for average pooling. Taken from Section 2.3.1 of\nhttps://www.sam.math.ethz.ch/sam_reports/reports_final/reports2016/2016-29_fp.pdf\n'''\ndef avg_pool_lipschitz(pool_layer, input_shape):\n n_pool_elements = input_shape[1] * input_shape[2]\n lip_const = n_pool_elements ** (-1/2)\n\n rand_input = torch.randn((1,*input_shape))\n output_shape = list(pool_layer(rand_input).shape[1:])\n return lip_const, output_shape\n\n\ndef linear_lipschitz(linear_layer, shape):\n weight = linear_layer.weight.cpu().detach().numpy()\n sing_vals = np.linalg.svd(weight, compute_uv=False)\n lip_const = max(sing_vals)\n\n rand_input = torch.randn((1,*shape), device=linear_layer.weight.device)\n output_shape = list(linear_layer(rand_input).shape[1:])\n return lip_const, output_shape\n\n# Based on \n# Lipschitz Continuous Neural Networks, Gouk et al., 2018\n# https://arxiv.org/pdf/1804.04368.pdf\ndef bn_lipschitz(bn_layer):\n gamma = bn_layer.weight.cpu().detach().numpy()\n var = bn_layer.running_var.cpu().detach().numpy()\n sqrt_var = np.sqrt(var)\n quot = np.abs(gamma / sqrt_var)\n lip_const = quot.max()\n return lip_const\n\n\ndef resnet18_lipschitz(model, input_shape):\n # Starting\n layers = OrderedDict()\n layers['conv1'] = model.conv1\n layers['bn'] = model.bn1\n # Layer 1\n layers['layer1.basic_block1'] = list(model.layer1.named_children())[0][1]\n layers['layer1.basic_block2'] = list(model.layer1.named_children())[1][1]\n # Layer 2\n layers['layer2.basic_block1'] = list(model.layer2.named_children())[0][1]\n layers['layer2.basic_block2'] = list(model.layer2.named_children())[1][1]\n # Layer 3\n layers['layer3.basic_block1'] = list(model.layer3.named_children())[0][1]\n layers['layer3.basic_block2'] = list(model.layer3.named_children())[1][1]\n # Layer 4\n layers['layer4.basic_block1'] = list(model.layer4.named_children())[0][1]\n layers['layer4.basic_block2'] = list(model.layer4.named_children())[1][1]\n # Linear\n layers['linear'] = model.linear\n\n lips_constants = OrderedDict()\n shape = input_shape\n print('Computing Lipschitz constant of each layer...')\n for idx, (layer_name, layer) in enumerate(layers.items()):\n print(50 * '-')\n print(f'Layer #{idx}: \"{layer_name}\". Inp. shape: {shape}. Layer is', end=' ')\n if isinstance(layer, nn.Conv2d):\n print('Convolution.', end=' ')\n lip_const, shape = conv_lipschitz(layer, shape)\n elif isinstance(layer, nn.BatchNorm2d):\n print('BatchNorm.', end=' ') # shape doesn't change\n lip_const = bn_lipschitz(layer)\n elif isinstance(layer, BasicBlock):\n print('BasicBlock.', end=' ')\n inn_consts, shape = basicblock_lipschitz(layer, shape)\n lip_const = inn_consts['after_shortcut']\n elif isinstance(layer, nn.Linear):\n print('Linear.', end=' ')\n # In ResNet18 there's only one Linear layer: before the output.\n # Before passing the feature, there's an average pooling with a kernel\n # of size equal to that of the spatial dimensions\n shape = shape[:1]\n lip_const, shape = linear_lipschitz(layer, shape)\n\n\n print(f'Output shape: {shape}')\n lips_constants[layer_name] = lip_const\n\n # See individual constants:\n df = pd.DataFrame({\n 'layer_name' : list(lips_constants.keys()), \n 'lipschitz_constant' : list(lips_constants.values())\n })\n print('\\nAll Lipschitz constants: \\n', df.to_string(index=False))\n\n tot_lipschitz = np.prod(list(lips_constants.values()))\n print(f'\\n>> Total Lipschitz constant of the network: {tot_lipschitz:4.3f}')\n return tot_lipschitz\n\n\ndef isonet18_lipschitz(model, input_shape, with_linear=False, with_pool=True):\n # Starting\n layers = OrderedDict()\n layers['stem'] = model.stem.conv # stem has conv, relu and maxpool\n # Stage 1. Blocks have conv, relu, conv, relu\n layers['stage1.block1'] = model.s1.b1\n layers['stage1.block2'] = model.s1.b2\n # Stage 2\n layers['stage2.block1'] = model.s2.b1\n layers['stage2.block2'] = model.s2.b2\n # Stage 3\n layers['stage3.block1'] = model.s3.b1\n layers['stage3.block2'] = model.s3.b2\n # Stage 4\n try:\n layers['stage4.block1'] = model.s4.b1\n layers['stage4.block2'] = model.s4.b2\n except:\n print('layer 4 not found')\n # Linear. The head has avgpool, dropout and fc\n if with_pool:\n layers['avg_pool'] = model.head.avg_pool\n if with_linear:\n layers['linear'] = model.head.fc\n\n lips_constants = OrderedDict()\n shape = input_shape\n print('Computing Lipschitz constant of each layer...')\n for idx, (layer_name, layer) in enumerate(layers.items()):\n print(50 * '-')\n print(f'Layer #{idx}: \"{layer_name}\". Inp. shape: {shape}. Layer is', end=' ')\n if isinstance(layer, nn.Conv2d):\n print('Convolution.', end=' ')\n lip_const, shape = conv_lipschitz(layer, shape)\n elif isinstance(layer, ResBlock):\n print('ResBlock.', end=' ')\n inn_consts, shape = resblock_lipschitz(layer, shape)\n lip_const = inn_consts['l_conv1'] * inn_consts['l_conv2']\n elif isinstance(layer, nn.AdaptiveAvgPool2d):\n lip_const, shape = avg_pool_lipschitz(layer, shape)\n elif isinstance(layer, nn.Linear):\n print('Linear.', end=' ')\n # In ResNet18 there's only one Linear layer: before the output.\n # Before passing the feature, there's an average pooling with a kernel\n # of size equal to that of the spatial dimensions\n shape = shape[:1]\n lip_const, shape = linear_lipschitz(layer, shape)\n\n print(f'Output shape: {shape}')\n lips_constants[layer_name] = lip_const\n\n # See individual constants:\n df = pd.DataFrame({\n 'layer_name' : list(lips_constants.keys()), \n 'lipschitz_constant' : list(lips_constants.values())\n })\n print('\\nAll Lipschitz constants: \\n', df.to_string(index=False))\n\n tot_lipschitz = np.prod(list(lips_constants.values()))\n print(f'\\n>> Total Lipschitz constant of the network: {tot_lipschitz:4.3f}')\n return tot_lipschitz","sub_path":"isonet/utils/lips_utils.py","file_name":"lips_utils.py","file_ext":"py","file_size_in_byte":9552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"10682308","text":"#!/usr/bin/env python3\n\n##############################################################################\n# #\n# DEVELOPED BY: Chris Clement (K7CTC) #\n# VERSION: v1.2 #\n# DESCRIPTION: This utility was written for use with the Ronoth LoStik #\n# LoRa transceiver. It is intended to be run on Linux but #\n# can be adapted for Windows with some modification. The #\n# utility connects to the LoStik via its serial interface #\n# and writes all desired LoRa configuration parameters to #\n# the device. The device will generally respond with 'ok' #\n# when a parameter is successully written. #\n# #\n# #\n# INFORMATION: Ronoth LoStik does not retain radio settings between #\n# power cycles. #\n# #\n##############################################################################\n\n#import required modules\nimport argparse\nimport serial\nimport time\nimport sys\nimport pathlib\nimport os\n\n#start with a clear terminal window\nos.system('clear')\n\n#establish and parse command line arguments\nparser = argparse.ArgumentParser(description='Ronoth LoStik Utility: Set Configuration', epilog='Created by K7CTC. This utility will write specified LoRa settings to the LoStik device.')\nparser.add_argument('-p', '--port', help='LoStik serial port descriptor (default: /dev/ttyUSB0)', default='/dev/ttyUSB0')\nargs = parser.parse_args()\n\n##### BEGIN LOSTIK STARTUP #####\n\n#check to see if the port descriptor path exists (determines if device is connected on linux systems)\nlostik_path = pathlib.Path(args.port)\ntry:\n print('Looking for LoStik...\\r', end='')\n lostik_abs_path = lostik_path.resolve(strict=True)\nexcept FileNotFoundError:\n print('Looking for LoStik... FAIL!')\n print('ERROR: LoStik serial port descriptor not found!')\n print('HELP: Check serial port descriptor and/or device connection.')\n print('Unable to proceed, now exiting!')\n sys.exit(1)\nelse:\n print('Looking for LoStik... DONE!')\n\n#connect to lostik\ntry:\n print('Connecting to LoStik...\\r', end='')\n lostik = serial.Serial(args.port, baudrate=57600, timeout=1)\nexcept:\n print('Connecting to LoStik... FAIL!')\n print('HELP: Check port permissions. Current user must be in \"dialout\" group.')\n print('Unable to proceed, now exiting!')\n sys.exit(1)\n#at this point we're already connected, but we can call the is_open method just to be sure\nelse:\n if lostik.is_open == True:\n print('Connecting to LoStik... DONE!')\n elif lostik.is_open == False:\n print('Connecting to LoStik... FAIL!')\n print('HELP: Check port permissions. Current user must be in \"dialout\" group.')\n print('Unable to proceed, now exiting!')\n sys.exit(1)\n\n#make sure both LEDs are off before continuing\nrx_led_off = False\ntx_led_off = False\nprint('Checking status LEDs...\\r', end='')\nlostik.write(b'sys set pindig GPIO10 0\\r\\n') #GPIO10 is the blue rx led\nif lostik.readline().decode('ASCII').rstrip() == 'ok':\n rx_led_off = True\nlostik.write(b'sys set pindig GPIO11 0\\r\\n') #GPIO11 is the red tx led\nif lostik.readline().decode('ASCII').rstrip() == 'ok':\n tx_led_off = True\nif rx_led_off == True and tx_led_off == True:\n print('Checking status LEDs... DONE!')\nelse:\n print('Checking status LEDs...FAIL!')\n print('ERROR: Error communicating with LoStik.')\n print('Unable to proceed, now exiting!')\n sys.exit(1)\n\n#pause mac (LoRaWAN) as this is required to access the radio directly\nprint('Pausing LoRaWAN protocol stack...\\r', end='')\nlostik.write(b'mac pause\\r\\n')\nif lostik.readline().decode('ASCII').rstrip() == '4294967245':\n print('Pausing LoRaWAN protocol stack... DONE!\\n')\nelse:\n print('Pausing LoRaWAN protocol stack...FAIL!')\n print('ERROR: Error communicating with LoStik.')\n print('Unable to proceed, now exiting!')\n sys.exit(1)\n\n##### END LOSTIK STARTUP #####\n\n##### BEGIN LOSTIK FUNCTIONS #####\n\n#function for controlling LEDS\ndef led_control(led, state):\n if led == 'rx':\n if state == 'off':\n lostik.write(b'sys set pindig GPIO10 0\\r\\n') #GPIO10 is the blue rx led\n if lostik.readline().decode('ASCII').rstrip() == 'ok':\n return True\n else:\n return False\n elif state == 'on':\n lostik.write(b'sys set pindig GPIO10 1\\r\\n') #GPIO10 is the blue rx led\n if lostik.readline().decode('ASCII').rstrip() == 'ok':\n return True\n else:\n return False\n elif led == 'tx':\n if state == 'off':\n lostik.write(b'sys set pindig GPIO11 0\\r\\n') #GPIO11 is the red tx led\n if lostik.readline().decode('ASCII').rstrip() == 'ok':\n return True\n else:\n return False\n elif state == 'on':\n lostik.write(b'sys set pindig GPIO11 1\\r\\n') #GPIO11 is the red tx led\n if lostik.readline().decode('ASCII').rstrip() == 'ok':\n return True\n else:\n return False\n else:\n return False\n\n##### END LOSTIK FUNCTIONS #####\n\n#settings to be written to LoStik\n#Modulation Mode (default=lora)\nset_mod = b'lora' #this exists just in case the radio was mistakenly set to FSK somehow\n#Frequency (default=923300000)\nset_freq = b'923300000' #value range: 902000000 to 928000000\n#Transmit Power (default=2)\nset_pwr = b'2' #value range: 2 to 20\n#Spreading Factor (default=sf12)\nset_sf = b'sf12' #values: sf7, sf8, sf9, sf10, sf11, sf12\n#CRC Header (default=on)\nset_crc = b'on' #values: on, off (not sure why off exists, best to just leave it on)\n#IQ Inversion (default=off)\nset_iqi = b'off' #values: on, off (not sure why on exists, best to just leave it off)\n#Coding Rate (default=4/5)\nset_cr = b'4/5' #values: 4/5, 4/6, 4/7, 4/8\n#Watchdog Timer Timeout (default=15000)\nset_wdt = b'15000' #value range: 0 to 4294967295 (0 disables wdt functionality)\n#Sync Word (default=34)\nset_sync = b'34' #value: one hexadecimal byte\n#Radio Bandwidth (default=125)\nset_bw = b'125' #values: 125, 250, 500\n#end of line bytes\nend_line = b'\\r\\n'\n\n#turn on both LEDs\nled_control('rx', 'on')\nled_control('tx', 'on')\n\n#write settings to LoStik\nprint('Writing LoStik Settings')\nprint('-----------------------')\n#set mode (default: lora)\nlostik.write(b''.join([b'radio set mod ', set_mod, end_line]))\nprint(' Set Modulation Mode (default=lora): ' + set_mod.decode('ASCII') + ' ... ' + lostik.readline().decode('ASCII'), end='')\n#set frequency (default: 923300000)\nlostik.write(b''.join([b'radio set freq ', set_freq, end_line]))\nprint(' Set Frequency (default=923300000): ' + set_freq.decode('ASCII') + ' ... ' + lostik.readline().decode('ASCII'), end='')\n#set power (default: 2)\nlostik.write(b''.join([b'radio set pwr ', set_pwr, end_line]))\nprint(' Set Transmit Power (default=2): ' + set_pwr.decode('ASCII') + ' ... ' + lostik.readline().decode('ASCII'), end='')\n#set spreading factor (default: sf12)\nlostik.write(b''.join([b'radio set sf ', set_sf, end_line]))\nprint(' Set Spreading Factor (default=sf12): ' + set_sf.decode('ASCII') + ' ... ' + lostik.readline().decode('ASCII'), end='')\n#set CRC header usage (default: on)\nlostik.write(b''.join([b'radio set crc ', set_crc, end_line]))\nprint(' Set CRC Header (default=on): ' + set_crc.decode('ASCII') + ' ... ' + lostik.readline().decode('ASCII'), end='')\n#set IQ inversion (default: off)\nlostik.write(b''.join([b'radio set iqi ', set_iqi, end_line]))\nprint(' Set IQ Inversion (default=off): ' + set_iqi.decode('ASCII') + ' ... ' + lostik.readline().decode('ASCII'), end='')\n#set coding rate (default: 4/5)\nlostik.write(b''.join([b'radio set cr ', set_cr, end_line]))\nprint(' Set Coding Rate (default=4/5): ' + set_cr.decode('ASCII') + ' ... ' + lostik.readline().decode('ASCII'), end='')\n#set watchdog timer timeout (default: 15000)\nlostik.write(b''.join([b'radio set wdt ', set_wdt, end_line]))\nprint('Set Watchdog Timer Timeout (default=15000): ' + set_wdt.decode('ASCII') + ' ... ' + lostik.readline().decode('ASCII'), end='')\n#set sync word (default: 34)\nlostik.write(b''.join([b'radio set sync ', set_sync, end_line]))\nprint(' Set Sync Word (default=34): ' + set_sync.decode('ASCII') + ' ... ' + lostik.readline().decode('ASCII'), end='')\n#set radio bandwidth (default: 125)\nlostik.write(b''.join([b'radio set bw ', set_bw, end_line]))\nprint(' Set Radio Bandwidth (default=125): ' + set_bw.decode('ASCII') + ' ... ' + lostik.readline().decode('ASCII'))\n\n#sleep for half second\ntime.sleep(.5)\n\n#turn of both LEDs\nled_control('rx', 'off')\nled_control('tx', 'off')\n\n#disconnect from lostik\nprint('Disconnecting from LoStik...\\r', end='')\nlostik.close()\nif lostik.is_open == True:\n print('Disconnecting from LoStik... FAIL!')\nelif lostik.is_open == False:\n print('Disconnecting from LoStik... DONE!')\n\n#user notice\nprint('NOTE: Settings do not persist after device power cycle.')\n","sub_path":"set_config.py","file_name":"set_config.py","file_ext":"py","file_size_in_byte":9710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"60967257","text":"\nimport matplotlib.pyplot as plt\n\n# dados\nx = [1, 2, 5]\ny = [2, 3, 7]\n\n# definindo o título do gráfico\nplt.title(\"Gráfico de linhas\")\n\n# definindo legendas\nplt.xlabel(\"Eixo X\")\nplt.ylabel(\"Eixo Y\")\n\n# montando o gráfico\nplt.plot(x, y)\n\n# exibindo o gráfico\nplt.show()\n","sub_path":"matplotlib/1-lines.py","file_name":"1-lines.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"1868224","text":"\"\"\"\nImage processing application for generation of RGB flatfield images\nfrom cloudy images.\n\n\"\"\"\nimport os, rawpy, cv2\nimport numpy as np\n\n# Global settings\nMAX_SATURATION_PERCENT = 10\n\ndef create_flatfield(input, output):\n\n filelist = os.listdir(input)\n \n rgb = ['r', 'g', 'b']\n \n # Do each channel separately to reduce memory footprint\n for i in range(3):\n \n channel = rgb[i]\n \n # Array to store selected & preprocessed RGB frames\n frames = np.empty([20, 4928, 7380], dtype=np.uint8)\n \n idx = 0\n \n for file in filelist:\n \n print('Processing file ', file, ' channel: ', channel) \n \n # Read raw NEF image\n raw = rawpy.imread(input + '/' + file)\n \n # Convert to standard RGB pixels [0:255]\n # Note that rawpy offers control over how the demosaicing is done, e.g.\n # rgbimage = raw.postprocess(gamma=(1,1), no_auto_bright=True)\n # ...however the method we use here should match what's used in the\n # image processing code, to make the flatfield consistent.\n \n # numpy.ndarray of shape (4928, 7380, 3)\n rgbimage = raw.postprocess()\n \n # numpy.ndarray of shape (4928, 7380)\n image = rgbimage[:,:,i]\n \n # Detect saturated images; count number of elements that are 255\n sat = (image == 255).sum()\n sat_perc = 100 * sat / (4928 * 7380)\n \n if sat_perc < MAX_SATURATION_PERCENT:\n frames[idx] = preprocess(image)\n path = str(output) + '/' + file.replace('.NEF', '_' + channel + '.png')\n cv2.imwrite(path, frames[idx])\n idx += 1\n \n print('Used frames = ', idx)\n \n \n # Got all preprocessed images; construct flatfield\n flatfield = construct_flatfield(frames)\n \n # Write flatfields to file\n path = str(output) + '/' + 'vignet_' + channel + '.png'\n \n # Written as PNG image data, 7380 x 4928, 8-bit grayscale, non-interlaced\n cv2.imwrite(path, flatfield)\n \ndef preprocess(frame):\n \n \"\"\"\n Prepares a single R/G/B image for use in flatfield estimation by smoothing,\n normalising etc.\n \"\"\"\n \n # frame pixels -> numpy.uint8\n \n # Measure backgrounds of each image\n frame_smooth = cv2.medianBlur(frame, 71)\n \n # frame_smooth pixels -> numpy.uint8\n \n # Normalise to average pixel value (causes above-average pixels to be above 1.0)\n #norm = np.mean(frame_smooth)\n \n # Normalise to max pixel value\n #norm = np.max(frame_smooth)\n \n # Normalise to 99th percentile level to make robust to noise\n norm = np.percentile(frame_smooth, 99)\n \n # Normalise\n frame_smooth = np.divide(frame_smooth, norm/255)\n \n # Clip values to uint8 range\n frame_smooth = np.clip(frame_smooth, 0, 255)\n \n # Convert back to uint8 to save memory\n frame_smooth = frame_smooth.astype(np.uint8)\n \n return frame_smooth\n\ndef construct_flatfield(frames_array):\n \n # Take unweighted median of the individual frames\n median = np.median(frames_array, axis=0)\n \n # Normalise the median image\n norm = np.percentile(median, 99)\n \n median = np.divide(median, norm/255.0)\n \n return median\n\n\nif __name__ == \"__main__\":\n input = '/home/nrowell/Projects/SSA/FireOPAL/flatfield/input/NEF'\n output = '/home/nrowell/Projects/SSA/FireOPAL/flatfield/output'\n create_flatfield(input, output)\n","sub_path":"src/util/flatfield.py","file_name":"flatfield.py","file_ext":"py","file_size_in_byte":3610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"177320166","text":"import math\r\n\r\n\r\ndef sumar(a,b):\r\n \"\"\"Resuelve la suma de 2 numeros complejos.\r\n\r\n Devuelve una tupla con la parte real y la parte imaginaria.\r\n\r\n Parametros:\r\n a -- Es una tupla que contiene parte real y la parte imaginaria del numero complejo.\r\n b -- Es una tupla que contiene parte real y la parte imaginaria del numero complejo.\r\n\r\n \"\"\"\r\n ente=a[0]+b[0]\r\n imag=a[1]+b[1]\r\n return (ente,imag) \r\n\r\ndef restar(a,b):\r\n \"\"\"Resuelve la resta de 2 numeros complejos.\r\n\r\n Devuelve una tupla con la parte real y la parte imaginaria.\r\n\r\n Parametros:\r\n a -- Es una tupla que contiene parte real y la parte imaginaria del numero complejo.\r\n b -- Es una tupla que contiene parte real y la parte imaginaria del numero complejo.\r\n\r\n \"\"\"\r\n ente=a[0]-b[0]\r\n imag=a[1]-b[1]\r\n return (ente,imag) \r\n\r\ndef multiplicar(a,b):\r\n \"\"\"Resuelve la multiplicacion de 2 numeros complejos.\r\n\r\n Devuelve una tupla con la parte real y la parte imaginaria.\r\n\r\n Parametros:\r\n a -- Es una tupla que contiene parte real y la parte imaginaria del numero complejo.\r\n b -- Es una tupla que contiene parte real y la parte imaginaria del numero complejo.\r\n\r\n \"\"\"\r\n ente=a[0]*b[0]+(-1*(b[1]*a[1]))\r\n imag=a[0]*b[1]+a[1]*b[0]\r\n return (ente,imag) \r\n\r\ndef modulo(a):\r\n \"\"\"Resuelve el modulo de un numero complejo.\r\n\r\n Devuelve una tupla de un real.\r\n\r\n Parametros:\r\n a -- Es una tupla que contiene parte real y la parte imaginaria del numero complejo.\r\n\r\n \"\"\"\r\n return (math.sqrt((a[0]**2+a[1]**2)))\r\n \r\ndef division(a,b):\r\n \"\"\"Resuelve la division de 2 numeros complejos.\r\n\r\n Devuelve una tupla con la parte real y la parte imaginaria.\r\n\r\n Parametros:\r\n a -- Es una tupla que contiene parte real y la parte imaginaria del numero complejo.\r\n b -- Es una tupla que contiene parte real y la parte imaginaria del numero complejo.\r\n\r\n \"\"\"\r\n try:\r\n div=b[0]**2+b[1]**2\r\n ente=(a[0]*b[0]+a[1]*b[1])/div\r\n imag=(a[1]*b[0]-a[0]*b[1])/div\r\n return (ente,imag) \r\n except:\r\n return 'Imposible hacer la division.'\r\n \r\ndef conjugado(a):\r\n \"\"\"Resuelve el conugado de un numero complejo.\r\n\r\n Devuelve una tupla con la parte real y la parte imaginaria.\r\n\r\n Parametros:\r\n a -- Es una tupla que contiene parte real y la parte imaginaria del numero complejo.\r\n\r\n \"\"\"\r\n ente=a[0]\r\n imag=a[1]*-1\r\n return (ente,imag)\r\n\r\ndef cartesianoPolar(a):\r\n \"\"\"Cambia de coordenadas cartesianas a polares de un numero complejo.\r\n\r\n Devuelve una tupla con la parte real y un angulo en radianes.\r\n\r\n Parametros:\r\n a -- Es una tupla que contiene parte real y la parte imaginaria del numero complejo.\r\n\r\n \"\"\"\r\n p=(math.sqrt(a[0]**2+a[1]**2))\r\n o=(math.atan2(a[1],a[0]))\r\n return (p,o)\r\n\r\ndef polarCartesiano(p):\r\n \"\"\"Cambia de coordenadas polares a cartesianas de un numero complejo.\r\n\r\n Devuelve una tupla con la parte real y la parte imaginaria del numero complejo.\r\n\r\n Parametros:\r\n p -- Es una tupla que contiene parte real y un angulo.\r\n\r\n \"\"\"\r\n a=round(p[0]*math.cos(p[1]),3)\r\n b=round(p[0]*math.sin(p[1]),3)\r\n return (a,b)\r\n\r\ndef fase(a):\r\n \"\"\"Resuelve la fase de un numero complejo.\r\n\r\n Devuelve una tupla que contiene el angulo en radianes.\r\n\r\n Parametros:\r\n a -- Es una tupla que contiene parte real y la parte imaginaria del numero complejo.\r\n\r\n \"\"\"\r\n res=math.atan2(a[1],a[0])\r\n return (round(res,2))\r\n\r\ndef sumaVectoresComplejos(a,b):\r\n \"\"\"Resuelve la suma de dos vectores de numeros complejos.\r\n\r\n Devuelve un arreglo con la suma de vectores.\r\n\r\n Parametros:\r\n a -- Es un Arreglo que repesenta un vector.\r\n b -- Es un Arreglo que repesenta un vector.\r\n\r\n \"\"\"\r\n try:\r\n res=[]\r\n for i in range(len(a)):\r\n row=sumar(a[i],b[i])\r\n res.append(row)\r\n return res\r\n except:\r\n return 'No es posible hacer la suma de vectores, revisa las dimensiones.'\r\n\r\ndef inversaVectores(a):\r\n \"\"\"Calcula la inversa de un vector de numeros complejos.\r\n\r\n Devuelve un arreglo con la inversa del vector a.\r\n\r\n Parametros:\r\n a -- Es un Arreglo que representa un vector, contiene tuplas de numeros complejos.\r\n\r\n \"\"\"\r\n res=[]\r\n for i in range(len(a)):\r\n real=a[i][0]\r\n img=a[i][1]\r\n row=(-real,-img)\r\n res.append(row)\r\n return res\r\n\r\ndef multEscalarVectores(escalar,vector):\r\n \"\"\"Resuelve la multiplicacion de un escalar por un vectores de numeros complejos.\r\n\r\n Devuelve un arreglo con la multiplicacion del escalar por el vector.\r\n\r\n Parametros:\r\n escalar -- Es una tupla que contiene un numero complejo (real, imaginario).\r\n vector -- Es un Arreglo que repesenta un vector, con tuplas de complejos.\r\n\r\n \"\"\"\r\n res=[]\r\n for i in range(len(vector)):\r\n row=multiplicar(escalar,vector[i])\r\n res.append(row)\r\n return res\r\n\r\ndef sumaMatricesComplejas(a,b):\r\n \"\"\"Resuelve la suma de dos matrices de numeros complejos.\r\n\r\n Devuelve un arreglo con la suma de las matrices.\r\n\r\n Parametros:\r\n a -- Es un arreglo de arreglos que repesenta una matriz, contiene tuplas de numeros complejos.\r\n b -- Es un arreglo de arreglos que repesenta una matriz, contiene tuplas de numeros complejos.\r\n\r\n \"\"\"\r\n try:\r\n res=[]\r\n for i in range(len(a)):\r\n row=[]\r\n for j in range(len(a[i])):\r\n add=sumar(a[i][j],b[i][j])\r\n row.append(add)\r\n res.append(row)\r\n return res\r\n except:\r\n return 'No es posible hacer la suma de matrices, revisa las dimensinones.'\r\n\r\n\r\n\r\ndef inversaMatricesComplejas(a):\r\n \"\"\"Calcula la inversa de una matriz de numeros comlejos.\r\n\r\n Devuelve un arreglo de arreglos con la inversa de a.\r\n\r\n Parametros:\r\n a -- Es un arreglo de arreglos que repesenta una matriz, contiene tuplas de numeros complejos.\r\n\r\n \"\"\"\r\n res=[]\r\n for i in range(len(a)):\r\n res.append(inversaVectores(a[i]))\r\n return res\r\n\r\ndef multEscalarMatriz(escalar,matriz):\r\n \"\"\"Calcula la multiplicaicon de un escalar por una matriz de numeros complejos.\r\n\r\n Devuelve un arreglo de arreglos que representa la multiplicacion.\r\n\r\n Parametros:\r\n escalar -- Es una tupla de un numero complejo.\r\n matriz -- Es un arreglo de arreglos que repesenta una matriz, contiene tuplas de numeros complejos.\r\n\r\n \"\"\"\r\n res=[]\r\n for i in matriz:\r\n res.append(multEscalarVectores(escalar,i))\r\n return res\r\n\r\ndef transpuestaMatriz(a):\r\n \"\"\"Calcula la transpuesta de una matriz de numeros complejos.\r\n En particular, si se ingresa un vector seria de la forma:[[(r0,c0),(r1,c1),(rn,cn)]]\r\n\r\n Devuelve un arreglo de arreglos con la transpuesta de a.\r\n\r\n Parametros:\r\n a -- Es un arreglo de arreglos que repesenta una matriz, contiene tuplas de numeros complejos.\r\n\r\n \"\"\"\r\n res=rellenar(a) \r\n for i in range(len(a)):\r\n for j in range(len(a[i])):\r\n res[j][i]=a[i][j]\r\n return res\r\n\r\ndef conjugadoMatriz(a):\r\n \"\"\"Calcula el conjugado de una matriz de numeros complejos.\r\n En particular, si se ingresa un vector seria de la forma:[[(r0,c0),(r1,c1),(rn,cn)]]\r\n\r\n Devuelve un arreglo de arreglos con el conjugado de a.\r\n\r\n Parametros:\r\n a -- Es un arreglo de arreglos que repesenta una matriz, contiene tuplas de numeros complejos.\r\n\r\n \"\"\"\r\n res=[]\r\n for i in range(len(a)):\r\n row=[]\r\n for j in range(len(a[i])):\r\n row.append(conjugado(a[i][j]))\r\n res.append(row)\r\n return res\r\n\r\ndef adjuntaMatriz(a):\r\n \"\"\"Calcula la adjunta de un matriz de numeros complejos.\r\n\r\n Devuelve un arreglo de arreglos con la adjunta de a.\r\n\r\n Parametros:\r\n a -- Es un arreglo de arreglos que repesenta una matriz, contiene tuplas de numeros complejos.\r\n\r\n \"\"\"\r\n conj=conjugadoMatriz(a)\r\n return transpuestaMatriz(conj)\r\n\r\ndef productoDeMatrices(a,b):\r\n \"\"\"Calcula el producto dos matrices de numeros complejos.\r\n\r\n Devuelve un arreglo de arreglos con el producto de a y b.\r\n\r\n Parametros:\r\n a -- Es un arreglo de arreglos que repesenta una matriz, contiene tuplas de numeros complejos.\r\n b -- Es un arreglo de arreglos que repesenta una matriz, contiene tuplas de numeros complejos.\r\n\r\n \"\"\"\r\n try:\r\n res=[]\r\n for i in range(len(a)):\r\n row=[]\r\n for j in range(len(a[i])):\r\n suma=(0,0)\r\n for k in range(len(a[i])):\r\n temp=multiplicar(a[i][k],b[k][j])\r\n suma=sumar(temp, suma)\r\n row.append(suma)\r\n res.append(row)\r\n return res\r\n except:\r\n return 'No es posible hacer el prudcto de matrices, revisa las dimensiones.'\r\n\r\ndef productoMatrizVector(matriz,vector):\r\n \"\"\"Calcula el producto una matrices y un vector; de numeros complejos.\r\n\r\n Devuelve un arreglo con el producto de la matriz y el vector.\r\n\r\n Parametros:\r\n matriz -- Es un arreglo de arreglos que repesenta una matriz, contiene tuplas de numeros complejos.\r\n vector -- Es un arreglo repesenta un vector, contiene tuplas de numeros complejos.\r\n\r\n \"\"\"\r\n try:\r\n res=[]\r\n for i in range(len(matriz)):\r\n suma=(0,0)\r\n for j in range(len(vector)):\r\n temp=multiplicar(matriz[i][j],vector[j])\r\n suma=sumar(temp,suma)\r\n res.append(suma) \r\n return res\r\n except:\r\n return 'No es posible hacer el producto de matriz y vector, revisa las dimensiones.'\r\n\r\ndef productoInternoVectores(a,b):\r\n \"\"\"Calcula el producto interno de 2 vectores de numeros complejos.\r\n\r\n Devuelve un numero complejo con el producto interno de a y b.\r\n\r\n Parametros:\r\n a -- Es un arreglo que repesenta un vector, contiene tuplas de numeros complejos.\r\n b -- Es un arreglo que repesenta un vector, contiene tuplas de numeros complejos.\r\n\r\n \"\"\"\r\n try:\r\n newA=adjuntaMatriz([a])\r\n suma=(0,0)\r\n for i in range(len(a)):\r\n for j in range(len(newA[i])):\r\n temp=multiplicar(newA[i][j],b[i])\r\n suma=sumar(temp,suma)\r\n return suma\r\n except:\r\n return 'No es posible hacer el prodcuto interno de vecctores, revisa las dimensiones.'\r\n\r\ndef normaVector(a):\r\n \"\"\"Calcula la norma o loguitud de un vectorde numeros complejos.\r\n\r\n Devuelve un numero que representa la norma o longuitud.\r\n\r\n Parametros:\r\n a -- Es un arreglo que repesenta un vector, contiene tuplas de numeros complejos.\r\n \"\"\"\r\n pim=productoInternoVectores(a,a)\r\n return math.sqrt(pim[0])\r\n\r\ndef distanciaVectores(a,b):\r\n \"\"\"Calcula la distancia de 2 vectores de numeros complejos.\r\n\r\n Devuelve un numero que representa la disstancia.\r\n\r\n Parametros:\r\n a -- Es un arreglo que repesenta un vector, contiene tuplas de numeros complejos.\r\n b -- Es un arreglo que repesenta un vector, contiene tuplas de numeros complejos.\r\n\r\n \"\"\"\r\n newB=multEscalarVectores((-1,0),b)\r\n A=sumaMatricesComplejas([a],[newB])\r\n pim=productoInternoVectores(A[0],A[0])\r\n return math.sqrt(pim[0]) \r\n\r\ndef matrizUnitariaComprobacion(a):\r\n \"\"\"Comprueba si la matriz es o no unitaria.\r\n\r\n Devuelve un booleano avisando si la matriz es o no unitaria.\r\n\r\n Parametros:\r\n a -- Es un arreglo de arreglos que repesenta una matriz, contiene tuplas de numeros complejos.\r\n\r\n \"\"\"\r\n adj=adjuntaMatriz(a)\r\n mul=productoDeMatrices(a,adj)\r\n res=crearIdentidad(a)\r\n rm=redondear(mul)\r\n if res==rm:\r\n return True\r\n return False\r\n\r\ndef matrizHermitianaComprobacion(a):\r\n \"\"\"Comprueba si la matriz es o no hermitiana.\r\n\r\n Devuelve un booleano avisando si la matriz es o no hermitiana.\r\n\r\n Parametros:\r\n a -- Es un arreglo de arreglos que repesenta una matriz, contiene tuplas de numeros complejos.\r\n\r\n \"\"\"\r\n adj=adjuntaMatriz(a)\r\n if adj==a:\r\n return True\r\n return False\r\n \r\ndef productoTensor(a,b):\r\n \"\"\"Calcula el producto tensor entre 2 matrices de numeros complejos.\r\n\r\n Devuelve una matriz con el producto tensor de a y b.\r\n\r\n Parametros:\r\n a -- Es un arreglo de arreglos que repesenta una matriz, contiene tuplas de numeros complejos.\r\n b -- Es un arreglo de arreglos que repesenta una matriz, contiene tuplas de numeros complejos.\r\n\r\n \"\"\"\r\n\r\n res=[]\r\n for i in range(len(a)):\r\n for j in range(len(b)):\r\n row=[]\r\n for k in range(len(a[i])):\r\n for l in range(len(b[k])):\r\n val=multiplicar(a[i][k],b[j][l])\r\n row.append(val)\r\n res.append(row) \r\n return res\r\n \r\ndef redondear(a):\r\n res=[]\r\n for i in a:\r\n row=[]\r\n for j in i:\r\n row.append((round(j[0]),j[1]))\r\n res.append(row)\r\n return res\r\n\r\ndef crearIdentidad(a):\r\n res=[]\r\n for i in range(len(a)):\r\n row=[]\r\n for j in range(len(a[i])):\r\n if j==i:\r\n row.append((1,0))\r\n else:\r\n row.append((0,0))\r\n res.append(row)\r\n return res\r\n \r\ndef rellenar(a):\r\n res=[]\r\n for i in range(len(a[0])):\r\n row=[]\r\n for j in range(len(a)):\r\n row.append(None)\r\n res.append(row)\r\n return res\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n","sub_path":"Complejos.py","file_name":"Complejos.py","file_ext":"py","file_size_in_byte":13525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"638683668","text":"'''\nEnunciado: faça um programa que leia 5 valores numeŕicos e guarde-os em uma lista.\nNo finla, mostre qual o maior e menor valor digitado e suas respectivas posições na lista.\n'''\n\nvalores = list()\nmaior = 0\nmenor = 0\npmaior = []\npmenor = []\n\nfor c in range(0, 5):\n valores.append(int(input(f'Informe um valor para a posição {c}: ')))\n if c == 0:\n maior = valores[c]\n menor = valores[c]\n else:\n if valores[c] > maior:\n maior = valores[c]\n pmaior.append(c)\n if valores[c] < menor:\n menor = valores[c]\n pmenor.append(c)\n\nprint()\nprint(f'Voce digitou os números: {valores}')\n\n'''\nprint(f'\\nO maior valor foi {maior} na posição ', end='')\nfor cnt1 in range(0, len(pmaior)):\n print(f'{pmaior[cnt1]}...', end='')\n\nprint(f'\\nO menor valor foi {menor} na posição ', end='')\nfor cnt2 in range(0, len(pmenor)):\n print(f'{pmenor[cnt2]}...', end='')\n'''","sub_path":"exercicios-cursoemvideo-python3-mundo3/Aula17_p1/exerc078.py","file_name":"exerc078.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"121914760","text":"# pip install SpeechRecognition\n#import library\nimport speech_recognition as sr\n\n# Initialize recognizer class (for recognizing the speech)\nr = sr.Recognizer()\n\n# Reading Audio file as source\n# listening the audio file and store in audio_text variable\n\n#with sr.AudioFile('Voice001wav.wav') as source: #run with the audio file in spanish\n#with sr.AudioFile('Lumumba1aac.wav') as source: #run with the audio file in french\nwith sr.AudioFile('MaximilienParyacc.wav') as source: #run with the audio file in english\n \n #audio_text = r.listen(source, timeout=3)\n audio_text = r.record(source)\n \n #audio = r.adjust_for_ambient_noise(source)\n \n# recoginize_() method will throw a request error if the API is unreachable, hence using exception handling\n try:\n \n # using google speech recognition\n #text = r.recognize_google(audio_text, show_all=True)\n #text = r.recognize_google(audio_text, language=\"es-ES\")\n #text = r.recognize_google(audio_text, language=\"fr-FR\")\n text = r.recognize_google(audio_text, language=\"en-EN\")\n print('Converting audio transcripts into text ...')\n print(text)\n \n except:\n print('Sorry.. run again...')","sub_path":"voice_recognition.py","file_name":"voice_recognition.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"358559372","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2012-2013 Universidad Politécnica de Madrid\n\n# This file is part of Wirecloud.\n\n# Wirecloud 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# Wirecloud 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 Wirecloud. If not, see .\n\n\n# -*- coding: utf-8 -*-\n\nimport codecs\nimport os\nimport rdflib\nfrom tempfile import mkdtemp\nfrom shutil import rmtree\nimport json\n\nfrom django.contrib.auth.models import User, Group\nfrom django.core.cache import cache\nfrom django.core.urlresolvers import reverse\nfrom django.test import Client\nfrom django.utils import simplejson\n\nfrom wirecloud.catalogue import utils as catalogue\nfrom wirecloud.commons.test import WirecloudTestCase\nfrom wirecloud.commons.utils.wgt import WgtDeployer, WgtFile\nfrom wirecloud.platform.get_data import get_global_workspace_data\nfrom wirecloud.platform.models import IWidget, Tab, UserWorkspace, Variable, VariableValue, Workspace\nfrom wirecloud.platform.iwidget.utils import SaveIWidget, deleteIWidget\nfrom wirecloud.platform.workspace.packageCloner import PackageCloner\nfrom wirecloud.platform.workspace.mashupTemplateGenerator import build_template_from_workspace, build_rdf_template_from_workspace, build_usdl_from_workspace\nfrom wirecloud.platform.workspace.mashupTemplateParser import buildWorkspaceFromTemplate, fillWorkspaceUsingTemplate\nfrom wirecloud.platform.workspace.utils import sync_base_workspaces\nfrom wirecloud.platform.workspace.views import createEmptyWorkspace, linkWorkspace\n\n\n# Avoid nose to repeat these tests (they are run through wirecloud/tests/__init__.py)\n__test__ = False\n\n\nclass CacheTestCase(WirecloudTestCase):\n\n def setUp(self):\n super(CacheTestCase, self).setUp()\n cache.clear()\n\n\nclass WorkspaceTestCase(CacheTestCase):\n\n fixtures = ('test_data',)\n\n def setUp(self):\n super(WorkspaceTestCase, self).setUp()\n\n self.user = User.objects.get(username='test')\n\n def test_get_global_workspace_data(self):\n\n workspace = Workspace.objects.get(pk=1)\n data = get_global_workspace_data(workspace, self.user).get_data()\n self.assertEqual(len(data['tabs']), 1)\n\n tab = data['tabs'][0]\n variables = tab['iwidgets'][0]['variables']\n self.assertEqual(variables['password']['value'], '')\n self.assertEqual(variables['password']['secure'], True)\n self.assertEqual(variables['username']['value'], 'test_username')\n self.assertEqual(variables['prop']['value'], 'test_data')\n test_get_global_workspace_data.tags = ('fiware-ut-3',)\n\n def test_create_empty_workspace(self):\n\n workspace = createEmptyWorkspace('Testing', self.user)\n\n user_workspace = UserWorkspace.objects.filter(user=self.user, workspace=workspace)\n self.assertEqual(user_workspace.count(), 1)\n self.assertEqual(user_workspace[0].active, True)\n\n workspace_tabs = Tab.objects.filter(workspace=workspace)\n self.assertEqual(workspace_tabs.count(), 1)\n\n data = get_global_workspace_data(workspace, self.user).get_data()\n self.assertEqual(data['owned'], True)\n self.assertEqual(data['shared'], False)\n test_create_empty_workspace.tags = ('fiware-ut-3',)\n\n def test_link_workspace(self):\n\n workspace = Workspace.objects.get(pk=1)\n\n alternative_user = User.objects.get(username='test2')\n new_workspace = linkWorkspace(alternative_user, workspace.id, self.user)\n\n all_variables = VariableValue.objects.filter(variable__iwidget__tab__workspace=workspace)\n initial_vars = all_variables.filter(user=self.user)\n cloned_vars = all_variables.filter(user=alternative_user)\n\n self.assertEqual(new_workspace.user, alternative_user)\n self.assertEqual(workspace.creator, self.user)\n self.assertEqual(new_workspace.workspace, workspace)\n self.assertEqual(initial_vars.count(), cloned_vars.count())\n\n def test_clone_workspace(self):\n\n workspace = Workspace.objects.get(pk=1)\n\n packageCloner = PackageCloner()\n cloned_workspace = packageCloner.clone_tuple(workspace)\n\n self.assertNotEqual(workspace, cloned_workspace)\n self.assertEqual(cloned_workspace.users.count(), 0)\n\n original_iwidgets = IWidget.objects.filter(tab__workspace=workspace)\n cloned_iwidgets = IWidget.objects.filter(tab__workspace=cloned_workspace)\n self.assertEqual(original_iwidgets.count(), cloned_iwidgets.count())\n self.assertNotEqual(original_iwidgets[0].id, cloned_iwidgets[0].id)\n\n original_variables = Variable.objects.filter(iwidget__tab__workspace=workspace)\n cloned_variables = Variable.objects.filter(iwidget__tab__workspace=cloned_workspace)\n\n self.assertEqual(original_variables.count(), cloned_variables.count())\n self.assertNotEqual(original_variables[0].id, cloned_variables[0].id)\n\n def test_merge_workspaces(self):\n\n workspace = Workspace.objects.get(pk=1)\n\n packageCloner = PackageCloner()\n cloned_workspace = packageCloner.clone_tuple(workspace)\n linkWorkspace(self.user, cloned_workspace.id, self.user)\n\n packageCloner = PackageCloner()\n packageCloner.merge_workspaces(cloned_workspace, workspace, self.user)\n\n # Check cache invalidation\n data = get_global_workspace_data(workspace, self.user).get_data()\n tab_list = data['tabs']\n\n self.assertEqual(len(tab_list), 2)\n\n def test_shared_workspace(self):\n\n workspace = Workspace.objects.get(pk=1)\n\n # Create a new group and share the workspace with it\n group = Group.objects.create(name='test_users')\n workspace.targetOrganizations.add(group)\n\n other_user = User.objects.get(username='test2')\n other_user.groups.add(group)\n other_user.save()\n\n # Sync shared workspaces\n sync_base_workspaces(other_user)\n\n # Check that other_user can access to the shared workspace\n data = get_global_workspace_data(workspace, other_user).get_data()\n iwidget_list = data['tabs'][0]['iwidgets']\n self.assertEqual(len(iwidget_list), 2)\n\n # Add a new iWidget to the workspace\n tab = Tab.objects.get(pk=1)\n iwidget_data = {\n 'widget': 'Test/Test Widget/1.0.0',\n 'name': 'test',\n 'top': 0,\n 'left': 0,\n 'width': 2,\n 'height': 2,\n 'zIndex': 1,\n 'layout': 0,\n 'icon_top': 0,\n 'icon_left': 0\n }\n SaveIWidget(iwidget_data, self.user, tab, {})\n\n data = get_global_workspace_data(workspace, other_user).get_data()\n iwidget_list = data['tabs'][0]['iwidgets']\n self.assertEqual(len(iwidget_list), 3)\n\n\nclass WorkspaceCacheTestCase(CacheTestCase):\n\n fixtures = ('test_data',)\n tags = ('fiware-ut-3',)\n\n def setUp(self):\n super(WorkspaceCacheTestCase, self).setUp()\n\n self.user = User.objects.get(username='test')\n self.workspace = Workspace.objects.get(pk=1)\n\n # Fill cache\n get_global_workspace_data(self.workspace, self.user)\n\n def test_variable_updating_invalidates_cache(self):\n\n client = Client()\n put_data = [\n {'id': 1, 'value': 'new_password'},\n {'id': 2, 'value': 'new_username'},\n {'id': 4, 'value': 'new_data'},\n ]\n\n put_data = simplejson.dumps(put_data, ensure_ascii=False).encode('utf-8')\n client.login(username='test', password='test')\n result = client.put(reverse('wirecloud.variable_collection', kwargs={'workspace_id': 1}), put_data, content_type='application/json', HTTP_HOST='localhost', HTTP_REFERER='http://localhost')\n self.assertEqual(result.status_code, 200)\n\n data = get_global_workspace_data(self.workspace, self.user).get_data()\n variables = data['tabs'][0]['iwidgets'][0]['variables']\n self.assertEqual(variables['password']['value'], '')\n self.assertEqual(variables['password']['secure'], True)\n self.assertEqual(variables['username']['value'], 'new_username')\n self.assertEqual(variables['prop']['value'], 'new_data')\n\n def test_widget_instantiation_invalidates_cache(self):\n\n tab = Tab.objects.get(pk=1)\n iwidget_data = {\n 'widget': 'Test/Test Widget/1.0.0',\n 'name': 'test',\n 'top': 0,\n 'left': 0,\n 'width': 2,\n 'height': 2,\n 'zIndex': 1,\n 'layout': 0,\n 'icon_top': 0,\n 'icon_left': 0\n }\n SaveIWidget(iwidget_data, self.user, tab, {})\n\n data = get_global_workspace_data(self.workspace, self.user).get_data()\n\n iwidget_list = data['tabs'][0]['iwidgets']\n self.assertEqual(len(iwidget_list), 3)\n\n def test_widget_deletion_invalidates_cache(self):\n\n deleteIWidget(IWidget.objects.get(pk=1), self.user)\n data = get_global_workspace_data(self.workspace, self.user).get_data()\n iwidget_list = data['tabs'][0]['iwidgets']\n self.assertEqual(len(iwidget_list), 1)\n\n\nclass ParameterizedWorkspaceGenerationTestCase(WirecloudTestCase):\n\n WIRE_M = rdflib.Namespace('http://wirecloud.conwet.fi.upm.es/ns/mashup#')\n FOAF = rdflib.Namespace('http://xmlns.com/foaf/0.1/')\n RDF = rdflib.Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')\n DCTERMS = rdflib.Namespace('http://purl.org/dc/terms/')\n USDL = rdflib.Namespace('http://www.linked-usdl.org/ns/usdl-core#')\n VCARD = rdflib.Namespace('http://www.w3.org/2006/vcard/ns#')\n\n fixtures = ('test_data',)\n tags = ('fiware-ut-1',)\n\n def setUp(self):\n\n super(ParameterizedWorkspaceGenerationTestCase, self).setUp()\n\n self.user = User.objects.get(username='test')\n self.workspace_with_iwidgets = Workspace.objects.get(pk=1)\n self.workspace = createEmptyWorkspace('Testing', self.user)\n\n def assertXPathText(self, root_element, xpath, content):\n elements = root_element.xpath(xpath)\n self.assertEqual(len(elements), 1)\n self.assertEqual(elements[0].text, content)\n\n def assertXPathAttr(self, root_element, xpath, attr, content):\n elements = root_element.xpath(xpath)\n self.assertEqual(len(elements), 1)\n self.assertEqual(elements[0].get(attr), content)\n\n def assertXPathCount(self, root_element, xpath, count):\n elements = root_element.xpath(xpath)\n self.assertEqual(len(elements), count)\n\n def assertRDFElement(self, graph, element, ns, predicate, content):\n elements = graph.objects(element, ns[predicate])\n for e in elements:\n self.assertEqual(unicode(e), content)\n\n def assertRDFCount(self, graph, element, ns, predicate, count):\n num = 0\n for e in graph.objects(element, ns[predicate]):\n num = num + 1\n\n self.assertEqual(num, count)\n\n def test_build_template_from_workspace(self):\n\n options = {\n 'vendor': 'Wirecloud Test Suite',\n 'name': 'Test Mashup',\n 'version': '1',\n 'author': 'test',\n 'email': 'a@b.com',\n 'readOnlyWidgets': True,\n }\n template = build_template_from_workspace(options, self.workspace, self.user)\n\n # Basic info\n self.assertXPathText(template, '/Template/Catalog.ResourceDescription/Vendor', 'Wirecloud Test Suite')\n self.assertXPathText(template, '/Template/Catalog.ResourceDescription/Name', 'Test Mashup')\n self.assertXPathText(template, '/Template/Catalog.ResourceDescription/Version', '1')\n self.assertXPathText(template, '/Template/Catalog.ResourceDescription/Author', 'test')\n self.assertXPathText(template, '/Template/Catalog.ResourceDescription/Mail', 'a@b.com')\n\n # IWidgets\n self.assertXPathCount(template, '/Template/Catalog.ResourceDescription/IncludedResources/Tab', 1)\n self.assertXPathAttr(template, '/Template/Catalog.ResourceDescription/IncludedResources/Tab[1]', 'name', 'Tab')\n self.assertXPathCount(template, '/Template/Catalog.ResourceDescription/IncludedResources/Tab[1]/IWidget', 0)\n\n # Workspace with iwidgets\n options = {\n 'vendor': 'Wirecloud Test Suite',\n 'name': 'Test Mashup',\n 'version': '1',\n 'author': 'test',\n 'email': 'a@b.com',\n 'readOnlyWidgets': True,\n }\n template = build_template_from_workspace(options, self.workspace_with_iwidgets, self.user)\n\n # Basic info\n self.assertXPathText(template, '/Template/Catalog.ResourceDescription/Vendor', 'Wirecloud Test Suite')\n self.assertXPathText(template, '/Template/Catalog.ResourceDescription/Name', 'Test Mashup')\n self.assertXPathText(template, '/Template/Catalog.ResourceDescription/Version', '1')\n self.assertXPathText(template, '/Template/Catalog.ResourceDescription/Author', 'test')\n self.assertXPathText(template, '/Template/Catalog.ResourceDescription/Mail', 'a@b.com')\n\n # IWidgets\n self.assertXPathCount(template, '/Template/Catalog.ResourceDescription/IncludedResources/Tab', 1)\n self.assertXPathAttr(template, '/Template/Catalog.ResourceDescription/IncludedResources/Tab[1]', 'name', 'tab')\n self.assertXPathCount(template, '/Template/Catalog.ResourceDescription/IncludedResources/Tab[1]/Resource', 2)\n\n def test_build_rdf_template_from_workspace(self):\n\n options = {\n 'vendor': u'Wirecloud Test Suite',\n 'name': u'Test Mashup',\n 'version': u'1',\n 'author': u'test',\n 'email': u'a@b.com',\n 'readOnlyWidgets': True,\n }\n # Basic info\n graph = build_rdf_template_from_workspace(options, self.workspace, self.user)\n mashup_uri = graph.subjects(self.RDF['type'], self.WIRE_M['Mashup']).next()\n\n self.assertRDFElement(graph, mashup_uri, self.DCTERMS, 'title', u'Test Mashup')\n self.assertRDFElement(graph, mashup_uri, self.USDL, 'versionInfo', u'1')\n\n vendor = graph.objects(mashup_uri, self.USDL['hasProvider']).next()\n self.assertRDFElement(graph, vendor, self.FOAF, 'name', u'Wirecloud Test Suite')\n\n addr = graph.objects(mashup_uri, self.VCARD['addr']).next()\n self.assertRDFElement(graph, addr, self.VCARD, 'email', u'a@b.com')\n\n author = graph.objects(mashup_uri, self.DCTERMS['creator']).next()\n self.assertRDFElement(graph, author, self.FOAF, 'name', u'test')\n\n self.assertRDFCount(graph, mashup_uri, self.WIRE_M, 'hasTab', 1)\n\n tab = graph.objects(mashup_uri, self.WIRE_M['hasTab']).next()\n self.assertRDFElement(graph, tab, self.DCTERMS, 'title', u'Tab')\n\n # Workspace with iwidgets\n options = {\n 'vendor': u'Wirecloud Test Suite',\n 'name': u'Test Mashup',\n 'version': u'1',\n 'author': u'test',\n 'email': u'a@b.com',\n 'readOnlyWidgets': True,\n }\n graph = build_rdf_template_from_workspace(options, self.workspace_with_iwidgets, self.user)\n mashup_uri = graph.subjects(self.RDF['type'], self.WIRE_M['Mashup']).next()\n\n self.assertRDFElement(graph, mashup_uri, self.DCTERMS, 'title', u'Test Mashup')\n self.assertRDFElement(graph, mashup_uri, self.USDL, 'versionInfo', u'1')\n\n vendor = graph.objects(mashup_uri, self.USDL['hasProvider']).next()\n self.assertRDFElement(graph, vendor, self.FOAF, 'name', u'Wirecloud Test Suite')\n\n addr = graph.objects(mashup_uri, self.VCARD['addr']).next()\n self.assertRDFElement(graph, addr, self.VCARD, 'email', u'a@b.com')\n\n author = graph.objects(mashup_uri, self.DCTERMS['creator']).next()\n self.assertRDFElement(graph, author, self.FOAF, 'name', u'test')\n\n self.assertRDFCount(graph, mashup_uri, self.WIRE_M, 'hasTab', 1)\n\n tab = graph.objects(mashup_uri, self.WIRE_M['hasTab']).next()\n self.assertRDFElement(graph, tab, self.DCTERMS, 'title', u'tab')\n self.assertRDFCount(graph, tab, self.WIRE_M, 'hasiWidget', 2)\n\n def test_build_rdf_template_from_workspace_utf8_char(self):\n options = {\n 'vendor': u'Wirecloud Test Suite',\n 'name': u'Test Mashup with ñ',\n 'version': u'1',\n 'author': u'author with é',\n 'email': u'a@b.com',\n 'readOnlyWidgets': True,\n }\n\n graph = build_rdf_template_from_workspace(options, self.workspace, self.user)\n mashup_uri = graph.subjects(self.RDF['type'], self.WIRE_M['Mashup']).next()\n\n self.assertRDFElement(graph, mashup_uri, self.DCTERMS, 'title', u'Test Mashup with ñ')\n self.assertRDFElement(graph, mashup_uri, self.USDL, 'versionInfo', u'1')\n\n vendor = graph.objects(mashup_uri, self.USDL['hasProvider']).next()\n self.assertRDFElement(graph, vendor, self.FOAF, 'name', u'Wirecloud Test Suite')\n\n addr = graph.objects(mashup_uri, self.VCARD['addr']).next()\n self.assertRDFElement(graph, addr, self.VCARD, 'email', u'a@b.com')\n\n author = graph.objects(mashup_uri, self.DCTERMS['creator']).next()\n self.assertRDFElement(graph, author, self.FOAF, 'name', u'author with é')\n\n def test_build_usdl_from_workspace(self):\n\n options = {\n 'vendor': u'Wirecloud Test Suite',\n 'name': u'Test Workspace',\n 'version': u'1',\n 'author': u'test',\n 'email': u'a@b.com',\n 'readOnlyWidgets': True,\n }\n graph = build_usdl_from_workspace(options, self.workspace, self.user, 'http://wirecloud.conwet.fi.upm.es/ns/mashup#/Wirecloud%20Test%20Suite/Test%20Workspace/1')\n services = graph.subjects(self.RDF['type'], self.USDL['Service'])\n\n for service in services:\n if str(service) == str(self.WIRE_M[options['vendor'] + '/' + options['name'] + '/' + options['version']]):\n service_uri = service\n break\n else:\n raise Exception\n\n self.assertRDFElement(graph, service_uri, self.DCTERMS, 'title', u'Test Workspace')\n self.assertRDFElement(graph, service_uri, self.USDL, 'versionInfo', u'1')\n vendor = graph.objects(service_uri, self.USDL['hasProvider']).next()\n self.assertRDFElement(graph, vendor, self.FOAF, 'name', u'Wirecloud Test Suite')\n\n\nclass ParameterizedWorkspaceParseTestCase(CacheTestCase):\n\n fixtures = ('selenium_test_data',)\n tags = ('fiware-ut-2',)\n\n @classmethod\n def setUpClass(cls):\n\n super(ParameterizedWorkspaceParseTestCase, cls).setUpClass()\n\n # catalogue deployer\n cls.old_catalogue_deployer = catalogue.wgt_deployer\n cls.catalogue_tmp_dir = mkdtemp()\n catalogue.wgt_deployer = WgtDeployer(cls.catalogue_tmp_dir)\n\n cls.widget_wgt_file = open(os.path.join(cls.shared_test_data_dir, 'Wirecloud_Test_1.0.wgt'))\n cls.widget_wgt = WgtFile(cls.widget_wgt_file)\n catalogue.add_widget_from_wgt(cls.widget_wgt_file, None, wgt_file=cls.widget_wgt, deploy_only=True)\n\n cls.operator_wgt_file = open(os.path.join(cls.shared_test_data_dir, 'Wirecloud_TestOperator_1.0.zip'), 'rb')\n cls.operator_wgt = WgtFile(cls.operator_wgt_file)\n catalogue.add_widget_from_wgt(cls.operator_wgt_file, None, wgt_file=cls.operator_wgt, deploy_only=True)\n\n @classmethod\n def tearDownClass(cls):\n\n catalogue.wgt_deployer = cls.old_catalogue_deployer\n rmtree(cls.catalogue_tmp_dir, ignore_errors=True)\n\n cls.widget_wgt_file.close()\n cls.operator_wgt_file.close()\n\n super(ParameterizedWorkspaceParseTestCase, cls).tearDownClass()\n\n def setUp(self):\n\n super(ParameterizedWorkspaceParseTestCase, self).setUp()\n\n self.user = User.objects.create_user('test', 'test@example.com', 'test')\n self.workspace = createEmptyWorkspace('Testing', self.user)\n self.template1 = self.read_template('wt1.xml')\n self.template2 = self.read_template('wt2.xml')\n self.rdfTemplate1 = self.read_template('wt1.rdf')\n self.rdfTemplate2 = self.read_template('wt2.rdf')\n self.rdfTemplate3 = self.read_template('wt3.rdf')\n self.rdfTemplate4 = self.read_template('wt4.rdf')\n\n def read_template(self, filename):\n f = codecs.open(os.path.join(os.path.dirname(__file__), 'test-data', filename), 'rb')\n contents = f.read()\n f.close()\n\n return contents\n\n def test_fill_workspace_using_template(self):\n fillWorkspaceUsingTemplate(self.workspace, self.template1)\n data = get_global_workspace_data(self.workspace, self.user).get_data()\n self.assertEqual(self.workspace.name, 'Testing')\n self.assertEqual(len(data['tabs']), 2)\n\n # Workspace template 2 adds a new Tab\n fillWorkspaceUsingTemplate(self.workspace, self.template2)\n data = get_global_workspace_data(self.workspace, self.user).get_data()\n self.assertEqual(len(data['tabs']), 3)\n\n # Check that we handle the case where there are 2 tabs with the same name\n fillWorkspaceUsingTemplate(self.workspace, self.template2)\n data = get_global_workspace_data(self.workspace, self.user).get_data()\n self.assertEqual(len(data['tabs']), 4)\n self.assertNotEqual(data['tabs'][2]['name'], data['tabs'][3]['name'])\n\n def test_build_workspace_from_template(self):\n workspace, _junk = buildWorkspaceFromTemplate(self.template1, self.user)\n get_global_workspace_data(self.workspace, self.user)\n\n wiring_status = json.loads(workspace.wiringStatus)\n self.assertEqual(len(wiring_status['connections']), 1)\n self.assertEqual(wiring_status['connections'][0]['readOnly'], False)\n\n def test_build_workspace_from_rdf_template(self):\n workspace, _junk = buildWorkspaceFromTemplate(self.rdfTemplate1, self.user)\n get_global_workspace_data(self.workspace, self.user)\n\n wiring_status = json.loads(workspace.wiringStatus)\n self.assertEqual(len(wiring_status['connections']), 1)\n self.assertEqual(wiring_status['connections'][0]['readOnly'], False)\n\n def test_build_workspace_from_rdf_template_utf8_char(self):\n workspace, _junk = buildWorkspaceFromTemplate(self.rdfTemplate4, self.user)\n data = get_global_workspace_data(workspace, self.user).get_data()\n\n for t in data['tabs']:\n self.assertEqual(t['name'][0:7], u'Pestaña')\n\n def test_blocked_connections(self):\n workspace, _junk = buildWorkspaceFromTemplate(self.template2, self.user)\n\n wiring_status = json.loads(workspace.wiringStatus)\n self.assertEqual(len(wiring_status['connections']), 1)\n self.assertEqual(wiring_status['connections'][0]['readOnly'], True)\n\n def test_bloqued_connections_rdf(self):\n workspace, _junk = buildWorkspaceFromTemplate(self.rdfTemplate2, self.user)\n\n wiring_status = json.loads(workspace.wiringStatus)\n self.assertEqual(len(wiring_status['connections']), 1)\n self.assertEqual(wiring_status['connections'][0]['readOnly'], True)\n\n def test_complex_workspaces(self):\n template3 = self.read_template('wt3.xml')\n\n workspace, _junk = buildWorkspaceFromTemplate(template3, self.user)\n data = get_global_workspace_data(workspace, self.user).get_data()\n\n self.assertEqual(len(data['tabs']), 4)\n self.assertEqual(data['tabs'][0]['name'], 'Tab')\n self.assertEqual(len(data['tabs'][0]['iwidgets']), 1)\n self.assertEqual(data['tabs'][1]['name'], 'Tab 2')\n self.assertEqual(len(data['tabs'][1]['iwidgets']), 1)\n self.assertEqual(data['tabs'][2]['name'], 'Tab 3')\n self.assertEqual(len(data['tabs'][2]['iwidgets']), 0)\n self.assertEqual(data['tabs'][3]['name'], 'Tab 4')\n self.assertEqual(len(data['tabs'][3]['iwidgets']), 0)\n\n wiring_status = data['wiring']\n self.assertEqual(len(wiring_status['operators']), 1)\n self.assertEqual(len(wiring_status['connections']), 1)\n self.assertEqual(wiring_status['connections'][0]['source']['type'], 'iwidget')\n self.assertEqual(wiring_status['connections'][0]['source']['endpoint'], 'event')\n self.assertEqual(wiring_status['connections'][0]['target']['type'], 'iwidget')\n self.assertEqual(wiring_status['connections'][0]['target']['endpoint'], 'slot')\n\n def test_complex_workspaces_rdf(self):\n workspace, _junk = buildWorkspaceFromTemplate(self.rdfTemplate3, self.user)\n\n data = get_global_workspace_data(workspace, self.user).get_data()\n\n self.assertEqual(len(data['tabs']), 4)\n self.assertEqual(data['tabs'][0]['name'], u'Tab')\n self.assertEqual(len(data['tabs'][0]['iwidgets']), 1)\n self.assertEqual(data['tabs'][1]['name'], u'Tab 2')\n self.assertEqual(len(data['tabs'][1]['iwidgets']), 1)\n self.assertEqual(data['tabs'][2]['name'], u'Tab 3')\n self.assertEqual(len(data['tabs'][2]['iwidgets']), 0)\n self.assertEqual(data['tabs'][3]['name'], u'Tab 4')\n self.assertEqual(len(data['tabs'][3]['iwidgets']), 0)\n\n wiring = data['wiring']\n self.assertEqual(len(wiring['connections']), 1)\n self.assertEqual(wiring['connections'][0]['source']['type'], 'iwidget')\n self.assertEqual(wiring['connections'][0]['source']['endpoint'], 'event')\n self.assertEqual(wiring['connections'][0]['target']['type'], 'iwidget')\n self.assertEqual(wiring['connections'][0]['target']['endpoint'], 'slot')\n","sub_path":"WIRECLOUD/instaladores/wirecloud-0.4.0b1/wirecloud/platform/workspace/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":26046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"378091554","text":"import yaml\nimport subprocess\nfrom datetime import date\n\n\nclass Download:\n def __init__(self):\n with open(\".c42/c42.yml\", \"r\") as yml_file:\n self.config = yaml.load(yml_file, Loader=yaml.FullLoader)\n\n def database(self):\n remote_config = self.config[\"remote\"]\n host = remote_config[\"host\"]\n dump = remote_config[\"dump\"]\n dump_path = remote_config[\"dump_path\"]\n\n if host and dump:\n current_date = date.today().strftime(\"%Y-%m-%d\")\n subprocess.run(\n f\"rsync -avz {host}:{dump_path}/{current_date}/{dump} .c42/tmp/dump.sql.xz\".split())\n print(\"Download complete\")\n\n def media(self):\n remote_config = self.config[\"remote\"]\n host = remote_config[\"host\"]\n media_path = remote_config[\"media\"]\n\n subprocess.run(\n f\"rsync -avz --exclude=cache --exclude=download --exclude=downloadable {host}:{media_path} htdocs/media/\".split())\n","sub_path":"utils/magento/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"39511714","text":"import logging\nimport os\nimport re\nimport subprocess\nfrom virtualenv import create_environment, make_environment_relocatable\n\nLOGGER = logging.getLogger(__name__)\nBASE = os.path.dirname(os.path.abspath(__file__))\nLIB_DIR = os.path.dirname(BASE)\n\n\ndef install_virtualenv(install_dir):\n \"\"\"\n install a virtualenv to the desired directory,\n and returns the path to the executable.\n \"\"\"\n if is_virtualenv(install_dir):\n return\n\n create_environment(install_dir, no_setuptools=False,\n no_pip=False, site_packages=False,\n symlink=False)\n make_environment_relocatable(install_dir)\n return os.path.exists(install_dir, \"bin\")\n\n\nVIRTUALENV_FILES = {\n 'activate file': os.path.join('bin', 'activate')\n}\n\n\ndef is_virtualenv(path):\n \"\"\" validate if the path is already a virtualenv \"\"\"\n for name, venv_path in VIRTUALENV_FILES.items():\n target_path = os.path.join(path, venv_path)\n if not os.path.exists(target_path):\n return False\n return True\n\nINJECT_WRAPPER = \"# URANIUM_INJECT THIS\"\n\nINJECT_MATCH = re.compile(\"(\\n?{0}.*{0}\\n)\".format(INJECT_WRAPPER), re.DOTALL)\n\nINJECT_TEMPLATE = \"\"\"\nsys.executable = os.path.join(base, \"bin\", \"python\")\n\n{0}\n{{body}}\n{0}\n\"\"\".format(INJECT_WRAPPER)\n\nSITE_PY_INJECTION = \"\"\"\n# reshuffling the paths to ensure that distributions in the sandbox\n# always come first\npaths_to_append = [p for p in sys.path if p.startswith(sys.real_prefix)]\nsys.path = [p for p in sys.path if not p.startswith(sys.real_prefix)]\nsys.path += paths_to_append\n\"\"\"\n\n\ndef inject_into_activate_this(venv_root, body):\n \"\"\"\n inject a body into activate_this.py.\n\n this will overwrite any values previously injected into activate_this.\n \"\"\"\n activate_this_file = os.path.join(venv_root, 'bin', 'activate_this.py')\n inject_into_file(activate_this_file, body)\n\n\ndef write_activate_this(venv_root, additional_content=None):\n\n activate_this_template = os.path.join(LIB_DIR, \"scripts\", \"activate_this.py\")\n with open(activate_this_template, \"r\") as fh:\n content = fh.read() + \"\\n\"\n content += (additional_content or \"\")\n\n activate_this_file = os.path.join(venv_root, \"bin\", \"activate_this.py\")\n with open(activate_this_file, \"w+\") as fh:\n fh.write(content)\n\n\ndef inject_sitepy(venv_root):\n site_py_file = _get_site_file_path(venv_root)\n inject_into_file(site_py_file, SITE_PY_INJECTION)\n\n\ndef _get_site_file_path(venv_directory):\n executable = os.path.join(venv_directory, 'bin', 'python')\n return subprocess.Popen(\n [executable, \"-c\", \"import site; print(site.__file__)\"],\n stdout=subprocess.PIPE\n # we strip the last character 'c' in case it's a .pyc file\n # want the .py\n ).communicate()[0].decode('utf-8').rstrip('c\\n')\n\n\ndef inject_into_file(path, body):\n \"\"\" inject into a file \"\"\"\n with open(path) as fh:\n content = fh.read()\n\n content = INJECT_MATCH.sub(\"\", content)\n content += INJECT_TEMPLATE.format(body=body)\n\n with open(path, 'w+') as fh:\n fh.write(content)\n","sub_path":"uranium/lib/virtualenv_utils.py","file_name":"virtualenv_utils.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"166472750","text":"from flask import Flask, redirect, render_template, request, url_for\r\nfrom server import app, question_list, survey_name, n\r\nimport csv\r\n\r\nfrom ExternalDataModel import ExternalDataModel\r\nfrom InternalDataModel import Survey\r\n#from authenticate import login_required\r\n\r\n@app.route('/StudentDashboard',methods = [\"GET\", \"POST\"])\r\n#@login_required(role=\"student\")\r\ndef student_dashboard():\r\n course_surveys = []\r\n open_surveys_info = []\r\n closed_survey_info = []\r\n\r\n # get all the courses the student is enrolled in\r\n studEnrol = ExternalDataModel() #ExternalDataModel is the class name\r\n enrollments = studEnrol.search_user_enrollments(zID) # returned a list of tuples e.g. [(COMP1531, 17S2), ...]\r\n for i in enrollments :\r\n # get all the surveys in that course\r\n course_surveys.append(Survey)\r\n\r\n # get if they are still open or closed\r\n for surveys in course_surveys :\r\n if surveys.status == \"active\" :\r\n open_surveys_info.append(surveys.surveyName)\r\n open_surveys_info.append(surveys.ExpiryDate)\r\n # GET THE URL OF THE SURVEY AS WELL\r\n\r\n elif surveys.status == \"closed\" :\r\n closed_survey_info.append(surveys.surveyName)\r\n closed_survey_info.append(surveys.ExpiryDate)\r\n # GET THE URL OF THE SURVEY AS WELL\r\n\r\n return render_template(\"student_dashboard.html\", open_surveys = open_surveys_info, closed_surveys = closed_survey_info )\r\n\r\n#class ExternalDataModel(object):\r\n# def search_user_enrollments(self,zID):\r\n# query = \"SELECT courseCode, courseTime from ENROLLMENT where zID = '%s' \" %zID\r\n# enrollments = self.dbselect(query)\r\n# return enrollments # it is a list of tuples, e.g. [(COMP1531,17S2),(COMP2521,17S2)]\r\n\r\n#class Survey(Base):\r\n# __tablename__ = 'SURVEY'\r\n# surveyName = Column(String, primary_key=True, nullable=False) # survey name\r\n# status = Column(String, nullable=False) # active, toBeReviewed, closed\r\n# ExpiryDate = Column(String)\r\n\r\n# def __repr__(self):\r\n# return \"[Survey: '%s', Status = '%s', ExpiryDate = '%s']\" %(self.surveyName, self.status, self.ExpiryDate)\r\n\r\n# Need to send details of COURSES the student takes, due date\r\n# Send them all over, and inside the html folder, only show it if the student hasnt done that survey yet..\r\n # Then have to return if they've completed it?\r\n\r\n\"\"\"\r\n1. can see enrolled and active surveys\r\n2. click on the survey links and can fill in the survey\r\n\"\"\"\r\n","sub_path":"student_dashboard.py","file_name":"student_dashboard.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"6719456","text":"import pandas as pd\nimport datetime\nimport time\nimport json\nimport os\nfrom sample_uploader.utils.sample_utils import (\n get_sample_service_url,\n get_sample,\n save_sample,\n compare_samples,\n generate_user_metadata,\n generate_controlled_metadata,\n generate_source_meta,\n update_acls\n)\nfrom sample_uploader.utils.verifiers import verifiers\nfrom sample_uploader.utils.parsing_utils import upload_key_format\n# from sample_uploader.utils.mappings import shared_fields\n\n# These columns should all be in lower case.\nREGULATED_COLS = ['name', 'id', 'parent_id']\nNOOP_VALS = ['ND', 'nd', 'NA', 'na', 'None', 'n/a', 'N/A']\n\n\ndef verify_columns(\n df,\n column_verification_map\n):\n \"\"\"\"\"\"\n cols = df.columns\n for col in cols:\n if column_verification_map.get(col):\n func_str, args = column_verification_map.get(col)\n func = verifiers.get(func_str)\n if not func:\n raise ValueError(f\"no such verifying function {func_str}\")\n try:\n func(df[col], *args)\n except Exception as err:\n raise ValueError(f\"error parsing column \\\"{col}\\\" - {err}\")\n # else:\n # raise ValueError(f\"column {col} not supported in input format.\")\n\n\ndef validate_params(params):\n if not params.get('sample_file'):\n raise ValueError(f\"sample_file argument required in params: {params}\")\n if not params.get('workspace_name'):\n raise ValueError(f\"workspace_name argument required in params: {params}\")\n sample_file = params.get('sample_file')\n if not os.path.isfile(sample_file):\n # try prepending '/staging/' to file and check then\n if os.path.isfile(os.path.join('/staging', sample_file)):\n sample_file = os.path.join('/staging', sample_file)\n else:\n raise ValueError(f\"input file {sample_file} does not exist.\")\n ws_name = params.get('workspace_name')\n return sample_file\n\n\ndef load_file(\n sample_file,\n header_index,\n date_columns\n):\n \"\"\"\"\"\"\n # def find_date_cols(sample_file, date_columns, sep=','):\n # with open(sample_file) as f:\n # for i in range(header_index + 1):\n # col_line = f.readline()\n # cols = [c.lower() for c in col_line.split(sep)]\n # new_dcs = []\n # for dc in date_columns:\n # if dc.lower() in cols:\n # new_dcs.append(dc)\n # return new_dcs\n if sample_file.endswith('.tsv'):\n # df = pd.read_csv(sample_file, sep=\"\\t\", parse_dates=date_columns, header=header_index)\n df = pd.read_csv(sample_file, sep=\"\\t\", header=header_index)\n elif sample_file.endswith('.csv'):\n # df = pd.read_csv(sample_file, parse_dates=date_columns, header=header_index)\n df = pd.read_csv(sample_file, header=header_index)\n elif sample_file.endswith('.xls') or sample_file.endswith('.xlsx'):\n df = pd.read_excel(sample_file, header=header_index)\n else:\n raise ValueError(f\"File {os.path.basename(sample_file)} is not in \"\n f\"an accepted file format, accepted file formats \"\n f\"are '.xls' '.csv' '.tsv' or '.xlsx'\")\n return df\n\n\ndef produce_samples(\n df,\n cols,\n column_groups,\n column_unit_regex,\n sample_url,\n token,\n existing_samples,\n columns_to_input_names\n):\n \"\"\"\"\"\"\n samples = []\n existing_sample_names = {sample['name']: sample for sample in existing_samples}\n\n for idx, row in df.iterrows():\n if row.get('id'):\n # first we check if a 'kbase_sample_id' column is specified\n kbase_sample_id = None\n if row.get('kbase_sample_id'):\n kbase_sample_id = str(row.pop('kbase_sample_id'))\n if 'kbase_sample_id' in cols:\n cols.pop(cols.index('kbase_sample_id'))\n # use name field as name, if there is non-reuse id.\n if row.get('name'):\n name = str(row['name'])\n else:\n name = str(row['id'])\n if row.get('parent_id'):\n parent = str(row.pop('parent_id'))\n if 'parent_id' in cols:\n cols.pop(cols.index('parent_id'))\n if 'id' in cols:\n cols.pop(cols.index('id'))\n if 'name' in cols:\n cols.pop(cols.index('name'))\n\n controlled_metadata = generate_controlled_metadata(\n row,\n column_groups\n )\n sample = {\n 'node_tree': [{\n \"id\": str(row['id']),\n \"parent\": None,\n \"type\": \"BioReplicate\",\n \"meta_controlled\": controlled_metadata,\n \"meta_user\": generate_user_metadata(\n row,\n cols,\n column_groups,\n column_unit_regex\n ),\n 'source_meta': generate_source_meta(\n row,\n controlled_metadata.keys(),\n columns_to_input_names\n )\n }],\n 'name': name,\n }\n prev_sample = None\n if kbase_sample_id:\n prev_sample = get_sample({\"id\": kbase_sample_id}, sample_url, token)\n if name in existing_sample_names and prev_sample['name'] == name:\n # now we check if the sample 'id' and 'name' are the same\n if existing_sample_names[name]['id'] != prev_sample['id']:\n raise ValueError(f\"'kbase_sample_id' and input sample set have different ID's for sample: {name}\")\n elif name in existing_sample_names and name != prev_sample['name']:\n # not sure if this is an error case\n raise ValueError(f\"Cannot rename existing sample from {prev_sample['name']} to {name}\")\n elif name in existing_sample_names:\n prev_sample = get_sample(existing_sample_names[name], sample_url, token)\n if compare_samples(sample, prev_sample):\n if sample.get('name') not in existing_sample_names:\n existing_sample_names[sample['name']] = prev_sample\n continue\n elif name in existing_sample_names:\n existing_sample_names.pop(name)\n\n sample_id, sample_ver = save_sample(sample, sample_url, token, previous_version=prev_sample)\n\n samples.append({\n \"id\": sample_id,\n \"name\": name,\n \"version\": sample_ver\n })\n # check input for any reason to update access control list\n # should have a \"writer\", \"reader\", \"admin\" entry\n writer = row.get('writer')\n reader = row.get('reader')\n admin = row.get('admin')\n if writer or reader or admin:\n acls = {\n \"reader\": [r for r in reader],\n \"writer\": [w for w in writer],\n \"admin\": [a for a in admin]\n }\n update_acls(sample_url, sample_id, acls, token)\n else:\n raise RuntimeError(f\"{row['id']} evaluates as false\")\n # add the missing samples from existing_sample_names\n samples += [existing_sample_names[key] for key in existing_sample_names]\n return samples\n\n\ndef import_samples_from_file(\n params,\n sw_url,\n token,\n column_verification_map,\n column_mapping,\n column_groups,\n date_columns,\n column_unit_regex,\n input_sample_set,\n header_index\n):\n \"\"\"\n import samples from '.csv' or '.xls' files in SESAR format\n \"\"\"\n # verify inputs\n sample_file = validate_params(params)\n ws_name = params.get('workspace_name')\n df = load_file(sample_file, header_index, date_columns)\n # change columns to upload format\n columns_to_input_names = {upload_key_format(c): c for c in df.columns}\n df = df.rename(columns={c: upload_key_format(c) for c in df.columns})\n verify_columns(df, column_verification_map)\n df = df.rename(columns=column_mapping)\n for key in column_mapping:\n if key in columns_to_input_names:\n val = columns_to_input_names.pop(key)\n columns_to_input_names[column_mapping[key]] = val\n df.replace({n:None for n in NOOP_VALS}, inplace=True)\n\n if params['file_format'].upper() in ['SESAR', \"ENIGMA\"]:\n if 'material' in df.columns:\n df.rename({\"material\": params['file_format'].upper() + \":material\"}, inplace=True)\n\n # process and save samples\n cols = list(set(df.columns) - set(REGULATED_COLS))\n sample_url = get_sample_service_url(sw_url)\n samples = produce_samples(\n df,\n cols,\n column_groups,\n column_unit_regex,\n sample_url,\n token,\n input_sample_set['samples'],\n columns_to_input_names\n )\n return {\n \"samples\": samples,\n \"description\": params.get('description')\n }\n","sub_path":"lib/sample_uploader/utils/importer.py","file_name":"importer.py","file_ext":"py","file_size_in_byte":9117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"415957831","text":"# ======================================\r\n# == I M P O R T S ==\r\n# ======================================\r\n# Tell main where to find the libraries\r\n# and other game code. It will search in\r\n# this directory and in Thonny's directory.\r\n\r\n#Import Pygame\r\nimport pygame\r\n#Share all of Pygame's methods and variables\r\n#so we can use them here without worrying about\r\n#telling the code to look in pygame for them\r\n#each time. I think. People online suggest that\r\n#using the * function like this is generally bad\r\n#practice because it makes confusing code when\r\n#different files freely share their internal data.\r\nfrom pygame.locals import *\r\n\r\n# Import math functions\r\nimport math\r\nimport random\r\n\r\n#Import functions that let us read and write\r\n#to .tmx files, which are what Tiled Map Editor\r\n#creates. If you don't have pytmx, it can be\r\n#added from within Thonny under Tools->Manage Packages.\r\nimport pytmx\r\n#Share one of pytmx's methods.Note that we're not using\r\n#the * function this time, so the only methods that\r\n#get imported are those we expressly name.\r\nfrom pytmx.util_pygame import load_pygame\r\n\r\n#Import other game files. These are in the same\r\n#directory as Notmario and exist basically to help\r\n#organize the code.\r\nimport methods\r\n#Again, need to expressly share the methods to which\r\n#we want to have access.\r\nfrom methods import blit_all_tiles\r\nfrom methods import get_tile_properties\r\nfrom methods import play_sound\r\n\r\n#This file contains CONSTANTS. Technically, Python does\r\n#not have a \"constant\" variable type. But, we just use\r\n#regular old variables and treat them as constants. To\r\n#remind us not to change them, we name them in all caps.\r\nimport constants\r\n#More bad practice importing all of constant\r\nfrom constants import *\r\n\r\n#Import the game classes\r\nimport game_objects\r\n\r\n# ============================================\r\n# == C A M E R A ==\r\n# ============================================\r\n\r\nclass Camera(object):\r\n \r\n def __init__ (self):\r\n \r\n # The (x,y) coordinates of the camera. Measured from the CENTER!\r\n # NOT MEASURED FROM TOP LEFT!\r\n self.x = 100\r\n self.y = 300\r\n \r\n # A pointer to the sprite the camera is following\r\n self.following = pygame.sprite\r\n # The (x,y) coordinates that the camera wants to move towards.\r\n self.target_x = 0\r\n self.target_y = 0\r\n \r\n self.zoom = STARTING_CAMERA_ZOOM\r\n self.target_zoom = 1\r\n self.view_width = SCREEN_W\r\n self.view_height = SCREEN_H\r\n \r\n self.camera_speed = 2\r\n \r\n self.camera_scaled = pygame.Surface\r\n\r\n def change_follow(self, target_sprite):\r\n\r\n self.following = target_sprite\r\n target_coords = self.following.getpos()\r\n self.target_x = target_coords[0]\r\n self.target_y = target_coords[1]\r\n \r\n def change_zoom(self, new_target_zoom):\r\n \r\n self.target_zoom = new_target_zoom\r\n \r\n def snap_to_target(self):\r\n\r\n target_coords = self.following.getpos()\r\n self.target_x = target_coords[0]\r\n self.target_y = target_coords[1]\r\n \r\n self.x = self.target_x\r\n self.y = self.target_y\r\n \r\n def snap_to_coords(self, new_x, new_y):\r\n \r\n self.x = new_x\r\n self.y = new_y\r\n \r\n def update(self, map_width, map_height, keys):\r\n \r\n #Change zoom based on keys\r\n if(self.zoom > self.target_zoom): self.zoom -= 1\r\n elif(self.zoom < self.target_zoom): self.zoom += 1\r\n \r\n #Determine size of camera view based on zoom.\r\n self.view_width = SCREEN_W/self.zoom\r\n self.view_height = SCREEN_H/self.zoom\r\n \r\n # Move towards the sprite target\r\n # Currently, assumes that the sprite is one tile wide.\r\n target_coords = self.following.getpos()\r\n self.target_x = target_coords[0]\r\n self.target_y = target_coords[1] \r\n \r\n if(self.x < (self.target_x+TILESIZE/2)): self.x += self.camera_speed\r\n if(self.x > (self.target_x+TILESIZE/2)): self.x -= self.camera_speed \r\n if(self.y < (self.target_y+TILESIZE/2)): self.y += self.camera_speed\r\n if(self.y > (self.target_y+TILESIZE/2)): self.y -= self.camera_speed\r\n \r\n # Don't show area outside the map. This varies depending on size of window.\r\n if(self.xmap_width-(self.view_width/2)):\r\n self.x = map_width-(self.view_width/2)\r\n if(self.ymap_height-(self.view_height/2)):\r\n self.y = map_height-(self.view_height/2)\r\n\r\n def draw(self,pre_render_image):\r\n \r\n # Figure out how much of map image to draw based on zoom\r\n # We're looking at how much of the map we want to actually see.\r\n x1 = self.x - self.view_width/2\r\n y1 = self.y - self.view_height/2\r\n x2 = self.view_width\r\n y2 = self.view_height\r\n \r\n # Now, calculate round integers. We're about to make a temporary\r\n # image that is exactly as large as the section of the screen\r\n # that we want to display. Pygame surfaces only use integers, so\r\n # we need to round off the view sizes, which can be floats.\r\n approx_width = round(self.view_width,0)\r\n approx_height = round(self.view_height,0)\r\n # Create a temporary image just big enough for the part of the map we want.\r\n camera_view = pygame.Surface((approx_width,approx_height))\r\n \r\n # Grab the portion of the map_image caculated by the zoom and load it\r\n # into our custom-sized image.\r\n camera_view.blit( (pre_render_image), #Start with the pre-render image\r\n (0,0), # draw it to the camera starting at corner 0,0\r\n (x1,y1,x2,y2) # Draw the section at the camera view \r\n )\r\n\r\n # Lastly, scale the image back to match the size of the screen showing to\r\n # the player.\r\n self.camera_scaled = pygame.transform.smoothscale(camera_view, (SCREEN_W, SCREEN_H))\r\n \r\n self.camera_scaled.convert\r\n return self.camera_scaled\r\n\r\n \r\n ","sub_path":"camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":6387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"202961804","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index_view, name='index'),\n url(r'^login/$', views.login_view, name='login'),\n url(r'^logout/$', views.logout_view, name='logout'),\n url(r'^register/$', views.register_view, name='register'),\n url(r'^edit_user/$', views.edit_user_view, name='edit_user'),\n]","sub_path":"user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"635236722","text":"from fastapi import FastAPI\nfrom starlette.staticfiles import StaticFiles\nfrom starlette.websockets import WebSocket\nfrom starlette.responses import FileResponse\nimport random\nimport asyncio\n\n\n# run this command: uvicorn main:app --reload\nasync def infinite_random():\n while True:\n yield random.random()\n await asyncio.sleep(3)\n\n\ndef infinite_random2():\n while True:\n yield random.random()\n\n\napp = FastAPI()\n\n\n@app.get(\"/\")\nasync def get():\n return FileResponse('static/index.html')\n\n\n@app.websocket(\"/ws\")\nasync def websocket_endpoint(websocket: WebSocket):\n await websocket.accept()\n\n async def get_message(websocket):\n while True:\n text = await websocket.receive_text()\n await websocket.send_text(f\"Received Text is: {text}\")\n\n async def give_random(websocket):\n while True:\n rn = next(infinite_random2())\n await asyncio.sleep(1)\n await websocket.send_text(f\"Random Number is : {rn}\")\n\n async def handler(websocket):\n msg_task = asyncio.ensure_future(get_message(websocket))\n rn_task = asyncio.ensure_future(give_random(websocket))\n done, pending = await asyncio.wait(\n [msg_task, rn_task], return_when=asyncio.FIRST_COMPLETED\n )\n print(done)\n for task in pending:\n task.cancel()\n\n while True:\n # How to get recieve while sending is going?!? See:\n # https://websockets.readthedocs.io/en/stable/intro.html\n await handler(websocket)\n # text = await websocket.receive_text()\n # data = next(infinite_random2())\n # # print(data)\n # # data = random.random()\n # await asyncio.sleep(1)\n # await websocket.send_text(f\"Random Number is : {data}\")\n # if text:\n","sub_path":"part2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"230672424","text":"import json\nfrom collections import Counter\nfrom os.path import dirname, join\n\nfrom pyfakefs.fake_filesystem import FakeFilesystem, FakeOsModule\n\nfrom word_counter.count import enumerate_files, count_words_in_text, \\\n count_files_in_directory\n\n\ndef test_file_enumeration(mocker):\n # creating fake filesystem.\n fake_fs = FakeFilesystem()\n\n file_list = [\n '/home/archive.zip',\n '/home/text1.txt',\n '/home/text2.txt',\n '/home/not_text.bin',\n '/home/books/book1.txt',\n '/home/books/book2.txt',\n '/home/books/not_text2.bin',\n '/home/books/archive2.zip'\n\n ]\n\n # creating files in fake filesystem.\n\n files_checklist = list()\n for path in file_list:\n fake_fs.create_file(path)\n if path.endswith('.txt') or path.endswith('.zip'):\n files_checklist.append(path)\n # creating and mocking needed fake modules.\n os_module = FakeOsModule(fake_fs)\n\n # mocking needed modules and functions.\n to_patch = {\n 'join': fake_fs.joinpaths,\n 'isdir': fake_fs.isdir,\n 'os': os_module\n }\n\n for name, f in to_patch.items():\n mocker.patch('word_counter.count.{}'.format(name), f)\n\n paths = list(enumerate_files('/'))\n assert Counter(paths) == Counter(files_checklist)\n\n\ndef test_word_count(generate_text):\n text = 'hello world'\n\n assert count_words_in_text(text) == Counter({'hello': 1, 'world': 1})\n\n # empty string\n assert count_words_in_text('') == Counter({})\n\n # zero words text\n assert count_words_in_text(' i 1 f3 . \"/;') == Counter({})\n\n text = \"' `s yea' 'don't -yeah no- ice-cream i I O Open it's a goody-1y day olly's \" \\\n \"free2play a A o i ice can't, won't I'm D R P g6l f1'3p\"\n\n result = count_words_in_text(text)\n assert result == Counter({\n 'yea': 1, \"don't\": 1, 'yeah': 1, 'no': 1, 'ice': 2, 'cream': 1,\n 'I': 1, \"O\": 1, 'open': 1, \"it's\": 1, 'a': 3, 'goody': 1, 'day': 1,\n \"olly's\": 1, \"can't\": 1, \"won't\": 1, \"i'm\": 1\n })\n\n random_text1, counter1 = generate_text(100, 1000)\n random_text2, counter2 = generate_text(100, 1000)\n\n result1 = count_words_in_text(random_text1)\n result2 = count_words_in_text(random_text2)\n\n assert result1 == counter1\n assert result2 == counter2\n\n\ndef test_count_directory():\n \"\"\"\n Apply word counting to test samples and check with pre-counted counter.\n \"\"\"\n samples_path = join(dirname(__file__), 'samples')\n with open(join(samples_path, 'check_list.txt'), 'r') as file:\n check_counter = Counter(json.load(file))\n counter = count_files_in_directory(join(samples_path, 'folder'))\n\n assert counter == check_counter\n","sub_path":"test/test_count.py","file_name":"test_count.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"164867267","text":"import time\nfrom selenium.webdriver.common.by import By\nfrom selenium import webdriver\nimport math\nimport pyperclip\n\nlink = 'http://suninjuly.github.io/alert_accept.html'\nbrowser = webdriver.Chrome()\n\n\ndef calc(x):\n return str(math.log(abs(12 * math.sin(x))))\n\n\ntry:\n browser.get(link)\n button1 = browser.find_element(By.CSS_SELECTOR, 'data_price.btn').click()\n browser.switch_to.alert.accept()\n data_input = browser.find_element(By.ID, 'input_value')\n data_input_x = data_input.text\n data_value = calc(int(data_input_x))\n data_answer = browser.find_element(By.ID, 'answer').send_keys(data_value)\n submit = browser.find_element(By.CSS_SELECTOR, 'data_price.btn').click()\n\n alert = browser.switch_to.alert\n addToClipBoard = alert.text.split(': ')[-1]\n pyperclip.copy(addToClipBoard)\n\n\nfinally:\n time.sleep(5)\n browser.quit()\n","sub_path":"tests/lesson2.3_4.py","file_name":"lesson2.3_4.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"514755976","text":"from pyaudio import PyAudio, paInt16\r\nimport wave\r\n\r\nCHUNK = 1024 # 버퍼\r\nFORMAT = paInt16 # 음질 bit depth\r\nCHANNELS = 1 # 모노 채널\r\n# RATE = 44100 # 샘플 레이트\r\nRATE = 16000 # 카카오 API에서는 16000Hz로 고정, 음성 식별 가능 수준\r\n\r\nRECORD_SECONDS = 5\r\nWAVE_OUTPUT_FILENAME = \"output.wav\"\r\n\r\np = PyAudio()\r\nstream = p.open(\r\n # input_device_index=2, # 16000Hz로 녹음 시에는 기본 녹음 장치를 선택하고 이걸 주석처리해야 함\r\n frames_per_buffer=CHUNK,\r\n format=FORMAT,\r\n channels=CHANNELS,\r\n rate=RATE,\r\n input=True)\r\n\r\n# 음량 조절 명령어 : alsamixer\r\nprint(\"Recording...\")\r\nframes = []\r\nfor i in range(0, int(RATE * RECORD_SECONDS / CHUNK)):\r\n data = stream.read(CHUNK, exception_on_overflow=False)\r\n frames.append(data)\r\nstream.stop_stream()\r\nstream.close()\r\np.terminate()\r\nprint(\"Finished recording!\")\r\n\r\n# wav 파일로 저장\r\nwith wave.open(WAVE_OUTPUT_FILENAME, 'wb') as wf:\r\n wf.setnchannels(CHANNELS)\r\n wf.setsampwidth(p.get_sample_size(FORMAT))\r\n wf.setframerate(RATE)\r\n wf.writeframes(b''.join(frames))\r\nprint(f\"Finished saving {WAVE_OUTPUT_FILENAME}\")\r\n","sub_path":"05. Audio/01. pyaudio/pyaudio_recorder.py","file_name":"pyaudio_recorder.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"67733153","text":"'''Cloc Feature'''\nfrom dffml_feature_git.util.proc import inpath, create, stop\n\nfrom .log import LOGGER\n\nfrom .monthly import GitMonthlyFeature\n\nclass GitClocFeature(GitMonthlyFeature):\n '''\n Count Lines Of Code\n '''\n\n NAME: str = 'cloc'\n BINARY: str = 'cloc'\n FASTER_THAN_CLOC = ['tokei']\n\n def __init__(self):\n super().__init__()\n self.binary = self.BINARY\n if not inpath(self.binary):\n LOGGER.error(\"%s not in path\", self.binary)\n for binary in self.FASTER_THAN_CLOC:\n if inpath(binary):\n self.binary = binary\n\n async def applicable(self, data):\n return inpath(self.binary) \\\n and await GitMonthlyFeature.applicable(self, data)\n\n async def git_parse(self, data):\n if not data.temp.get('cloc_data', False):\n data.temp.setdefault('cloc_data', [{'sum': 0}] * self.LENGTH)\n await super().git_parse(data)\n\n async def month_parse(self, data, i):\n parsed = data.temp.get('cloc_data')\n proc = await create(self.binary, data.git.cwd)\n cols = []\n while not proc.stdout.at_eof():\n line = (await proc.stdout.readline()).decode().split()\n if not line or line[0].startswith('-'):\n continue\n LOGGER.debug('%s line: %r', self.binary, line)\n if line[0].lower().startswith('lang'):\n cols = [cat.lower() for cat in line[1:]]\n # Tokei -> cloc compatibility\n if 'comments' in cols:\n cols[cols.index('comments')] = 'comment'\n continue\n if cols:\n header_cols = [word for word in line if not word.isdigit()]\n header = ''.join([c for c in '_'.join(header_cols).lower() \\\n if c.isalpha() or c == '_'])\n # Tokei -> cloc compatibility\n if header == 'total':\n header = 'sum'\n parsed[i][header] = dict(zip(cols,\n map(int, line[len(header_cols):])))\n LOGGER.debug('parsed[%d]: %r', i, parsed[i])\n await stop(proc)\n\n async def calc(self, data):\n try:\n return [int(100 * month['sum']['comment'] / \\\n (month['sum']['comment'] + month['sum']['code']))\n for month in (data.temp.get('cloc_data'))]\n except ZeroDivisionError:\n return [0 for month in (data.temp.get('cloc_data'))]\n","sub_path":"feature/git/dffml_feature_git/feature/cloc.py","file_name":"cloc.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"105901822","text":"\n\ndef sortlevel(self, level=0, ascending=True, sort_remaining=True):\n '\\n Sort MultiIndex at the requested level. The result will respect the\\n original ordering of the associated factor at that level.\\n\\n Parameters\\n ----------\\n level : list-like, int or str, default 0\\n If a string is given, must be a name of the level\\n If list-like must be names or ints of levels.\\n ascending : boolean, default True\\n False to sort in descending order\\n Can also be a list to specify a directed ordering\\n sort_remaining : sort by the remaining levels after level.\\n\\n Returns\\n -------\\n sorted_index : MultiIndex\\n '\n from pandas.core.groupby import _indexer_from_factorized\n if isinstance(level, (compat.string_types, int)):\n level = [level]\n level = [self._get_level_number(lev) for lev in level]\n sortorder = None\n if isinstance(ascending, list):\n if (not (len(level) == len(ascending))):\n raise ValueError('level must have same length as ascending')\n from pandas.core.groupby import _lexsort_indexer\n indexer = _lexsort_indexer(self.labels, orders=ascending)\n else:\n labels = list(self.labels)\n shape = list(self.levshape)\n primary = tuple((labels.pop((lev - i)) for (i, lev) in enumerate(level)))\n primshp = tuple((shape.pop((lev - i)) for (i, lev) in enumerate(level)))\n if sort_remaining:\n primary += (primary + tuple(labels))\n primshp += (primshp + tuple(shape))\n else:\n sortorder = level[0]\n indexer = _indexer_from_factorized(primary, primshp, compress=False)\n if (not ascending):\n indexer = indexer[::(- 1)]\n indexer = _ensure_platform_int(indexer)\n new_labels = [lab.take(indexer) for lab in self.labels]\n new_index = MultiIndex(labels=new_labels, levels=self.levels, names=self.names, sortorder=sortorder, verify_integrity=False)\n return (new_index, indexer)\n","sub_path":"Data Set/bug-fixing-2/bf1a5961a09a6f5237a681f9f1c9a698b1a13918--bug.py","file_name":"bf1a5961a09a6f5237a681f9f1c9a698b1a13918--bug.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"74609204","text":"# -*- coding: utf-8 -*-\n\"\"\"\n test-txtrader.py\n --------------\n\n TxTrader unit/regression test script\n\n Copyright (c) 2016 Reliance Systems Inc. \n Licensed under the MIT license. See LICENSE for details.\n\n\"\"\"\nfrom txtrader.client import API\nimport subprocess\nimport os\nimport signal\nimport time\n\nimport simplejson as json\nfrom pprint import pprint\nimport pytest\n\n\nTEST_ALGO_ROUTE='{\"TEST-ATM-ALGO\":{\"STRAT_ID\":\"BEST\",\"BOOKING_TYPE\":\"3\",\"STRAT_TIME_TAGS\":\"168;126\",\"STRAT_PARAMETERS\":{\"99970\":\"2\",\"99867\":\"N\",\"847\":\"BEST\",\"90057\":\"BEST\",\"91000\":\"4.1.95\"},\"ORDER_FLAGS_3\":\"0\",\"ORDER_CLONE_FLAG\":\"1\",\"STRAT_TARGET\":\"ATDL\",\"STRATEGY_NAME\":\"BEST\",\"STRAT_REDUNDANT_DATA\":{\"UseStartTime\":\"false\",\"UseEndTime\":\"false\",\"cConditionalType\":\"{NULL}\"},\"STRAT_TIME_ZONE\":\"America/New_York\",\"STRAT_TYPE\":\"COWEN_ATM_US_EQT\",\"STRAT_STRING_40\":\"BEST\",\"UTC_OFFSET\":\"-240\"}}'\n\ntestmode = 'RTX'\n\nfrom server_test import Server\n\n@pytest.fixture(scope='module')\ndef api():\n with Server() as s:\n yield s.init()\n\ndef dump(label, o):\n print('%s:\\n%s' % (label, json.dumps(o, indent=2, separators=(',', ':'))))\n\ndef test_init(api):\n print()\n print('test_init checking api')\n assert api \n print('waiting 1 second...')\n time.sleep(1)\n print('done')\n\ndef test_stock_prices(api):\n\n s = api.add_symbol('IBM')\n assert s\n\n p = api.query_symbol('IBM')\n assert p\n\n assert type(p) == dict\n print(repr(p))\n\n tdata = [\n ('symbol', unicode, True),\n ('fullname', unicode, True),\n ('last', float, True),\n ('size', int, True),\n ('volume', int, True),\n ('close', float, True)\n ]\n\n for key, _type, required in tdata:\n assert key in p.keys()\n assert type(p[key]) == _type\n if required:\n assert p[key]\n\n r = api.query_symbol_data('IBM')\n assert r\n dump('raw data for IBM', r)\n\n l = api.query_symbols()\n assert l\n dump('symbol list', l)\n assert l == ['IBM']\n\n s = api.add_symbol('TSLA')\n assert s\n dump('add TSLA', s)\n s = api.add_symbol('GOOG')\n assert s\n dump('add GOOG', s)\n s = api.add_symbol('AAPL')\n assert s\n dump('add AAPL', s)\n\n l = api.query_symbols()\n assert set(l) == set(['IBM', 'TSLA', 'GOOG', 'AAPL'])\n dump('symbol list', l)\n\n s = api.del_symbol('TSLA')\n assert s\n dump('del TSLA', s)\n\n l = api.query_symbols()\n assert set(l) == set(['IBM', 'GOOG', 'AAPL'])\n dump('symbol list', l)\n\n print(repr(l))\n\ndef test_buy_sell(api):\n print()\n #account = api.account\n #print('account=%s' % account)\n #api.set_account(account)\n print('buying IBM')\n o = api.market_order('IBM', 100)\n assert o\n assert type(o) == dict\n assert 'permid' in o.keys()\n assert 'status' in o.keys()\n dump('market_order(IBM,100)', o)\n\n print('selling IBM')\n\n o = api.market_order('IBM', -100)\n assert o\n assert type(o) == dict\n assert 'permid' in o.keys()\n assert 'status' in o.keys()\n dump('market_order(IBM,100)', o)\n\ndef test_set_order_route(api):\n print()\n oldroute = api.get_order_route()\n assert type(oldroute) == dict\n assert oldroute.keys() == ['DEMOEUR']\n r0 = 'DEMO'\n r1 = {'DEMO':None} \n r2 = {'DEMO': {'key1':'value1', 'key2':'value2'}}\n r3 = TEST_ALGO_ROUTE\n for rin, rout in [ (r0, r1), (r1, r1), (r2, r2), (json.dumps(r0), r1), (json.dumps(r1), r1), (json.dumps(r2), r2), (r3, json.loads(r3))]: \n print('set_order_route(%s)' % repr(rin))\n assert api.set_order_route(rin) == rout\n assert api.get_order_route() == rout\n assert api.set_order_route(oldroute) == oldroute\n\n\ndef test_partial_fill(api):\n print()\n oldroute = api.get_order_route()\n assert api.set_order_route('DEMO')\n assert api.get_order_route() == {'DEMO': None}\n quantity = 1000\n symbol = 'COWN'\n print('buying %d %s' % (quantity, symbol))\n p = api.add_symbol(symbol)\n assert p\n o = api.market_order(symbol, quantity)\n assert o\n assert 'permid' in o.keys()\n assert 'status' in o.keys()\n assert not o['status'] == 'Filled'\n oid = o['permid']\n print('oid=%s' % oid)\n partial_fills = 0\n while o['status'] != 'Filled':\n o = api.query_order(oid)\n #o={'status':'spoofed','TYPE':'spoofed'}\n #pprint(o)\n status = o['status']\n filled = o['filled'] if 'filled' in o.keys() else 0\n remaining = o['remaining'] if 'remaining' in o.keys() else 0\n if (int(filled) > 0) and (int(remaining) > 0) and (int(filled) < quantity):\n partial_fills += 1 \n average_price = o['avgfillprice'] if 'avgfillprice' in o.keys() else None\n print('status=%s filled=%s remaining=%s average_price=%s type=%s' % (status, filled, remaining, average_price, o['TYPE']))\n assert not (status=='Filled' and filled < quantity)\n assert status in ['Submitted', 'Pending', 'Filled']\n time.sleep(1)\n assert partial_fills\n o = api.market_order(symbol, quantity*-1)\n assert api.set_order_route(oldroute)\n\ndef test_status(api):\n assert api.status() == 'Up'\n\ndef test_uptime(api):\n uptime = api.uptime()\n assert uptime\n print('uptime: %s' % repr(uptime))\n assert type(uptime) == str or type(uptime) == unicode\n\ndef test_version(api):\n assert api.version()\n\ndef test_symbol_price(api):\n symbols = api.query_symbols()\n assert type(symbols)==list\n if 'AAPL' in symbols:\n ret = api.del_symbol('AAPL')\n assert ret\n symbols = api.query_symbols()\n assert type(symbols) == list\n assert 'AAPL' not in symbols\n price = api.query_symbol('AAPL')\n assert not price\n\n ret = api.add_symbol('AAPL')\n assert ret\n\n p = api.query_symbol('AAPL')\n assert p \n assert type(p) == dict\n assert p['symbol'] == 'AAPL'\n\ndef test_query_accounts(api):\n test_account = api.account\n\n accounts = api.query_accounts()\n\n assert type(accounts) == list\n assert accounts\n\n for a in accounts:\n assert type(a) == str or type(a) == unicode \n\n assert test_account in accounts\n ret = api.set_account(test_account)\n assert ret\n\n ret = api.query_account('b.b.b.INVALID_ACCOUNT')\n assert ret == None\n\n ret = api.query_account(test_account, 'INVALID_FIELD')\n assert ret == None\n\n ret = api.query_account(test_account, 'INVALID_FIELD_1,INVALID_FIELD_2')\n assert ret == None\n\n #print('query_account(%s)...' % a)\n data = api.query_account(test_account)\n #print('account[%s]: %s' % (a, repr(data)))\n assert data\n assert type(data)==dict\n\n fields = [k for k in data.keys() if not k.startswith('_')]\n\n if testmode == 'RTX':\n field = 'EXCESS_EQ'\n elif testmode == 'TWS':\n field = 'LiquidationValue'\n\n # txtrader is expected to set the value _cash to the correct field \n assert '_cash' in data.keys()\n assert float(data['_cash']) == round(float(data[field]),2)\n \n sdata = api.query_account(test_account, field) \n assert sdata\n assert type(sdata)==dict\n assert field in sdata.keys()\n\n rfields = ','.join(fields[:3])\n print('requesting fields: %s' % rfields)\n sdata = api.query_account(test_account, rfields)\n print('got %s' % repr(sdata))\n assert sdata\n assert type(sdata)==dict\n for field in rfields.split(','):\n assert field in sdata.keys()\n assert set(rfields.split(',')) == set(sdata.keys())\n \n\n #print('account[%s]: %s' % (a, repr(sdata)))\n\ndef _wait_for_fill(api, oid, return_on_error=False):\n print('Waiting for order %s to fill...' % oid)\n done = False\n last_status = ''\n while not done:\n o = api.query_order(oid)\n if last_status != o['status']:\n last_status = o['status'] \n print('order status: %s' % o['status'])\n if return_on_error and o['status'] == 'Error':\n return\n assert o['status'] != 'Error'\n if o['status'] == 'Filled':\n done = True\n else:\n time.sleep(1)\n\ndef _position(api, account):\n pos = api.query_positions()\n assert type(pos) == dict\n assert account in pos.keys()\n if account in pos:\n p=pos[account]\n assert type(p) == dict\n else: \n p={}\n return p\n\ndef _market_order(api, symbol, quantity, return_on_error=False):\n print('Sending market_order(%s, %d)...' % (symbol, quantity))\n o = api.market_order(symbol, quantity)\n print('market_order returned %s' % repr(o))\n assert o \n assert 'permid' in o.keys()\n assert 'status' in o.keys()\n oid = o['permid']\n assert type(oid) == str or type(oid) == unicode\n print('market_order(%s,%s) returned oid=%s status=%s' % (symbol, quantity, oid, o['status']))\n _wait_for_fill(api, oid, return_on_error) \n return oid\n\ndef test_trades(api):\n\n account = api.account\n\n oid = _market_order(api, 'AAPL',1)\n\n p = _position(api, account)\n if 'AAPL' in p.keys() and p['AAPL']!=0:\n oid = _market_order(api, 'AAPL', -1 * p['AAPL'])\n ostat = api.query_order(oid)\n assert ostat\n assert type(ostat) == dict\n assert 'permid' in ostat.keys()\n\n p = _position(api, account)\n assert not 'AAPL' in p.keys() or p['AAPL']==0\n\n oid = _market_order(api, 'AAPL', 100)\n\n p = _position(api, account)\n assert p\n assert type(p) == dict\n assert 'AAPL' in p.keys()\n \n assert p['AAPL'] == 100\n\n oid = _market_order(api, 'AAPL',-10)\n\n p = _position(api, account)\n assert 'AAPL' in p.keys()\n \n assert p['AAPL'] == 90\n\n@pytest.mark.staged\ndef test_staged_trades(api):\n\n t = api.stage_market_order('TEST.%s' % str(time.time()), 'GOOG', 10)\n assert t\n assert type(t) == dict\n assert 'permid' in t.keys()\n oid = t['permid']\n print('Created staged order %s, awaiting user execution from RealTick' % oid)\n _wait_for_fill(api, oid)\n\n\n@pytest.mark.staged\ndef test_staged_trade_cancel(api):\n t = api.stage_market_order('TEST.%s' % str(time.time()), 'INTC', 10)\n assert t\n assert type(t) == dict\n assert 'permid' in t.keys()\n oid = t['permid']\n print('Created staged order %s, awaiting user cancellation from RealTick' % oid)\n _wait_for_fill(api, oid, True)\n t = api.query_order(oid)\n assert t\n assert type(t)==dict\n assert 'status' in t.keys()\n assert t['status'] == 'Error'\n assert 'REASON' in t.keys()\n assert t['REASON'].lower().startswith('user cancel')\n print('detected user cancel of %s' % oid)\n\n@pytest.mark.staged\ndef test_staged_trade_execute(api):\n trade_symbol = 'AAPL'\n trade_quantity = 10\n t = api.stage_market_order('TEST.%s' % str(time.time()), trade_symbol, trade_quantity)\n assert t\n assert type(t) == dict\n assert 'permid' in t.keys()\n oid = t['permid']\n status = t['status']\n print('Created staged order %s with status %s, waiting 5 seconds, then changing order to auto-execute' % (oid, status))\n time.sleep(5)\n status = api.query_order(oid)['status']\n print('cancelling order %s with status=%s...' % (oid, status))\n r = api.cancel_order(oid)\n print('cancel returned %s' % repr(r))\n assert r\n _wait_for_fill(api, oid, True)\n o = api.query_order(oid)\n print('order: %s' % o)\n print('cancel confirmed oid=%s, status=%s' % (oid, o['status']))\n t = api.market_order(trade_symbol, trade_quantity)\n assert t\n assert type(t)==dict\n new_oid = t['permid']\n assert new_oid != oid\n print('submitted trade as new order %s' % new_oid)\n _wait_for_fill(api, new_oid)\n print('detected execution of %s' % new_oid)\n o = api.query_order(new_oid)\n assert o['status']=='Filled'\n\ndef test_query_orders(api):\n orders = api.query_orders()\n assert orders != None\n assert type(orders) == dict\n\ndef test_trade_and_query_orders(api):\n oid = _market_order(api, 'AAPL',1)\n orders = api.query_orders()\n assert orders != None\n assert type(orders) == dict\n assert oid in orders.keys()\n assert type(orders[oid]) == dict\n assert orders[oid]['permid'] == oid\n assert 'status' in orders[oid]\n\ndef test_query_executions(api):\n execs = api.query_executions()\n assert type(execs) == dict\n assert execs != None\n\ndef test_trade_and_query_executions_and_query_order(api):\n oid = _market_order(api, 'AAPL',1)\n oid = str(oid)\n #print('oid: %s' % oid)\n execs = api.query_executions()\n #print('execs: %s' % repr(execs))\n assert type(execs) == dict\n assert execs != None\n found=None\n for k,v in execs.items():\n #print('----------------')\n #print('k=%s' % k)\n #print('v=%s' % repr(v))\n #print('%s %s %s' % (found, v['permid'], oid))\n if str(v['permid']) == oid:\n found = k\n break\n assert found\n assert str(execs[k]['permid']) == oid\n\n o = api.query_order(oid)\n assert o\n assert oid == o['permid']\n assert 'status' in o\n assert o['status']=='Filled'\n\n\"\"\"\n ALGO ORDER fields per 2018-07-24 email from Raymond Tsui (rtsui@ezsoft.com)\n\n\"\"\"\n@pytest.mark.algo\ndef test_algo_order(api):\n print()\n\n ret = api.get_order_route()\n assert type(ret) == dict\n assert len(ret.keys()) == 1\n oldroute = ret.keys()[0] \n assert type(oldroute) == str or type(oldroute) == unicode\n assert ret[oldroute] == None\n assert oldroute in ['DEMO', 'DEMOEUR']\n\n algo_order_parameters = {\n \"STRAT_ID\": \"BEST\",\n \"BOOKING_TYPE\": 3,\n \"STRAT_TIME_TAGS\": \"168;126\",\n \"STRAT_PARAMETERS\": {\n \"99970\": \"2\",\n \"99867\": \"N\",\n \"847\": \"BEST\",\n \"90057\": \"BEST\",\n \"91000\": \"4.1.95\"\n },\n \"ORDER_FLAGS_3\": 0,\n \"ORDER_CLONE_FLAG\": 1,\n \"STRAT_TARGET\": \"ATDL\",\n \"STRATEGY_NAME\": \"BEST\",\n \"STRAT_REDUNDANT_DATA\": {\n \"UseStartTime\": \"false\",\n \"UseEndTime\": \"false\",\n \"cConditionalType\": \"{NULL}\"\n },\n \"STRAT_TIME_ZONE\": \"America/New_York\",\n \"STRAT_TYPE\": \"COWEN_ATM_US_EQT\",\n \"STRAT_STRING_40\": \"BEST\",\n \"UTC_OFFSET\": \"-240\"\n }\n route = 'TEST-ATM-ALGO'\n p = {route: algo_order_parameters}\n\n ret = api.set_order_route(p)\n assert ret\n\n assert api.get_order_route() == p\n\n oid = _market_order(api, 'INTC', 100)\n\n assert api.query_order(oid)['status'] == 'Filled'\n\n assert api.set_order_route(oldroute)\n\ndef test_trade_submission_error_bad_symbol(api):\n o = api.market_order('BADSYMBOL', 100)\n assert o\n assert o['status'] == 'Error'\n #print('order: %s' % repr(o))\n\ndef test_trade_submission_error_bad_quantity(api):\n o = api.market_order('AAPL', 0)\n assert o\n if o['status'] != 'Error':\n oid = o['permid']\n _wait_for_fill(api, oid, True)\n o = api.query_order(oid)\n assert o['status'] == 'Error'\n #print('order: %s' % repr(o))\n\n#TODO: test other order types\n\n# def json_limit_order(self, args, d):\n# \"\"\"limit_order('symbol', price, quantity) => {'field':, data, ...} \n# def json_stop_order(self, args, d): \n# \"\"\"stop_order('symbol', price, quantity) => {'field':, data, ...} \n# def json_stoplimit_order(self, args, d): \n# \"\"\"stoplimit_order('symbol', stop_price, limit_price, quantity) => {'field':, data, ...} \n\n@pytest.mark.bars\ndef dont_test_bars(api): \n sbar = '2017-07-06 09:30:00' \n ebar = '2017-07-06 09:40:00' \n ret = api.query_bars('SPY', 1, sbar, ebar) \n assert ret \n assert type(ret) == list \n assert ret[0]=='OK' \n bars = ret[1] \n assert bars \n assert type(bars) == list \n for bar in bars:\n assert type(bar) == dict\n assert 'date' in bar\n assert 'open' in bar\n assert 'high' in bar\n assert 'low' in bar\n assert 'close' in bar\n assert 'volume' in bar\n #print('%s %s %s %s %s %s' % (bar['date'], bar['open'], bar['high'], bar['low'], bar['close'], bar['volume']))\n\ndef test_cancel_order(api):\n ret = api.cancel_order('000')\n assert ret\n\ndef test_global_cancel(api):\n ret = api.global_cancel()\n assert ret\n\ndef json_gateway_logon(api):\n ret = api.gateway_logon('user', 'passwd')\n assert ret\n\ndef test_gateway_logoff(api):\n ret = api.gateway_logoff()\n assert ret\n\ndef test_set_primary_exchange(api):\n if testmode == 'RTX':\n exchange = 'NAS'\n elif testmode == 'TWS':\n exchange = 'NASDAQ'\n assert api.set_primary_exchange('MSFT', exchange)\n assert api.add_symbol('MSFT')\n assert api.query_symbol('MSFT')\n\ndef test_help(api):\n help = api.help()\n assert help == None\n","sub_path":"txtrader/txtrader_test.py","file_name":"txtrader_test.py","file_ext":"py","file_size_in_byte":16488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"257183321","text":"\n\npeople = {\"name\": [\"Marina\", \"Robert\", \"Mike\", \"Siri\", \"Alexa\", \"Betty\"],\n \"age\": [20, 23, 17, 45, 3, 14]}\n\nempty_dict = {\"name\": [], \"age\": []}\n\n# Question 1\n# function that updates the dictionary with the given name and age\n\ndef add_new_person(dict, lst):\n \"\"\"Adds new person to the dictionary\n\n >>> people1 = {\"name\": [\"Marina\", \"Robert\", \"Mike\", \"Siri\", \"Alexa\", \"Betty\"],\\\n \"age\": [20, 23, 17, 41, 3, 14]}\n >>> person = [\"Lucy\", 15]\n >>> add_new_person(people1, person)\n >>> people1\n {'name': ['Marina', 'Robert', 'Mike', 'Siri', 'Alexa', 'Betty', 'Lucy'], 'age': [20, 23, 17, 41, 3, 14, 15]}\n \n >>> people2 = {'name': [], 'age': []}\n >>> another_person = ['Joey', 2]\n >>> add_new_person(people2, another_person)\n >>> people2 \n {'name': ['Joey'], 'age': [2]}\n \"\"\"\n for i in range(len(dict)):\n key = list(dict.keys())[i]\n dict[key] = dict[key] + [lst[i]]\n\n# Question 2. Dictionary to a tuple of lists\n\ndef from_dict_to_tuple(dict):\n \"\"\" Converts dictionary in a tuple of lists\n >>> sorted(from_dict_to_tuple(people), key=lambda tup: tup[1])\n [['Alexa', 3], ['Betty', 14], ['Mike', 17], ['Marina', 20], ['Robert', 23], ['Siri', 45]]\n \n >>> tutors = {'name': ['Rajit', 'Joey'], 'age': [21, 19]}\n >>> sorted(from_dict_to_tuple(tutors), key=lambda tup: tup[1])\n [['Joey', 19], ['Rajit', 21]]\n\n >>> from_dict_to_tuple(empty_dict)\n ()\n \"\"\"\n values = [dict[i] for i in dict]\n\n key = list(dict.keys())[0]\n tuple_output = []\n for i in range(len(dict[key])):\n tuple_output.append([values[0][i], values[1][i]])\n\n return(tuple(tuple_output))\n \n\n\n# Question 3 Fiter the tuple of lists by age\n\n\ndef filter_age(lists, threshold):\n \"\"\"Returns filtered tuple of lists\n >>> lists = from_dict_to_tuple(people)\n >>> sorted(filter_age(lists, 23), key=lambda tup: tup[1])\n [['Alexa', 3], ['Betty', 14], ['Mike', 17], ['Marina', 20], ['Robert', 23]]\n\n >>> filter_age(lists, 1)\n ()\n \n >>> len(filter_age(lists, 45))\n 6\n \"\"\"\n count = []\n for i in lists:\n if i[1] <= threshold:\n count.append(i)\n\n return tuple(count)\n\n\n# Question 4 Put it back in a dictionary\n\ndef names_are_back(lists):\n \"\"\"Returns a dictionary with filtered people\n >>> lists = from_dict_to_tuple(people)\n >>> lists = filter_age(lists, 23)\n >>> new_dictionary = names_are_back(lists)\n >>> 'Marina' in new_dictionary['name']\n True\n\n >>> 45 in new_dictionary['age']\n False\n\n >>> new_dictionary['age'].sort()\n >>> new_dictionary['age']\n [3, 14, 17, 20, 23]\n\n >>> lists = from_dict_to_tuple(people)\n >>> lists = filter_age(lists, 45)\n >>> len(names_are_back(lists)['name'])\n 6\n\n \"\"\"\n keys = list(people.keys())\n new_dict = {}\n for i in keys:\n new_dict[i] = []\n\n for pairs in lists:\n for j in range(len(pairs)):\n new_dict[keys[j]].append(pairs[j])\n\n # for i in lists:\n # new_dict[keys[0]].append(i[0])\n # new_dict[keys[1]].append(i[1])\n\n return new_dict\n\n\n# Question 5 From dictionary to pandas\n\nimport pandas as pd\nimport numpy as n\n\ndef create_df(dict):\n \"\"\"Converts dict to a DataFrame\n >>> df = create_df(people)\n >>> df.sort_values(ascending=False, by='age').iloc[0,:]['name']\n 'Siri'\n >>> df.sort_values(ascending=True, by='age').iloc[0,:]['name']\n 'Alexa'\n \"\"\"\n return pd.DataFrame(data=dict)\n\n\n# Question 6\n\ndef filter_using_pandas(dict, threshold):\n \"\"\"Returns data frame with ages below the threshold \n >>> nf = filter_using_pandas(people, 23)\n >>> nf.sort_values(ascending=False, by='age').iloc[0,:]['name']\n 'Robert'\n >>> nf.sort_values(ascending=True, by='age').iloc[0,:]['name']\n 'Alexa'\n \"\"\"\n data_frame = create_df(dict)\n return data_frame[data_frame['age'] <= threshold]\n\n\n# Question 7 Re-write using lambdas\n\nfrom Lecture7_solution import *\n\ndef closer_city_lambda(lat, lon, city1, city2):\n \"\"\" Returns the name of either city1 or city2, whichever is closest\n to coordinate (lat, lon).\n\n >>> san_diego = make_city('San Diego', 32.71, 117.16)\n >>> los_ang = make_city('Los Angeles', 34.0522, 118.24)\n >>> closer_city_lambda(33.68, 117.82, san_diego, los_ang)\n 'Los Angeles'\n >>> bucharest = make_city('Bucharest', 44.43, 26.10)\n >>> vienna = make_city('Vienna', 48.20, 16.37)\n >>> closer_city_lambda(32.71, 117.16, bucharest, vienna)\n 'Bucharest'\n \"\"\"\n return (lambda temp: distance(temp, city1) > distance(temp, city2) and get_name(city2) or get_name(city1))(make_city(\"temp\", lat, lon))\n\n","sub_path":"lab05/Lab05.py","file_name":"Lab05.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"573436042","text":"import re\nfrom collections import namedtuple\nfrom ROOT import TGraphAsymmErrors, TVector, TCanvas, TPad, TGaxis, TH2F, kYellow, kBlue\n\n\n# n = len(nps)\n\n# premupull = TVector(5*n+4)\n# premuerr = TVector(5*n+4)\n# postmupull = TVector(5*n+4)\n# postmuerr = TVector(5*n+4)\n\n\n# pos = TVector(5*n+4)\n# hw = TVector(5*n+4)\n# null = TVector(5*n+4)\n\n# for i, name in enumerate(sorted(nps.keys())):\n# i1 = 5*i + 2\n# i2 = 5*i + 3\n# i3 = 5*i + 4\n# vals = nps[name]\n\n# premupull[i1] = vals[6]/maxerr\n# premuerr[i1] = vals[7]/maxerr\n\n# prel[i2] = vals[0]\n# prepull[i2] = vals[1]\n# preh[i2] = vals[2]\n# postl[i2] = vals[3]\n# postpull[i2] = vals[4]\n# posth[i2] = vals[5]\n\n# postmupull[i3] = vals[8]/maxerr\n# postmuerr[i3] = vals[9]/maxerr\n\n# for i in xrange(5*n):\n# pos[i] = i+1\n# hw[i] = 1\n\n\n# c1 = TCanvas('c', '', 1200, 2000)\n\n# nppad = TPad('nppad', '', 0.2, 0, 1, 1)\n# nppad.Draw()\n# nppad.cd()\n# npframe = TH2F('ax', '', 1, -2, 2, n*5+4, 0, n*5+4)\n# npframe.SetStats(0)\n# for i, name in enumerate(sorted(nps.keys())):\n# npframe.GetYaxis().SetBinLabel(5*i+4, name)\n# npframe.Draw()\n\n# nppre = TGraphAsymmErrors(prepull, pos, prel, preh, null, null)\n# nppre.SetLineStyle(7);\n# nppre.SetLineWidth(3);\n# nppre.Draw(\"p\")\n\n# nppost = TGraphAsymmErrors(postpull, pos, postl, posth, null, null)\n# nppost.SetLineWidth(3);\n# nppost.Draw(\"p\")\n\n# c1.cd()\n# mupad = TPad('mupad', '', 0.2, 0, 1, 1)\n# mupad.SetFillStyle(4000)\n# mupad.SetFrameFillStyle(4000)\n# mupad.Draw()\n# mupad.cd()\n\n# mupre = TGraphAsymmErrors(premupull, pos, premuerr, premuerr, hw, hw)\n# mupre.SetFillColor(9)\n\n# mupost = TGraphAsymmErrors(postmupull, pos, postmuerr, postmuerr, hw, hw)\n# mupost.SetFillColor(5)\n\n# muframe = mupad.DrawFrame(-2, 0, 2, n*5+4)\n\n# muframe.GetXaxis().SetLabelOffset(99)\n# muframe.GetXaxis().SetTickSize(0)\n# muframe.GetYaxis().SetLabelOffset(99)\n\n# mupre.Draw(\"E2\")\n# mupost.Draw(\"E2\")\n\n# axis = TGaxis(-2, n*5+4, 2, n*5+4, -2*maxerr, 2*maxerr, 510, '-')\n# axis.Draw()\n\n\n\n\n\n\n\ncv = TCanvas('c', '', 1200, 2000)\npad1 = TPad('pad1', '', 0, 0, 1, 1)\npad1.SetLeftMargin(0.2)\npad2 = TPad('pad2', '', 0, 0, 1, 1)\npad2.SetLeftMargin(0.2)\n_obj = []\n\ndef read_file(fname):\n \n Entry = namedtuple('Entry', ['np_prefit_pull', 'np_postfit_pull',\n 'np_prefit_lo', 'np_prefit_up', 'np_postfit_lo', 'np_postfit_up',\n 'mu_prefit_lo', 'mu_prefit_up', 'mu_postfit_lo', 'mu_postfit_up'])\n\n stats = {}\n\n with open(fname, 'r') as f:\n for line in f:\n if not line.startswith('alpha'):\n continue\n items = line.split()\n name = items[0][6:]\n data = [float(v) for v in items[1:]]\n stats[name] = Entry(mu_prefit_up = data[0],\n mu_prefit_lo = data[1], \n mu_postfit_up = data[2],\n mu_postfit_lo = data[3],\n np_prefit_up = data[4],\n np_prefit_pull = data[5],\n np_prefit_lo = data[6],\n np_postfit_up = data[7],\n np_postfit_pull = data[8],\n np_postfit_lo = data[9])\n \n return stats\n\n\ndef plot_np(stats):\n\n n = len(stats)\n nbins = 5*n + 4\n\n pre_lo = TVector(nbins)\n pre_pull = TVector(nbins)\n pre_up = TVector(nbins)\n post_lo = TVector(nbins)\n post_pull = TVector(nbins)\n post_up = TVector(nbins)\n\n fill = TVector(nbins)\n ypos = TVector(nbins)\n zero = TVector(nbins)\n\n names = sorted(stats.keys())\n\n cv.cd()\n pad1.Draw()\n pad1.cd()\n\n frame = TH2F('frame1', '', 1, -2, 2, nbins, 0, nbins)\n frame.SetStats(0)\n yax = frame.GetYaxis()\n frame.GetXaxis().SetTitle('( #hat{#theta} - #theta_{0} ) / #Delta#theta')\n\n\n for idx, name in enumerate(names):\n \n i = 5*idx + 3\n entry = stats[name]\n\n pre_lo[i] = entry.np_prefit_lo\n pre_pull[i] = entry.np_prefit_pull\n pre_up[i] = entry.np_prefit_up\n\n post_lo[i] = entry.np_postfit_lo\n post_pull[i] = entry.np_postfit_pull\n post_up[i] = entry.np_postfit_up\n\n name = name.replace('sys_', '').replace('_sys', '')\n yax.SetBinLabel(i, name)\n\n for i in xrange(1, nbins - 3):\n ypos[i] = i\n\n frame.Draw()\n\n pre_g = TGraphAsymmErrors(pre_pull, ypos, pre_lo, pre_up, zero, zero)\n pre_g.SetLineStyle(7);\n pre_g.SetLineColor(15);\n pre_g.SetLineWidth(2);\n pre_g.Draw('p')\n\n post_g = TGraphAsymmErrors(post_pull, ypos, post_lo, post_up, zero, zero)\n post_g.SetLineWidth(2);\n post_g.Draw('p')\n\n _obj.extend([frame, pre_g, post_g])\n\n\ndef plot_mu(stats):\n\n n = len(stats)\n nbins = 5*n + 4\n\n pre_err = TVector(nbins)\n pre_pull = TVector(nbins)\n post_err = TVector(nbins)\n post_pull = TVector(nbins)\n\n fill = TVector(nbins)\n ypos = TVector(nbins)\n\n names = sorted(stats.keys())\n mu_max = 0\n\n\n cv.cd()\n pad2.SetFillStyle(4000)\n pad2.SetFrameFillStyle(4000)\n pad2.Draw()\n pad2.cd()\n\n\n for idx, name in enumerate(names):\n \n i_pre = 5*idx + 2\n i_post = 5*idx + 4\n entry = stats[name]\n\n err = (entry.mu_prefit_up - entry.mu_prefit_lo)/2\n pre_err[i_pre] = err\n pre_pull[i_pre] = entry.mu_prefit_lo + err\n if pre_pull[i_pre] + err > mu_max:\n mu_max = pre_pull[i_pre] + err\n\n err = abs(entry.mu_postfit_up - entry.mu_postfit_lo)/2\n post_err[i_post] = err\n post_pull[i_post] = entry.mu_postfit_lo + err\n if post_pull[i_post] + err > mu_max:\n mu_max = post_pull[i_post] + err \n\n for idx in xrange(len(names)):\n i_pre = 5*idx + 2\n i_post = 5*idx + 4\n pre_err[i_pre] /= mu_max\n pre_pull[i_pre] /= mu_max\n post_err[i_post] /= mu_max\n post_pull[i_post] /= mu_max\n\n for i in xrange(1, nbins - 3):\n ypos[i] = i\n fill[i] = 0.8\n\n frame = pad2.DrawFrame(-2, 0, 2, nbins)\n frame.GetXaxis().SetLabelOffset(99)\n frame.GetXaxis().SetTickSize(0)\n frame.GetYaxis().SetLabelOffset(99)\n\n pre_g = TGraphAsymmErrors(pre_pull, ypos, pre_err, pre_err, fill, fill)\n pre_g.SetFillColorAlpha(kYellow-7, 0.85)\n pre_g.Draw('E2')\n\n post_g = TGraphAsymmErrors(post_pull, ypos, post_err, post_err, fill, fill)\n post_g.SetFillColorAlpha(kBlue-10, 0.85)\n post_g.Draw('E2')\n\n axis = TGaxis(-2, nbins, 2, nbins, -2 * mu_max, 2 * mu_max, 510, '-')\n axis.SetLabelSize(.035)\n axis.SetLabelFont(42)\n axis.SetTitle('#Delta#hat#mu')\n axis.Draw()\n\n _obj.extend([axis, pre_g, post_g])\n\n\ndef main():\n\n# stats = read_file(fname)\n\n\n Entry = namedtuple('Entry', ['np_prefit_pull', 'np_postfit_pull',\n 'np_prefit_lo', 'np_prefit_up', 'np_postfit_lo', 'np_postfit_up',\n 'mu_prefit_lo', 'mu_prefit_up', 'mu_postfit_lo', 'mu_postfit_up'])\n\n stats = {}\n with open('systematics.txt', 'r') as f:\n f.readline()\n f.readline()\n for line in f:\n try:\n name, pull, constr = re.match(\"alpha_([\\w_]+)\\s*=\\s*([e\\.\\-0-9]+)\\s*\\+/-\\s*([e\\.0-9]+)\\s*\\(limited\\)\", line).groups()\n stats[name] = Entry(mu_prefit_up= 0,\n mu_prefit_lo= 0, \n mu_postfit_up=0,\n mu_postfit_lo=0,\n np_prefit_lo=1,\n np_prefit_pull=0,\n np_prefit_up=1,\n np_postfit_lo=float(constr),\n np_postfit_pull=float(pull),\n np_postfit_up=float(constr))\n except:\n break\n\n\n with open('root-files/BDT/boosted_el_np/1000.txt', 'r') as f:\n f.readline()\n f.readline()\n f.readline()\n for line in f:\n if not line:\n break\n vals = line.split()\n name = vals[0]\n preh, prel, posth, postl = [float(v) for v in vals[1:]]\n\n entry = stats[name[6:]]\n entry = entry._replace(mu_prefit_up=preh)\n entry = entry._replace(mu_prefit_lo=prel)\n entry = entry._replace(mu_postfit_up=posth)\n entry = entry._replace(mu_postfit_lo=postl)\n stats[name[6:]] = entry\n\n plot_np(stats)\n plot_mu(stats)\n \n\nif __name__ == '__main__':\n main()\n cv.Print('plot.pdf')\n","sub_path":"np.py","file_name":"np.py","file_ext":"py","file_size_in_byte":8772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"547201531","text":"print(\"Start\")\n\ndef USDtoINR(a):\n return a*71\n\ndef C2F(a):\n f = (a*9/5)+32\n return f\n\n\nprint(USDtoINR(100))\n\nfar1 = C2F(50)\nprint(\"50 degrees c is \", far1)\n\n\n\n\n\n\n\n\n\n\nprint(\"END\")","sub_path":"Week2/28-JustBasicFunction - Copy.py","file_name":"28-JustBasicFunction - Copy.py","file_ext":"py","file_size_in_byte":187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"620269506","text":"class Solution:\n # @return an integer\n def minDistance(self, word1, word2):\n if len(word1)==0:\n return len(word2)\n elif len(word2)==0:\n return len(word1)\n \n M = [[0]*(len(word2)+1) for i in range(1+len(word1))]\n M[len(word1)][len(word2)] = 0\n for i in range(len(word2)):\n M[len(word1)][i] = len(word2)-i\n for i in range(len(word1)):\n M[i][len(word2)] = len(word1)-i\n for i in range(len(word1)-1,-1,-1):\n for j in range(len(word2)-1,-1,-1):\n if word1[i] == word2[j]:\n M[i][j] = M[i+1][j+1]\n else:\n M[i][j] = 1 + min(min(M[i+1][j],M[i][j+1]),M[i+1][j+1])\n return M[0][0]","sub_path":"leetcode/edit-distance.py","file_name":"edit-distance.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"565468748","text":"#!/usr/bin/env python3.85\n#Need to check if the files are empty entirely\n\nimport json\nimport fileinput\nimport os\nimport sys\nimport copy\nimport csv\nimport os.path\nfrom os import path\n\n#arguments are: 1: the directory\ndef main():\n directory = sys.argv[1];\n \n outputfile = directory + \"_output.csv\";\n\n filelist = os.listdir(directory);\n \n print(directory + \"/\" + filelist[0]);\n\n headers = [];\n rows = [];\n columns = {};\n for file in filelist:\n if file.endswith(\".json\"): \n file = open(directory + \"/\" + filelist[0], 'r');\n print(file);\n j_data = json.load(file);\n\n file.close();\n\n for j in j_data:\n if len(headers) != 0:\n for h in headers:\n if h not in headers:\n headers.append(h);\n else:\n for h in j.keys():\n headers.append(str(h));\n \n print(headers);\n\n\n for j in j_data:\n row = [];\n for h in headers:\n row.append(j[h]);\n #print(j[h]);\n rows.append(row);\n\n for h in headers:\n column = [];\n for j in j_data:\n column.append(j[h]);\n columns[h] = column\n \n if(path.exists(outputfile)):\n os.remove(outputfile);\n\n if(path.exists('_' + outputfile)):\n os.remove('_' + outputfile);\n\n with open(outputfile, mode=\"w\", newline='') as outfile:\n write = csv.writer(outfile, delimiter = ',')\n write.writerow(headers);\n for row in rows:\n print(row)\n if len(row) != 0:\n write.writerow(row);\n\n #with open(outputfile) as in_file:\n # with open('_' + outputfile, 'w') as out_file:\n # writer = csv.writer(out_file)\n # for row in csv.reader(in_file):\n # if any(field.strip() for field in row):\n # writer.writerow(row)\n #\n #if(path.exists(outputfile)):\n # os.remove(outputfile);\n \nif __name__ == \"__main__\":\n main()","sub_path":"FlappyBird/Assets/StreamingAssets/Data/json_csv.py","file_name":"json_csv.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"236227988","text":"import pickle\nimport argparse\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(\n description='Inference arguments for text generation')\n parser.add_argument('-m', '--model', required=True,\n help='Path for pickle file of RNN model.')\n parser.add_argument('-t', '--temperature', default=0.5,\n help='Check Readme for more details about temperature.')\n parser.add_argument('-s', '--start-token', required=True,\n help='Provide initial character to start generation.')\n parser.add_argument('--max-length', default=140,\n help='Number of chars to be produced.')\n \n\n args = parser.parse_args()\n\n rnn_model = None\n with open(args.model, 'rb') as f:\n rnn_model = pickle.load(f)\n\n print(rnn_model.sample_sentence(args.temperature, args.start_token, args.max_length))\n","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"338166395","text":"import tensorflow.compat.v1 as tf\n\n\ndef batch_normalization(inp, \n name, \n weight1=0.99, \n weight2=0.99, \n is_training=True):\n with tf.variable_scope(name):\n # 获取输入张量的形状\n inp_shape = inp.get_shape().as_list()\n\n # 定义不可训练变量hist_mean记录均值的移动平均值\n # 形状与输入张量最后一个维度相同\n hist_mean = tf.get_variable('hist_mean', \n shape=inp_shape[-1:], \n initializer=tf.zeros_initializer(), \n trainable=False)\n\n # 定义不可训练变量hist_var记录方差的移动平均值\n # 形状与输入张量最后一个维度相同\n hist_var = tf.get_variable('hist_var', \n shape=inp_shape[-1:], \n initializer=tf.ones_initializer(), \n trainable=False)\n\n # 定义可训练变量gamma和beta,形状与输入张量最后一个维度相同\n gamma = tf.Variable(tf.ones(inp_shape[-1:]), name='gamma')\n beta = tf.Variable(tf.zeros(inp_shape[-1:]), name='beta')\n\n # 计算输入张量除了最后一个维��外上面的均值与方差\n batch_mean, batch_var = tf.nn.moments(inp, \n axes=[i for i in range(len(inp_shape) - 1)], \n name='moments')\n\n # 计算均值的移动平均值,并将计算结果赋予hist_mean/running_mean\n running_mean = tf.assign(hist_mean, \n weight1 * hist_mean + (1 - weight1) * batch_mean)\n\n # 计算方差的移动平均值,并将计算结果赋予hist_var/running_var\n running_var = tf.assign(hist_var, \n weight2 * hist_var + (1 - weight2) * batch_var)\n\n # 使用control_dependencies限制先计算移动平均值\n with tf.control_dependencies([running_mean, running_var]):\n # 根据当前状态是训练或是测试选取不同的值进行标准化\n # is_training=True,使用batch_mean & batch_var\n # is_training=False,使用running_mean & running_var\n output = tf.cond(tf.cast(is_training, tf.bool),\n lambda: tf.nn.batch_normalization(inp, \n mean=batch_mean, \n variance=batch_var, \n scale=gamma, \n offset=beta, \n variance_epsilon=1e-5, \n name='bn'),\n lambda: tf.nn.batch_normalization(inp, \n mean=running_mean, \n variance=running_var, \n scale=gamma, \n offset=beta, \n variance_epsilon=1e-5, \n name='bn')\n )\n return output\n\ndef _batch_normalization(inp, name, weight1=0.99, weight2=0.99, is_training=True):\n with tf.variable_scope(name):\n return tf.layers.batch_normalization(\n inp,\n training=is_training\n )","sub_path":"章节6/mlp/normalizations/batch_normalization.py","file_name":"batch_normalization.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"111746444","text":"from pymirobot.mirobot import Mirobot\nfrom pymirobot.RemoteSerial import RemoteSerial\nfrom time import time, sleep\nfrom pymirobot.ArmState import ArmState\n\n\nclass MirobotClient(Mirobot):\n def __init__(self, host, port=2217, receive_callback=None, debug=False):\n super().__init__(receive_callback, debug)\n\n self.serial_device = RemoteSerial(host, port)\n\n def connect(self, receive_callback=None):\n if receive_callback is not None:\n self.receive_callback = receive_callback\n\n self.serial_device.open()\n self.serial_device.telnet.read_until(\n bytes(\"Using reset pos!\", \"utf-8\"), timeout=3\n )\n # Sometimes gets sent twice?\n self.serial_device.telnet.read_until(\n bytes(\"Using reset pos!\", \"utf-8\"), timeout=1\n )\n\n def home_simultaneous(self):\n msg = \"$H\"\n self.send_msg(msg)\n self.serial_device.telnet.read_until(bytes(\"ok\", \"utf-8\"), timeout=20)\n\n # If sending a command while returning to zero, coordinates get messed up\n # Poll for idle\n start = time()\n while time() - start < 10 and not self.is_idle():\n sleep(0.5)\n\n def get_arm_state(self):\n status = self._get_status_string()\n\n if status:\n state = ArmState.from_status_string(status)\n\n return state\n\n else:\n return None\n\n def is_idle(self):\n state = self.get_arm_state()\n\n if state:\n return not state.active\n\n else:\n return False\n\n def _get_status_string(self):\n self.send_msg(\"?\")\n\n result = self.serial_device.telnet.read_until(\n bytes(\">\", \"utf-8\"), timeout=1\n ).decode(\"utf-8\")\n\n start = result.find(\"<\")\n\n if start >= 0:\n result = result[start:]\n\n if \">\" in result:\n return result\n else:\n return None\n","sub_path":"MirobotClient.py","file_name":"MirobotClient.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"569958677","text":"from api import *\nfrom docker import *\nfrom console import *\n\n\ndef health():\n result = urlopen(\"http://0.0.0.0:8081/health\").read()\n return 'service is healthy' in result\ndef api():\n result = urlopen(\"http://0.0.0.0:8081/state/SujetoActor/1\").read()\n return '\"saldo\" : -244.72' in result\ndef database():\n return cassandra()\n\ntests = [\n health,\n api,\n database,\n # 'other test!'\n]\nenvironments = [\n \"dev\",\n \"prod\",\n # 'other environment!'\n]\n","sub_path":"git-hooks/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"260339108","text":"import Tkinter as tk\nfrom PIL import Image, ImageTk\nimport base64\nimport cStringIO\n\n#whole window\nroot = tk.Tk()\nroot.title('Face Search')\nroot.geometry('960x720')\n\n#define the parts for different functions in window\ntopFrame = tk.Frame(root, width=960, height=540)\ntopFrame.place(x=0, y=0, anchor='nw')\nbottomFrame = tk.Frame(root,width=960, height=180)\nbottomFrame.place(x=0, y=540, anchor='nw')\n\n#for original complete image\nframe1 = tk.Frame(topFrame, width=720, height=540)\nframe1.place(x=0, y=0, anchor='nw')\nframe2 = tk.Frame(topFrame, width=240, height=540)\nframe2.place(x=960, y=0, anchor='nw')\n#for search result\nframe3 = tk.Frame(bottomFrame, width=960, height=180)\nframe3.place(x=0, y=0, anchor='nw')\n\n#select faces for search\nframe21 = tk.Frame(frame2, width=240, height=405)\nframe21.place(x=0, y=0, anchor='nw')\n#function buttons\nframe22 = tk.Frame(frame2, width=240, height=135)\nframe22.place(x=0, y=541, anchor='nw')\n\n#list for faces and checkboxes\nframe_list1 = tk.Frame(frame21, width = 240, height = 100)\nframe_list1.place(x=0,y=0,anchor='nw')\nframe_face11 = tk.Frame(frame_list1, width=100, height=100, borderwidth=0, background = '#EEEEEE')\nframe_face11.place(x=0,y=0,anchor='nw')\nframe_face12 = tk.Frame(frame_list1, width=140, height= 100, borderwidth=0)\nframe_face12.place(x=100,y=0,anchor='nw')\n\nframe_list2 = tk.Frame(frame21, width = 240, height = 100)\nframe_list2.place(x=0,y=100,anchor='nw')\nframe_face21 = tk.Frame(frame_list2, width=100, height=100, borderwidth=0, background = '#EEEEEE')\nframe_face21.place(x=0,y=0,anchor='nw')\nframe_face22 = tk.Frame(frame_list2, width=140, height= 100, borderwidth=0)\nframe_face22.place(x=100,y=0,anchor='nw')\n\nframe_list3 = tk.Frame(frame21, width = 240, height = 100)\nframe_list3.place(x=0,y=200,anchor='nw')\nframe_face31 = tk.Frame(frame_list3, width=100, height=100, borderwidth=0, background = '#EEEEEE')\nframe_face31.place(x=0,y=0,anchor='nw')\nframe_face32 = tk.Frame(frame_list3, width=140, height= 100, borderwidth=0)\nframe_face32.place(x=100,y=0,anchor='nw')\n\nframe_list4 = tk.Frame(frame21, width = 240, height = 100)\nframe_list4.place(x=0,y=300,anchor='nw')\nframe_face41 = tk.Frame(frame_list4, width=100, height=100, borderwidth=0, background = '#EEEEEE')\nframe_face41.place(x=0,y=0,anchor='nw')\nframe_face42 = tk.Frame(frame_list4, width=140, height= 100, borderwidth=0)\nframe_face42.place(x=100,y=0,anchor='nw')\n\n#show origional image\ncanvas_image = tk.Canvas(frame1, width=720, height=540)\nimage_file1 = Image.open('images/power-rangers_960*720.jpg')\nimage_file1 = image_file1.resize((720,540), Image.ANTIALIAS)\nbuffer = cStringIO.StringIO()\nimage_file1.save(buffer, format=\"GIF\")\nimage_file1_encoded = base64.b64encode(buffer.getvalue())\nimage_origion = tk.PhotoImage(data=image_file1_encoded)\nimage_test1 = canvas_image.create_image(0,0, anchor='nw', image=image_origion)\ncanvas_image.pack(side='top')\n\n#select face function\n#show face part of the image\n#status of selection of faces\nface1_select = tk.Variable()\nface2_select = tk.Variable()\nface3_select = tk.Variable()\nface4_select = tk.Variable()\n\ncanvas_testimage1 = tk.Canvas(frame_face11, width=100, height = 100)\nimage_file_faces = Image.open('images/power-rangers_960*720.gif')\ncrop_rectangle1 = (0, 0, 100, 100)\nimage1_crop = image_file_faces.crop(crop_rectangle1)\nbuffer1 = cStringIO.StringIO()\nimage1_crop.save(buffer1, format=\"GIF\")\nimage1_encoded = base64.b64encode(buffer1.getvalue())\ncropped_im1 = tk.PhotoImage(data=image1_encoded)\nimage_test2 = canvas_testimage1.create_image(0,0, anchor='nw', image=cropped_im1)\ncanvas_testimage1.pack()\n\ncanvas_testimage2 = tk.Canvas(frame_face21, width=100, height = 100)\nimage_test2 = canvas_testimage2.create_image(0,0, anchor='nw', image=cropped_im1)\ncanvas_testimage2.pack()\n\ncanvas_testimage3 = tk.Canvas(frame_face31, width=100, height = 100)\nimage_file_faces3 = Image.open('images/power-rangers_960*720.gif')\ncrop_rectangle3 = (0, 0, 100, 100)\nimage3_crop = image_file_faces3.crop(crop_rectangle3)\nbuffer3 = cStringIO.StringIO()\nimage3_crop.save(buffer3, format=\"GIF\")\nimage3_encoded = base64.b64encode(buffer3.getvalue())\ncropped_im3 = tk.PhotoImage(data=image1_encoded)\nimage_test3 = canvas_testimage3.create_image(0,0, anchor='nw', image=cropped_im3)\ncanvas_testimage3.pack()\n\ncanvas_testimage4 = tk.Canvas(frame_face41, width=100, height = 100)\nimage_file_faces4 = Image.open('images/power-rangers_960*720.gif')\ncrop_rectangle4 = (0, 0, 100, 100)\nimage4_crop = image_file_faces4.crop(crop_rectangle4)\nbuffer4 = cStringIO.StringIO()\nimage4_crop.save(buffer4, format=\"GIF\")\nimage4_encoded = base64.b64encode(buffer4.getvalue())\ncropped_im4 = tk.PhotoImage(data=image4_encoded)\nimage_test4 = canvas_testimage4.create_image(0,0, anchor='nw', image=cropped_im4)\ncanvas_testimage4.pack()\n\n#checkbox and text discription\ncheckbutton1 = tk.Checkbutton(frame_face12, text='Face1', variable = face1_select, onvalue=1, offvalue=0)\ncheckbutton1.pack(side='top')\ntext_face1 =tk.Text(frame_face12, width=25, height=4, background = '#EEEEEE')\ntext_face1.pack(side='top')\n\ncheckbutton2 = tk.Checkbutton(frame_face22, text='Face2', variable = face2_select, onvalue=1, offvalue=0)\ncheckbutton2.pack(side='top')\ntext_face2 =tk.Text(frame_face22, width=25, height=4, background = '#EEEEEE')\ntext_face2.pack(side='top')\n\ncheckbutton3 = tk.Checkbutton(frame_face32, text='Face3', variable = face3_select, onvalue=1, offvalue=0)\ncheckbutton3.pack(side='top')\ntext_face3 = tk.Text(frame_face32, width=25, height=4, background = '#EEEEEE')\ntext_face3.pack(side='top')\n\ncheckbutton4 = tk.Checkbutton(frame_face42, text='Face4', variable = face4_select, onvalue=1, offvalue=0)\ncheckbutton4.pack(side='top')\ntext_face4 = tk.Text(frame_face42, width=25, height=4, background = '#EEEEEE')\ntext_face4.pack(side='top')\n\n#showfaces('images/power-rangers_960*720.gif')\n#buttons\nbutton1 = tk.Button(frame22, text='Open', width=10).place(x=60, y=15)\nbutton2 = tk.Button(frame22, text='Import', width=10).place(x=60, y=55)\nbutton2 = tk.Button(frame22, text='Search', width=10).place(x=60, y=95)\n\nframe1.place(x=0, y=0, anchor='nw')\nframe21.place(x=0, y=0, anchor='nw')\nframe22.place(x=0, y=405, anchor='nw')\nframe2.place(x=720, y=0, anchor='nw')\nframe3.place(x=0, y=0, anchor='nw')\n\ntopFrame.place(x=0, y=0, anchor='nw')\nbottomFrame.place(x=0, y=540, anchor='nw')\nroot.mainloop()\n","sub_path":"interface6_no-scrollbar.py","file_name":"interface6_no-scrollbar.py","file_ext":"py","file_size_in_byte":6342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"413734574","text":"\"\"\"\n Compute evaluation statistics.\n\"\"\"\nimport scipy.sparse as sp\nimport numpy as np\nfrom xclib.utils.sparse import topk, binarize, retain_topk\n__author__ = 'X'\n\n\ndef jaccard_similarity(pred_0, pred_1, y=None): \n \"\"\"Jaccard similary b/w two different predictions matrices\n Args:\n pred_0: csr_matrix\n prediction for algorithm 0\n pred_1: csr_matrix\n prediction for algorithm 1\n y: csr_matrix or None\n true labels\n \"\"\"\n def _correct_only(pred, y):\n pred = pred.multiply(y)\n pred.eliminate_zeros()\n return pred\n\n def _safe_divide(a, b):\n with np.errstate(divide='ignore', invalid='ignore'):\n out = np.true_divide(a, b)\n out[out == np.inf] = 0\n return np.nan_to_num(out)\n\n if y is not None:\n pred_0 = _correct_only(pred_0, y)\n pred_1 = _correct_only(pred_1, y)\n\n pred_0, pred_1 = binarize(pred_0), binarize(pred_1)\n intersection = np.array(pred_0.multiply(pred_1).sum(axis=1)).ravel()\n union = np.array(binarize(pred_0 + pred_1).sum(axis=1)).ravel()\n return np.mean(_safe_divide(intersection, union))\n\n\ndef recall(predicted_labels, true_labels, k=5):\n \"\"\"Compute recall@k\n Args:\n predicted_labels: csr_matrix\n predicted labels\n true_labels: csr_matrix\n true_labels\n k: int, default=5\n keep only top-k predictions\n \"\"\"\n predicted_labels = retain_topk(predicted_labels, k)\n denom = np.sum(true_labels, axis=1)\n rc = binarize(true_labels.multiply(predicted_labels))\n rc = np.sum(rc, axis=1)/(denom+1e-5)\n return np.mean(rc)*100\n\n\ndef format(*args, decimal_points='%0.2f'):\n out = []\n for vals in args:\n out.append(','.join(list(map(lambda x: decimal_points % (x*100), vals))))\n return '\\n'.join(out)\n\n\ndef compute_inv_propesity(labels, A, B):\n num_instances, _ = labels.shape\n freqs = np.ravel(np.sum(labels, axis=0))\n C = (np.log(num_instances)-1)*np.power(B+1, A)\n wts = 1.0 + C*np.power(freqs+B, -A)\n return np.ravel(wts)\n\n\nclass Metrices(object):\n def __init__(self, true_labels, inv_propensity_scores=None, remove_invalid=False, batch_size=20):\n \"\"\"\n Args:\n true_labels: csr_matrix: true labels with shape (num_instances, num_labels)\n remove_invalid: boolean: remove samples without any true label\n \"\"\"\n self.true_labels = true_labels\n self.num_instances, self.num_labels = true_labels.shape\n self.remove_invalid = remove_invalid\n self.valid_idx = None\n if self.remove_invalid:\n samples = np.sum(self.true_labels, axis=1)\n self.valid_idx = np.arange(self.num_instances).reshape(-1, 1)[samples > 0]\n self.true_labels = self.true_labels[self.valid_idx]\n self.num_instances = self.valid_idx.size\n \"inserting dummpy index\"\n self.true_labels_padded = sp.hstack(\n [self.true_labels, sp.csr_matrix(np.zeros((self.num_instances, 1)))]).tocsr()\n self.ndcg_denominator = np.cumsum(\n 1/np.log2(np.arange(1, self.num_labels+1)+1)).reshape(-1, 1)\n self.labels_documents = np.ravel(np.array(np.sum(self.true_labels, axis=1), np.int32))\n self.labels_documents[self.labels_documents == 0] = 1\n self.inv_propensity_scores = None\n self.batch_size = batch_size\n if inv_propensity_scores is not None:\n self.inv_propensity_scores = np.hstack(\n [inv_propensity_scores, np.zeros((1))])\n assert(self.inv_propensity_scores.size == self.true_labels_padded.shape[1])\n\n def _rank_sparse(self, X, K):\n \"\"\"\n Args:\n X: csr_matrix: sparse score matrix with shape (num_instances, num_labels)\n K: int: Top-k values to rank\n Returns:\n predicted: np.ndarray: (num_instances, K) top-k ranks\n \"\"\"\n total = X.shape[0]\n labels = X.shape[1]\n\n predicted = np.full((total, K), labels)\n for i, x in enumerate(X):\n index = x.__dict__['indices']\n data = x.__dict__['data']\n idx = np.argsort(-data)[0:K]\n predicted[i, :idx.shape[0]] = index[idx]\n return predicted\n\n def eval(self, predicted_labels, K=5):\n \"\"\"\n Args:\n predicted_labels: csr_matrix: predicted labels with shape (num_instances, num_labels)\n K: int: compute values from 1-5\n \"\"\"\n if self.valid_idx is not None:\n predicted_labels = predicted_labels[self.valid_idx]\n assert predicted_labels.shape == self.true_labels.shape\n predicted_labels = topk(predicted_labels, K, self.num_labels, -100)\n prec = self.precision(predicted_labels, K)\n ndcg = self.nDCG(predicted_labels, K)\n if self.inv_propensity_scores is not None:\n wt_true_mat = self._rank_sparse(self.true_labels.dot(sp.spdiags(\n self.inv_propensity_scores[:-1], diags=0, m=self.num_labels, n=self.num_labels)), K)\n PSprecision = self.PSprecision(predicted_labels, K) / self.PSprecision(wt_true_mat, K)\n PSnDCG = self.PSnDCG(predicted_labels, K) / self.PSnDCG(wt_true_mat, K)\n return [prec, ndcg, PSprecision, PSnDCG]\n else:\n return [prec, ndcg]\n\n def precision(self, predicted_labels, K):\n \"\"\"\n Compute precision for 1-K\n \"\"\"\n p = np.zeros((1, K))\n total_samples = self.true_labels.shape[0]\n ids = np.arange(total_samples).reshape(-1, 1)\n p = np.sum(self.true_labels_padded[ids, predicted_labels], axis=0)\n p = p*1.0/(total_samples)\n p = np.cumsum(p)/(np.arange(K)+1)\n return np.ravel(p)\n\n def nDCG(self, predicted_labels, K):\n \"\"\"\n Compute nDCG for 1-K\n \"\"\"\n ndcg = np.zeros((1, K))\n total_samples = self.true_labels.shape[0]\n ids = np.arange(total_samples).reshape(-1, 1)\n dcg = self.true_labels_padded[ids, predicted_labels] /(\n np.log2(np.arange(1, K+1)+1)).reshape(1, -1)\n dcg = np.cumsum(dcg, axis=1)\n denominator = self.ndcg_denominator[self.labels_documents-1]\n for k in range(K):\n temp = denominator.copy()\n temp[denominator > self.ndcg_denominator[k]] = self.ndcg_denominator[k]\n temp = np.power(temp, -1.0)\n for batch in np.array_split(np.arange(total_samples), self.batch_size):\n dcg[batch, k] = np.ravel(np.multiply(dcg[batch, k], temp[batch]))\n ndcg[0, k] = np.mean(dcg[:, k])\n del temp\n return np.ravel(ndcg)\n\n def PSnDCG(self, predicted_labels, K):\n \"\"\"\n Compute PSnDCG for 1-K\n \"\"\"\n psndcg = np.zeros((1, K))\n total_samples = self.true_labels.shape[0]\n ids = np.arange(total_samples).reshape(-1, 1)\n\n ps_dcg = self.true_labels_padded[ids, predicted_labels].toarray(\n )*self.inv_propensity_scores[predicted_labels]/np.log2(np.arange(1, K+1)+1).reshape(1, -1)\n \n ps_dcg = np.cumsum(ps_dcg, axis=1)\n denominator = self.ndcg_denominator[self.labels_documents-1]\n \n for k in range(K):\n temp = denominator.copy()\n temp[denominator > self.ndcg_denominator[k]] = self.ndcg_denominator[k]\n temp = np.power(temp, -1.0)\n for batch in np.array_split(np.arange(total_samples), self.batch_size):\n ps_dcg[batch, k] = ps_dcg[batch, k]*temp[batch, 0]\n psndcg[0, k] = np.mean(ps_dcg[:, k])\n del temp\n return np.ravel(psndcg)\n\n def PSprecision(self, predicted_labels, K):\n \"\"\"\n Compute PSprecision for 1-K\n \"\"\"\n psp = np.zeros((1, K))\n total_samples = self.true_labels.shape[0]\n ids = np.arange(total_samples).reshape(-1, 1)\n _p = self.true_labels_padded[ids, predicted_labels].toarray(\n )*self.inv_propensity_scores[predicted_labels]\n psp = np.sum(_p, axis=0)\n psp = psp*1.0/(total_samples)\n psp = np.cumsum(psp)/(np.arange(K)+1)\n return np.ravel(psp)\n","sub_path":"xclib/evaluation/xc_metrics.py","file_name":"xc_metrics.py","file_ext":"py","file_size_in_byte":8223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"619386383","text":"import json\nimport argparse\nimport pprint\n\n\ndef load_data(filepath):\n with open(filepath, 'r') as file:\n json_data_ = json.load(file)\n return json_data_\n\n\ndef pretty_print_json(json_data_):\n pprint.pprint(json_data_)\n\n\ndef parse_cli_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"path_to_file\", help='program reads JSON file and prints the content')\n args = parser.parse_args()\n return args.path_to_file\n\n\nif __name__ == '__main__':\n path_to_file = parse_cli_args()\n\n json_data = load_data(path_to_file)\n pretty_print_json(json_data)\n","sub_path":"pprint_json.py","file_name":"pprint_json.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"260422682","text":"from __future__ import print_function\n\nimport numpy as np\nimport argparse\nimport csv\nimport itertools\nimport random\nimport subprocess\nfrom pathlib import Path\n\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom rl_utils import hierarchical_parse_args\nfrom torch.utils.data import DataLoader, IterableDataset\nfrom torch.utils.tensorboard import SummaryWriter\nfrom tqdm import tqdm\nimport torch.nn as nn\n\nfrom ppo.control_flow.lines import If\nfrom ppo.control_flow.multi_step.env import Env\nfrom ppo.layers import Flatten\nfrom ppo.utils import init_\nimport ppo.control_flow.multi_step.env\n\nMAX_LAYERS = 3\n\ntry:\n from StringIO import StringIO\nexcept ImportError:\n from io import StringIO\n\n\ndef format_image(data, output, target):\n return torch.stack([data.sum(1)[0], target[0], output[0]], dim=0).unsqueeze(1)\n\n\nclass GridworldDataset(IterableDataset):\n def __init__(self, **kwargs):\n self.env = Env(rank=0, lower_level=\"pretrained\", **kwargs)\n\n def __iter__(self):\n while True:\n agent_pos, objects = self.env.populate_world([])\n evaluation = self.env.evaluate_line(\n line=If,\n counts=self.env.count_objects(objects),\n condition_evaluations=[],\n loops=0,\n )\n yield self.env.world_array(objects, agent_pos), int(evaluation)\n\n # def __len__(self):\n # pass\n\n\nclass Network(nn.Module):\n def __init__(\n self,\n d,\n h,\n w,\n conv_layers,\n conv_kernels,\n conv_strides,\n pool_type,\n pool_kernels,\n pool_strides,\n ):\n super().__init__()\n\n def remove_none(xs):\n return [x for x in xs if x is not None]\n\n conv_layers = remove_none(conv_layers)\n conv_kernels = remove_none(conv_kernels)\n conv_strides = remove_none(conv_strides)\n pool_kernels = remove_none(pool_kernels)\n pool_strides = remove_none(pool_strides)\n\n def generate_pools(k):\n for (kernel, stride) in zip(pool_kernels, pool_strides):\n kernel = min(k, kernel)\n padding = (kernel // 2) % stride\n if pool_type == \"avg\":\n pool = nn.AvgPool2d(\n kernel_size=kernel, stride=stride, padding=padding\n )\n elif pool_type == \"max\":\n pool = nn.MaxPool2d(\n kernel_size=kernel, stride=stride, padding=padding\n )\n else:\n raise RuntimeError\n k = int((k + 2 * padding - kernel) / stride + 1)\n k = yield k, pool\n\n def generate_convolutions(k):\n in_size = d\n for (layer, kernel, stride) in zip(conv_layers, conv_kernels, conv_strides):\n kernel = min(k, kernel)\n padding = (kernel // 2) % stride\n conv = init_(\n nn.Conv2d(\n in_channels=in_size,\n out_channels=layer,\n kernel_size=kernel,\n stride=stride,\n padding=padding,\n )\n )\n k = int((k + (2 * padding) - (kernel - 1) - 1) // stride + 1)\n k = yield k, conv\n in_size = layer\n\n def generate_modules(k):\n n_pools = min(len(pool_strides), len(pool_kernels))\n n_conv = min(len(conv_layers), len(conv_strides), len(conv_kernels))\n conv_iterator = generate_convolutions(k)\n try:\n k, conv = next(conv_iterator)\n yield conv\n pool_iterator = None\n for i in itertools.count():\n if pool_iterator is None:\n if i >= n_conv - n_pools and pool_type is not None:\n pool_iterator = generate_pools(k)\n k, pool = next(pool_iterator)\n yield pool\n else:\n k, pool = pool_iterator.send(k)\n yield pool\n k, conv = conv_iterator.send(k)\n yield conv\n except StopIteration:\n pass\n yield Flatten()\n yield init_(nn.Linear(k ** 2 * conv.out_channels, 1))\n yield nn.Sigmoid()\n\n self.net = nn.Sequential(*generate_modules(h))\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return self.net(x)\n\n\ndef main(\n no_cuda: bool,\n seed: int,\n batch_size: int,\n lr: float,\n log_dir: Path,\n run_id: str,\n env_args: dict,\n network_args: dict,\n log_interval: int,\n save_interval: int,\n):\n use_cuda = not no_cuda and torch.cuda.is_available()\n writer = SummaryWriter(str(log_dir))\n\n torch.manual_seed(seed)\n\n if use_cuda:\n nvidia_smi = subprocess.check_output(\n \"nvidia-smi --format=csv --query-gpu=memory.free\".split(),\n universal_newlines=True,\n )\n n_gpu = len(list(csv.reader(StringIO(nvidia_smi)))) - 1\n try:\n index = int(run_id[-1])\n except (ValueError, IndexError):\n index = random.randrange(0, n_gpu)\n print(\"Using GPU\", index)\n device = torch.device(\"cuda\", index=index % n_gpu)\n else:\n device = \"cpu\"\n\n dataset = GridworldDataset(**env_args)\n obs_shape = dataset.env.observation_space.spaces[\"obs\"].shape\n network = Network(*obs_shape, **network_args)\n network = network.to(device)\n optimizer = optim.Adam(network.parameters(), lr=lr)\n network.train()\n start = 0\n\n train_loader = torch.utils.data.DataLoader(\n dataset,\n batch_size=batch_size,\n **(dict(num_workers=1, pin_memory=True) if use_cuda else dict()),\n )\n total_loss = 0\n log_progress = None\n for i, (data, target) in enumerate(train_loader):\n data, target = data.to(device).float(), target.to(device).float()\n optimizer.zero_grad()\n output = network(data).flatten()\n loss = F.binary_cross_entropy(output, target, reduction=\"mean\")\n total_loss += loss\n loss.backward()\n avg_loss = total_loss / i\n optimizer.step()\n step = i + start\n if i % log_interval == 0:\n log_progress = tqdm(total=log_interval, desc=\"next log\")\n writer.add_scalar(\"loss\", loss, step)\n writer.add_scalar(\"avg_loss\", avg_loss, step)\n\n if i % save_interval == 0:\n torch.save(network.state_dict(), str(Path(log_dir, \"network.pt\")))\n log_progress.update()\n\n\ndef maybe_int(string):\n if string == \"None\":\n return None\n return int(string)\n\n\ndef cli():\n # Training settings\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n parser.add_argument(\n \"--batch-size\",\n type=int,\n default=64,\n metavar=\"N\",\n help=\"input batch size for training\",\n )\n parser.add_argument(\n \"--lr\", type=float, default=0.01, metavar=\"LR\", help=\"learning rate \"\n )\n parser.add_argument(\n \"--no-cuda\", action=\"store_true\", default=False, help=\"disables CUDA training\"\n )\n parser.add_argument(\"--seed\", type=int, default=0, metavar=\"S\", help=\"random seed \")\n parser.add_argument(\n \"--save-interval\",\n type=int,\n default=100,\n metavar=\"N\",\n help=\"how many batches to wait before logging training status\",\n )\n parser.add_argument(\n \"--log-interval\",\n type=int,\n default=10,\n metavar=\"N\",\n help=\"how many batches to wait before logging training status\",\n )\n parser.add_argument(\"--log-dir\", default=\"/tmp/mnist\", metavar=\"N\", help=\"\")\n parser.add_argument(\"--run-id\", default=\"\", metavar=\"N\", help=\"\")\n env_parser = parser.add_argument_group(\"env_args\")\n ppo.control_flow.multi_step.env.build_parser(\n env_parser,\n default_max_while_loops=1,\n default_max_world_resamples=0,\n default_min_lines=1,\n default_max_lines=1,\n default_time_to_waste=0,\n )\n network_parser = parser.add_argument_group(\"network_args\")\n network_parser.add_argument(f\"--pool-type\", choices=(\"avg\", \"max\", \"None\"))\n for i in range(MAX_LAYERS):\n network_parser.add_argument(\n f\"--conv-layer{i}\", dest=\"conv_layers\", action=\"append\", type=maybe_int\n )\n for mod in (\"conv\", \"pool\"):\n for component in (\"kernel\", \"stride\"):\n network_parser.add_argument(\n f\"--{mod}-{component}{i}\",\n dest=f\"{mod}_{component}s\",\n action=\"append\",\n type=maybe_int,\n )\n main(**hierarchical_parse_args(parser))\n\n\nif __name__ == \"__main__\":\n cli()\n","sub_path":"ppo/control_flow/supervised/conditions.py","file_name":"conditions.py","file_ext":"py","file_size_in_byte":8970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"492092722","text":"import io\nimport sys\n\n\ndef test_display():\n capturedOutput = io.StringIO()\n sys.stdout = capturedOutput\n display([['F', 'X', 'F', 'F', 'F', 'X'],\n ['g1', 'F', 'F', 'F', 'F', 'e'],\n ['F', 'b', 'F', 'F', 'F', 'F'],\n ['X', 'F', 'g2', 'F', 'F', 'X'],\n ['F', 'X', 'F', 'F', 'F', 'F'],\n ['F', 'F', 'F', 'F', 'F', 'F']])\n sys.stdout = sys.__stdout__\n print('Captured',capturedOutput.getvalue())\n\ndef display(board):\n board_size=len(board)\n for row in range(0,board_size):\n for col in range(0,board_size):\n print(\"%-2s\"%(board[row][col]),end=' ')\n print()\n return board\n\nif __name__==\"__main__\":\n\n test_display()\n","sub_path":"display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"247312714","text":"import random\n\nPIECES = [\n {\n '''\n #.\n #.\n #.\n ##\n '''\n 'id' : 'A',\n 'shape' : '24#.#.#.##', \n 'color' : [244, 117, 33],\n },{\n '''\n ..#\n .##\n ##.\n '''\n 'id' : 'B',\n 'shape' : '33..#.####.', \n 'color' : [119, 192, 66],\n },{\n '''\n #.#\n ###\n '''\n 'id' : 'C',\n 'shape' : '32#.####', \n 'color' : [255, 234, 1],\n },\n {\n '''\n #.\n ##\n .#\n .#\n '''\n 'id' : 'D',\n 'shape' : '24#.##.#.#', \n 'color' : [56, 46, 141],\n },\n {\n 'id' : 'E',\n '''\n ###\n .##\n '''\n 'shape' : '32###.##', \n 'color' : [208, 108, 170],\n },\n {\n '''\n ..#\n ###\n #..\n '''\n 'id' : 'F',\n 'shape' : '33..#####..', \n 'color' : [0, 176, 211],\n },\n {\n '''\n #..\n ###\n #..\n '''\n 'id' : 'G',\n 'shape' : '33#..####..', \n 'color' : [[0, 167, 78]],\n },\n {\n '''\n .#\n ##\n .#\n .#\n '''\n 'id' : 'H',\n 'shape' : '24.###.#.#', \n 'color' : [113, 55, 31],\n },\n {\n '#####'\n 'id' : 'I',\n 'shape' : '51#####', \n 'color' : [60, 123, 191],\n },\n {\n '''\n .#.\n ###\n .#.\n '''\n 'id' : 'J',\n 'shape' : '33.#.###.#.', \n 'color' : [237, 26, 56],\n },\n {\n '''\n ..#\n ###\n .#.\n '''\n 'id' : 'K',\n 'shape' : '33..####.#.', \n 'color' : [120, 133, 140],\n },{\n '''\n ###\n ..#\n ..#\n '''\n 'id' : 'L',\n 'shape' : '33###..#..#', \n 'color' : [15, 160, 219],\n },\n]\n\ndef flip(piece):\n \"\"\"\n Create a new piece that is flipped along the X axis from the given piece.\n Arguments:\n piece : 2D array -- the ascii representation of the given piece\n Returns:\n 2D array -- the ascii representation of the new piece\n \"\"\"\n # Yes, there is some slice magic I could use here instead\n ret = []\n for y in range(len(piece)-1,-1,-1):\n ret.append(piece[y])\n return ret\n\ndef turn(piece,dist):\n \"\"\"\n Create a new piece that is a clockwise rotation of the given piece.\n The number of turns is passed in, thus \"3\" is actually 1 rotation\n counterclockwise.\n Arguments:\n piece : 2D array -- the ascii representation of the given piece\n Returns:\n 2D array -- the ascii representation of the new piece\n \"\"\"\n for _ in range(dist):\n ret = []\n for x in range(len(piece[0])):\n nr = []\n for y in range(len(piece)-1,-1,-1):\n nr.append(piece[y][x])\n ret.append(nr)\n piece = ret\n return ret\n\ndef print_piece(piece,flat=False):\n \"\"\"\n Return a string representation of the given piece sutable\n for printing.\n Arguments: \n piece : 2D array -- the ascii representation of the given piece\n flat: true to leave out line feeds\n Returns:\n string representation of the new piece\n \"\"\"\n ret = ''\n if flat:\n ret = str(len(piece[0]))+str(len(piece))\n for y in range(len(piece)):\n for x in range(len(piece[y])):\n ret = ret + piece[y][x]\n if not flat:\n ret = ret + '\\n'\n return ret\n\ndef shrink(piece):\n \"\"\"\n Remove the empty columns and rows from a piece\n Arguments:\n piece : the piece to shrink in place\n \"\"\"\n for y in range(len(piece)-1,-1,-1):\n if not '#' in piece[y]:\n del piece[y]\n for x in range(len(piece[0])-1,-1,-1):\n fnd = False\n for y in range(len(piece)):\n if piece[y][x]=='#':\n fnd = True\n break\n if not fnd:\n for y in range(len(piece)):\n del piece[y][x]\n\ndef make_all_pieces():\n uniques = []\n\n for _ in range(1000):\n piece = [\n ['.','.','.','.','.','.','.','.','.'],\n ['.','.','.','.','.','.','.','.','.'],\n ['.','.','.','.','.','.','.','.','.'],\n ['.','.','.','.','.','.','.','.','.'],\n ['.','.','.','.','.','.','.','.','.'],\n ['.','.','.','.','.','.','.','.','.'],\n ['.','.','.','.','.','.','.','.','.'],\n ['.','.','.','.','.','.','.','.','.'],\n ['.','.','.','.','.','.','.','.','.'], \n ]\n\n offs = [\n (0,-1), # Up\n (1,0), # right\n (0,1), # down\n (-1,0), # left\n ]\n\n piece[4][4]='#'\n squares = [(4,4)]\n\n while(len(squares)<5):\n x,y = random.choice(squares)\n ofx,ofy = random.choice(offs)\n x += ofx\n y += ofy\n if piece[y][x] == '.':\n piece[y][x] = '#'\n squares.append((x,y))\n\n shrink(piece)\n m_piece = flip(piece)\n\n if (piece not in uniques and turn(piece,1) not in uniques and turn(piece,2) not in uniques and turn(piece,3) not in uniques and\n m_piece not in uniques and turn(m_piece,1) not in uniques and turn(m_piece,2) not in uniques and turn(m_piece,3) not in uniques): \n uniques.append(piece)\n\n return uniques\n\n\nuniques = make_all_pieces()\n\nfor piece in uniques:\n print('-----')\n g = print_piece(piece,flat=True)\n print(g)\n g = print_piece(piece)\n print(g)\n\nprint(len(uniques))\n\n# 23#####.\n# ##\n# ##\n# #.\n\ndef make_empty_board(num_pieces):\n ret = []\n for y in range(5):\n r = []\n for x in range(num_pieces):\n r.append('.')\n ret.append(r)\n print(ret)\n return ret\n\ndef place_piece(board,piece,x,y):\n for iy in range(len(piece)):\n for ix in range(len(piece[0])):\n a = piece[iy][ix]\n if a=='.':\n continue\n if board[y+iy][x+ix]!='.':\n raise Exception('Space not empty')\n board[y+iy][x+ix] = piece[iy][ix]\n\ndef can_place_piece(board,piece):\n for y in range(len(board)-len(piece)+1):\n for x in range(len(board[0])-len(piece[0])+1):\n ok = True\n for iy in range(len(piece)): \n for ix in range(len(piece[0])):\n a = board[y+iy][x+ix]\n b = piece[iy][ix]\n if b=='.' or a=='.':\n continue\n ok = False\n break\n if not ok:\n break \n if ok:\n break\n if ok:\n break \n return ok,x,y\n\nboard = make_empty_board(4)\n\npiece = uniques[0]\nok,x,y = can_place_piece(board,piece)\nif ok:\n place_piece(board,piece,x,y)\nprint(print_piece(board))\n\npiece = uniques[1]\nok,x,y = can_place_piece(board,piece)\nif ok:\n place_piece(board,piece,x,y)\nprint(print_piece(board))","sub_path":"src/new/five.py","file_name":"five.py","file_ext":"py","file_size_in_byte":7063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"304093489","text":"from prompt_toolkit import prompt\nfrom prompt_toolkit.application import run_in_terminal\nfrom prompt_toolkit.key_binding import KeyBindings\nimport os\nfrom mavfleetcontrol.craft import Craft\nfrom pymavlink import mavutil\nimport sys, select\nfrom mavfleetcontrol.actions.point import FlyToPoint\nfrom mavfleetcontrol.actions.circle import Circle\nfrom mavfleetcontrol.actions.land import land\n\nimport numpy as np\n\ni = 2\nterminalart = r\"\"\"\n___________ _________________ _________\n\\__ ___/ / _____/\\_ ___ \\ / _____/\n | | ______ / \\ ___/ \\ \\/ \\_____ \\ \n | | /_____/ \\ \\_\\ \\ \\____/ \\\n |____|erminal \\______ /\\______ /_______ /\n\t\t\t\t\t\t \\/ \\/ \\/ \"\"\"\n\nprint(terminalart)\nbindings = KeyBindings()\n# directory = \"/home/jules/MAVFleetControl\"\n# scripts = os.listdir(directory)\n\n# valid_scripts = []\n# for script in scripts:\n# \tif script.endswith('py'):\n# \t\tvalid_scripts.append(script)\n# print('Availible Options:')\n# for x in range(len(valid_scripts)):\n# \tprint(str(x)+'. ' + (valid_scripts[x])[:-3])\n\nloop = True\n#-------------------------------------------------------------------\ndef print_main_page():\n\tprint('1: Connect To Aircraft')\n\tprint('2: Actions')\n\tprint('3: Status')\n\tprint('4: Settings')\n\ndef connect_to_aircraft():\n\ttext = prompt('TGCS> How many aircraft?: ', key_bindings=bindings)\n\ttext = prompt('TGCS> Serial (1) or IP (2)', key_bindings=bindings)\n\tif text == '1': \n\t\tif sys.platform == \"darwin\":\n\t\t\tserialport = \"/dev/tty.usbmodem1\"\n\t\telse:\n\t\t\tserial_list = mavutil.auto_detect_serial(preferred_list=['*FTDI*',\n\t\t\t\t\"*Arduino_Mega_2560*\", \"*3D_Robotics*\", \"*USB_to_UART*\", '*PX4*', '*FMU*', \"*Gumstix*\"])\n\n\t\t\tif len(serial_list) == 0:\n\t\t\t\tprint(\"Error: no serial connsection found\")\n\t\t\t\treturn\n\n\t\t\tif len(serial_list) > 1:\n\t\t\t\tprint('Auto-detected serial ports are:')\n\t\t\t\tfor port in serial_list:\n\t\t\t\t\tprint(\" {:}\".format(port))\n\t\t\tprint('Using port {:}'.format(serial_list[0]))\n\t\t\tserialport = serial_list[0].device\n\t\tdrone = Craft('drone0','serial://' + serialport +':57600')\n\t\t\n\n\tif text =='2':\n\t\tdrone = Craft('drone0','udp://:14540')\t\n\tdrone.start()\n\treturn drone\ndef actions(drone):\n\n\tdrone.add_action(FlyToPoint(np.array([0,0,-10]),tolerance =1))\n\tdrone.add_action(land)\n# will run after FLYTOPOINT IS DONE)\n\ndef status(drone):\n\tprint('s')\n\tdrone.add_action(FlyToPoint(np.array([0,0,-5]),tolerance =1))\n\tdrone.add_action(land)\n\t# drone.close_conn()#will run after FLYTOPOINT IS DONE)\n\n\ndef settings():\n\tprint('set')\n\n\n\n\n# @bindings.add('c-t')\n# def _(event):\n# \t\" Say 'hello' when `c-t` is pressed. \"\n# \tdef print_hello():\n# \t\tprint('hello world')\n# \trun_in_terminal(print_hello)\n\n@bindings.add('c-c')\ndef _(event):\n\tprint(\"\\n\\n\\n\\n\")\n\tprint(\"Good Bye!, may your props be intact\")\n\tevent.app.exit()\n\tglobal loop\n\tloop = False\n\n\n#----------------------------------------------------------------------\n\nprint(\"Welcome!\")\ndrones = None\nwhile loop == True:\n\tprint_main_page()\n\ttext = prompt('TGCS> ', key_bindings=bindings)\n\tif text == '1':\n\t\tdrones = connect_to_aircraft()\n\tif text == '2':\n\t\tactions(drones)\n\tif text =='3':\n\t\tstatus(drones)\n\tif text == '4':\n\t\tsettings()\n\n\ndrones.override_action('exit')","sub_path":"TerminalGCS.py","file_name":"TerminalGCS.py","file_ext":"py","file_size_in_byte":3190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"575787714","text":"#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Generate HTTP tests from YAML files\n\nEach HTTP request is its own TestCase and can be requested to be run in\nisolation from other tests. If it is a member of a sequence of requests,\nprior requests will be run.\n\nA sequence is represented by an ordered list in a single YAML file.\n\nEach sequence becomes a TestSuite.\n\nAn entire directory of YAML files is a TestSuite of TestSuites.\n\"\"\"\n\nimport copy\nimport glob\nimport inspect\nimport os\nfrom unittest import suite\nimport uuid\n\nimport six\nimport yaml\n\nfrom gabbi import case\nfrom gabbi import handlers\nfrom gabbi import httpclient\nfrom gabbi import suite as gabbi_suite\n\nRESPONSE_HANDLERS = [\n handlers.HeadersResponseHandler,\n handlers.StringResponseHandler,\n handlers.JSONResponseHandler,\n]\n\n\nclass GabbiFormatError(ValueError):\n \"\"\"An exception to encapsulate poorly formed test data.\"\"\"\n pass\n\n\nclass TestBuilder(type):\n \"\"\"Metaclass to munge a dynamically created test.\"\"\"\n\n required_attributes = {'has_run': False}\n\n def __new__(mcs, name, bases, attributes):\n attributes.update(mcs.required_attributes)\n return type.__new__(mcs, name, bases, attributes)\n\n\ndef build_tests(path, loader, host=None, port=8001, intercept=None,\n test_loader_name=None, fixture_module=None,\n response_handlers=None, prefix=None):\n \"\"\"Read YAML files from a directory to create tests.\n\n Each YAML file represents an ordered sequence of HTTP requests.\n\n :param path: The directory where yaml files are located.\n :param loader: The TestLoader.\n :param host: The host to test against. Do not use with ``intercept``.\n :param port: The port to test against. Used with ``host``.\n :param intercept: WSGI app factory for wsgi-intercept.\n :param test_loader_name: Base name for test classes. Rarely used.\n :param fixture_module: Python module containing fixture classes.\n :param response_handers: ResponseHandler classes.\n :type response_handlers: List of ResponseHandler classes.\n :param prefix: A URL prefix for all URLs that are not fully qualified.\n :rtype: TestSuite containing multiple TestSuites (one for each YAML file).\n \"\"\"\n\n if not (bool(host) ^ bool(intercept)):\n raise AssertionError('must specify exactly one of host or intercept')\n\n response_handlers = response_handlers or []\n top_suite = suite.TestSuite()\n\n if test_loader_name is None:\n test_loader_name = inspect.stack()[1]\n test_loader_name = os.path.splitext(os.path.basename(\n test_loader_name[1]))[0]\n\n yaml_file_glob = '%s/*.yaml' % path\n\n # Initialize the extensions for response handling.\n for handler in RESPONSE_HANDLERS + response_handlers:\n handler(case.HTTPTestCase)\n\n # Return an empty suite if we have no host to access, either via\n # a real host or an intercept\n for test_file in glob.iglob(yaml_file_glob):\n if intercept:\n host = str(uuid.uuid4())\n test_yaml = load_yaml(test_file)\n test_name = '%s_%s' % (test_loader_name,\n os.path.splitext(\n os.path.basename(test_file))[0])\n file_suite = test_suite_from_yaml(loader, test_name, test_yaml,\n path, host, port, fixture_module,\n intercept, prefix)\n top_suite.addTest(file_suite)\n return top_suite\n\n\ndef load_yaml(yaml_file):\n \"\"\"Read and parse any YAML file. Let exceptions flow where they may.\"\"\"\n with open(yaml_file) as source:\n return yaml.safe_load(source.read())\n\n\ndef test_update(orig_dict, new_dict):\n \"\"\"Modify test in place to update with new data.\"\"\"\n for key, val in six.iteritems(new_dict):\n if key == 'data':\n orig_dict[key] = val\n elif isinstance(val, dict):\n orig_dict[key].update(val)\n elif isinstance(val, list):\n orig_dict[key] = orig_dict.get(key, []) + val\n else:\n orig_dict[key] = val\n\n\ndef test_suite_from_yaml(loader, test_base_name, test_yaml, test_directory,\n host, port, fixture_module, intercept, prefix=None):\n \"\"\"Generate a TestSuite from YAML data.\"\"\"\n\n file_suite = gabbi_suite.GabbiSuite()\n try:\n test_data = test_yaml['tests']\n except KeyError:\n raise GabbiFormatError(\n 'malformed test file, \"tests\" key required')\n except TypeError:\n # Swallow this exception as displaying it does not shine a\n # light on the path to fix it.\n raise GabbiFormatError('malformed test file, invalid format')\n\n fixtures = test_yaml.get('fixtures', None)\n\n # Set defaults from BASE_TESTS then update those defaults\n # with any defaults set in the YAML file.\n base_test_data = copy.deepcopy(case.HTTPTestCase.base_test)\n defaults = _validate_defaults(test_yaml.get('defaults', {}))\n test_update(base_test_data, defaults)\n\n # Establish any fixture classes.\n fixture_classes = []\n if fixtures and fixture_module:\n for fixture_class in fixtures:\n fixture_classes.append(getattr(fixture_module, fixture_class))\n\n prior_test = None\n base_test_key_set = set(case.HTTPTestCase.base_test.keys())\n for test_datum in test_data:\n test = copy.deepcopy(base_test_data)\n try:\n test_update(test, test_datum)\n except AttributeError as exc:\n if not isinstance(test_datum, dict):\n raise GabbiFormatError(\n 'test chunk is not a dict at \"%s\"' % test_datum)\n else:\n # NOTE(cdent): Not clear this can ever happen but just in\n # case.\n raise GabbiFormatError(\n 'malformed test chunk \"%s\": %s' % (test_datum, exc))\n\n if not test['name']:\n raise GabbiFormatError('Test name missing in a test in %s.'\n % test_base_name)\n test_name = '%s_%s' % (test_base_name,\n test['name'].lower().replace(' ', '_'))\n\n # use uppercase keys as HTTP method\n method_key = None\n for key, val in six.iteritems(test):\n if _is_method_shortcut(key):\n if method_key:\n raise GabbiFormatError(\n 'duplicate method/URL directive in \"%s\"' %\n test_name)\n\n test['method'] = key\n test['url'] = val\n method_key = key\n if method_key:\n del test[method_key]\n\n if not test['url']:\n raise GabbiFormatError('Test url missing in test %s.'\n % test_name)\n\n test_key_set = set(test.keys())\n if test_key_set != base_test_key_set:\n raise GabbiFormatError(\n 'Invalid test keys used in test %s: %s'\n % (test_name,\n ', '.join(list(test_key_set - base_test_key_set))))\n\n # Use metaclasses to build a class of the necessary type\n # and name with relevant arguments.\n http_class = httpclient.get_http(verbose=test['verbose'],\n caption=test_name)\n klass = TestBuilder(test_name, (case.HTTPTestCase,),\n {'test_data': test,\n 'test_directory': test_directory,\n 'fixtures': fixture_classes,\n 'http': http_class,\n 'host': host,\n 'intercept': intercept,\n 'port': port,\n 'prefix': prefix,\n 'prior': prior_test})\n\n tests = loader.loadTestsFromTestCase(klass)\n this_test = tests._tests[0]\n file_suite.addTest(this_test)\n prior_test = this_test\n\n return file_suite\n\n\ndef _validate_defaults(defaults):\n \"\"\"Ensure default test settings are acceptable\n\n Raises GabbiFormatError for invalid settings.\n \"\"\"\n if any(_is_method_shortcut(key) for key in defaults):\n raise GabbiFormatError(\n '\"METHOD: url\" pairs not allowed in defaults')\n return defaults\n\n\ndef _is_method_shortcut(key):\n return key.isupper()\n","sub_path":"gabbi/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":8862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"241928490","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Setting up some strings globals\nNAME = \"DiscoLog\"\n\n# Import modules with try and catch\ntry:\n import argparse\n import discord\n import getpass\n import progressbar\n import shlex\n import sys\n import os\n from datetime import timedelta\nexcept ImportError as message:\n print(\"Missing package(s) for %s: %s\" % (NAME, message))\n exit(12)\n\n# Import classes\ntry:\n from classes import Logger\nexcept ImportError as message:\n print(\"Missing python class(s) for %s: %s\" % (NAME, message))\n exit(12)\n\n\nclient = discord.Client()\nlogger = Logger.Logger()\n\n\n# Get PM and write them in chat_logs/Private_Messages/{NAME}-{ID}.log\nasync def get_private_messages():\n\n summary = open(\"chat_logs/summary.txt\", 'w')\n bar = progressbar.ProgressBar(redirect_stdout=True,\n widgets=[progressbar.Percentage(), \" \",\n progressbar.Bar(), ' [', progressbar.Timer(), ']', ])\n\n for chan in bar(client.private_channels):\n recipients = chan.me.name + \", \"\n for recipient in chan.recipients:\n recipients += recipient.name + (\"\" if recipient is chan.recipients[-1] else \", \")\n\n if (chan.name is not None):\n print(\"Fetching messages from the private channel \\\"\" + chan.name + \"\\\"\")\n #log_file = open(\"chat_logs/\" + chan.name + \"-\" + chan.id + \".log\", 'w')\n else:\n print(\"Fecthing messages from a chat with \" + recipients)\n #log_file = open(\"chat_logs/\" + recipients + \"-\" + chan.id + \".log\", 'w')\n\n log_file = open(\"chat_logs/\" + chan.id + \".log\", 'w')\n\n bar.update()\n\n # Get all messages\n messages = []\n async for item in client.logs_from(chan, limit=sys.maxsize):\n messages.append(item)\n\n # Make the header\n header = \"ID: %s\\n\" % chan.id\n header += \"Recipients:\" + recipients + \"\\n\"\n if (chan.name is not None):\n header += \"Chan name: \" + chan.name + \"\\n\"\n header += chan.created_at.strftime(\"Created at: %A %d %b %Y %H:%M:%S UTC\\n\")\n header += \"Length: %d messages\\n\\n\" % len(messages)\n\n # Write the header in the summary and in the chat log file\n log_file.write(header)\n summary.write(header)\n\n # Yeah I know the limit is maybe a bit too higher\n for msg in reversed(messages):\n log_file.write((msg.timestamp + timedelta(hours=1)).strftime(\"%Y-%m-%d %H:%M:%S\\t\"))\n log_file.write(msg.author.name + \"\\t\")\n log_file.write(msg.content + \"\\n\")\n log_file.close()\n summary.close()\n\n\n# Launch the getter when the bot is ready\n@client.async_event\ndef on_ready():\n user = client.user\n logger.log_info_print(\"Sucessfully connected as %s (%s)\" % (user.name, user.id))\n logger.logger.info(\"------------\")\n print()\n\n if not (os.path.exists(\"chat_logs\")):\n os.makedirs(\"chat_logs\")\n\n logger.log_info_print(\"Getting private messages\")\n yield from get_private_messages()\n print(\"Done.\")\n logger.logger.info(\"Done.\")\n\n yield from client.logout()\n logger.logger.info(\"#--------------END--------------#\")\n return\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"\")\n parser.add_argument(\"email\")\n args = parser.parse_args()\n password = getpass.getpass()\n client.run(args.email, password)\n return\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"DiscoLog/DiscoLog.py","file_name":"DiscoLog.py","file_ext":"py","file_size_in_byte":3483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"52571469","text":"from tkinter import *\r\n\r\nroot = Tk()\r\nroot.geometry(\"300x500\")\r\nroot.title(\"TIC TAC TOE\")\r\n\r\nhead = Label(root,text=\"TIC-TAC-TOE\",fg=\"forestgreen\",bg=\"light cyan\",font=(\"Arial\",20,\"italic\"))\r\nhead.pack()\r\n\r\np1_name = \"\"\r\np2_name = \"\"\r\nSTART = False\r\ndef Start():\r\n global p1_name,p2_name,START\r\n P1 = p1.get()\r\n P2 = p2.get()\r\n\r\n if P1.split() == []:\r\n text = \"Enter Player 1 Name\"\r\n turn.place(x=50,y=455)\r\n turn['fg'] = \"red\"\r\n turn['text'] = text\r\n elif P2.split() == []:\r\n text = \"Enter Player 2 Name\"\r\n turn.place(x=50,y=455)\r\n turn['fg'] = \"red\"\r\n turn['text'] = text\r\n elif P1.split() == P2.split():\r\n text = \"Enter Different Player Names\"\r\n turn.place(x=25,y=455)\r\n turn['fg'] = \"red\"\r\n turn['text'] = text\r\n else:\r\n p1_name = P1\r\n p2_name = P2\r\n p1['font'] = (\"Arial\",8,\"bold\")\r\n p2['font'] = (\"Arial\",8,\"bold\")\r\n p1['state']=DISABLED\r\n p2['state']=DISABLED\r\n\r\n start.place(x=1000,y=1000)\r\n turn['text'] = \"{}{} Turn\".format(p1_name,\"'s\")\r\n turn['fg'] = \"blue\"\r\n turn['font'] = (\"Ubuntu\",20,\"bold\")\r\n turn.place(x=50,y=425)\r\n START = True\r\n \r\ndef WinCheck():\r\n if b1['text'] == \"O\" and b2['text'] == \"O\" and b3['text'] == \"O\":\r\n b1['bg']=\"light green\";b2['bg']=\"light green\";b3['bg']=\"light green\"\r\n return \"p1\"\r\n elif b4['text'] == \"O\" and b5['text'] == \"O\" and b6['text'] == \"O\":\r\n b4['bg']=\"light green\";b5['bg']=\"light green\";b6['bg']=\"light green\"\r\n return \"p1\"\r\n elif b7['text'] == \"O\" and b8['text'] == \"O\" and b9['text'] == \"O\":\r\n b7['bg']=\"light green\";b8['bg']=\"light green\";b9['bg']=\"light green\"\r\n return \"p1\"\r\n elif b1['text'] == \"O\" and b4['text'] == \"O\" and b7['text'] == \"O\":\r\n b1['bg']=\"light green\";b4['bg']=\"light green\";b7['bg']=\"light green\"\r\n return \"p1\"\r\n elif b2['text'] == \"O\" and b5['text'] == \"O\" and b8['text'] == \"O\":\r\n b2['bg']=\"light green\";b5['bg']=\"light green\";b8['bg']=\"light green\"\r\n return \"p1\"\r\n elif b3['text'] == \"O\" and b6['text'] == \"O\" and b9['text'] == \"O\":\r\n b3['bg']=\"light green\";b6['bg']=\"light green\";b9['bg']=\"light green\"\r\n return \"p1\"\r\n elif b1['text'] == \"O\" and b5['text'] == \"O\" and b9['text'] == \"O\":\r\n b1['bg']=\"light green\";b5['bg']=\"light green\";b9['bg']=\"light green\"\r\n return \"p1\"\r\n elif b3['text'] == \"O\" and b5['text'] == \"O\" and b7['text'] == \"O\":\r\n b3['bg']=\"light green\";b5['bg']=\"light green\";b7['bg']=\"light green\"\r\n return \"p1\"\r\n \r\n if b1['text'] == \"X\" and b2['text'] == \"X\" and b3['text'] == \"X\":\r\n b1['bg']=\"light blue\";b2['bg']=\"light blue\";b3['bg']=\"light blue\"\r\n return \"p2\"\r\n elif b4['text'] == \"X\" and b5['text'] == \"X\" and b6['text'] == \"X\":\r\n b4['bg']=\"light blue\";b5['bg']=\"light blue\";b6['bg']=\"light blue\"\r\n return \"p2\"\r\n elif b7['text'] == \"X\" and b8['text'] == \"X\" and b9['text'] == \"X\":\r\n b7['bg']=\"light blue\";b8['bg']=\"light blue\";b9['bg']=\"light blue\"\r\n return \"p2\"\r\n elif b1['text'] == \"X\" and b4['text'] == \"X\" and b7['text'] == \"X\":\r\n b1['bg']=\"light blue\";b4['bg']=\"light blue\";b7['bg']=\"light blue\"\r\n return \"p2\"\r\n elif b2['text'] == \"X\" and b5['text'] == \"X\" and b8['text'] == \"X\":\r\n b2['bg']=\"light blue\";b5['bg']=\"light blue\";b8['bg']=\"light blue\"\r\n return \"p2\"\r\n elif b3['text'] == \"X\" and b6['text'] == \"X\" and b9['text'] == \"X\":\r\n b3['bg']=\"light blue\";b6['bg']=\"light blue\";b9['bg']=\"light blue\"\r\n return \"p2\"\r\n elif b1['text'] == \"X\" and b5['text'] == \"X\" and b9['text'] == \"X\":\r\n b1['bg']=\"light blue\";b5['bg']=\"light blue\";b9['bg']=\"light blue\"\r\n return \"p2\"\r\n elif b3['text'] == \"X\" and b5['text'] == \"X\" and b7['text'] == \"X\":\r\n b3['bg']=\"light blue\";b5['bg']=\"light blue\";b7['bg']=\"light blue\"\r\n return \"p2\"\r\n \r\n elif (b1['text'] != \"\" and b2['text'] != \"\" and b3['text'] != \"\" and\r\n b4['text'] != \"\" and b5['text'] != \"\" and b6['text'] != \"\" and\r\n b7['text'] != \"\" and b8['text'] != \"\" and b9['text'] != \"\"):\r\n return \"tie\"\r\n \r\n else:\r\n return False\r\ndef DisableButtons(ButtonList):\r\n for a in range(len(ButtonList)):\r\n ButtonList[a]['state'] = DISABLED\r\ndef EnableButtons(ButtonList):\r\n for a in range(len(ButtonList)):\r\n ButtonList[a]['state'] = NORMAL\r\ndef BtnClick(button):\r\n global START,p1_name,p2_name\r\n if START == True:\r\n if button['text'] == \"\":\r\n if turn['text'] == \"{}{} Turn\".format(p1_name,\"'s\"):\r\n button['text'] = \"O\"\r\n turn['text'] = \"{}{} Turn\".format(p2_name,\"'s\")\r\n else:\r\n button['text'] = \"X\"\r\n turn['text'] = \"{}{} Turn\".format(p1_name,\"'s\")\r\n\r\n check = WinCheck()\r\n if check != False:\r\n restart.place(x=105,y=470)\r\n START = False\r\n if check==\"p1\":\r\n text = \"{} Wins\".format(p1_name)\r\n buttons = [b1,b2,b3,b4,b5,b6,b7,b8,b9]\r\n Remove = []\r\n for i in range(9):\r\n if buttons[i]['bg'] == \"light green\":\r\n Remove.append(buttons[i])\r\n elif check==\"p2\":\r\n text = \"{} Wins\".format(p2_name)\r\n buttons = [b1,b2,b3,b4,b5,b6,b7,b8,b9]\r\n Remove = []\r\n for i in range(9):\r\n if buttons[i]['bg'] == \"light blue\":\r\n Remove.append(buttons[i])\r\n else:\r\n text = \"It is a tie !\"\r\n turn['fg'] = \"forestgreen\"\r\n turn['text'] = text\r\n\r\n if check == \"p1\" or check == \"p2\":\r\n for i in range(len(Remove)):\r\n buttons.remove(Remove[i])\r\n DisableButtons(buttons)\r\n\r\ndef Restart():\r\n Buttons = [b1,b2,b3,b4,b5,b6,b7,b8,b9]\r\n EnableButtons([p1,p2])\r\n EnableButtons(Buttons)\r\n restart.place(x=1000,y=1000)\r\n for a in range(len(Buttons)):\r\n Buttons[a]['text'] = \"\"\r\n Buttons[a]['bg'] = \"SystemButtonFace\"\r\n turn['text'] = \"\"\r\n start.place(x=107,y=410)\r\n p1['font'] = \"TkTextFont\"\r\n p2['font'] = \"TkTextFont\"\r\n####################################################################################\r\n\r\nLabel(root,text=\"Player 1 :\",fg=\"brown\",font=(\"Courier\",10,\"bold\")).place(x=0,y=50)\r\np1 = Entry(root)\r\np1.place(x=90,y=52)\r\n\r\nLabel(root,text=\"Player 2 :\",fg=\"brown\",font=(\"Courier\",10,\"bold\")).place(x=0,y=75)\r\np2 = Entry(root)\r\np2.place(x=90,y=77)\r\n\r\nstart = Button(root,text=\"START\",bg=\"gray90\",fg=\"green\",font=(\"Ubuntu\",15,\"bold\"),command=Start)\r\nstart.place(x=107,y=410)\r\n\r\nturn = Label(root,text=\"\",font=(\"Ubuntu\",15,\"normal\"))\r\nturn.place(x=50,y=455)\r\n\r\n###################################\r\n\r\nb1 = Button(root,width=13,height=6,command = lambda:BtnClick(b1))\r\nb1.place(x=0,y=100)\r\n\r\nb2 = Button(root,width=13,height=6,command = lambda:BtnClick(b2))\r\nb2.place(x=100,y=100)\r\n\r\nb3 = Button(root,width=13,height=6,command = lambda:BtnClick(b3))\r\nb3.place(x=200,y=100)\r\n\r\nb4 = Button(root,width=13,height=6,command = lambda:BtnClick(b4))\r\nb4.place(x=0,y=200)\r\n\r\nb5 = Button(root,width=13,height=6,command = lambda:BtnClick(b5))\r\nb5.place(x=100,y=200)\r\n\r\nb6 = Button(root,width=13,height=6,command = lambda:BtnClick(b6))\r\nb6.place(x=200,y=200)\r\n\r\nb7 = Button(root,width=13,height=6,command = lambda:BtnClick(b7))\r\nb7.place(x=0,y=300)\r\n\r\nb8 = Button(root,width=13,height=6,command = lambda:BtnClick(b8))\r\nb8.place(x=100,y=300)\r\n\r\nb9 = Button(root,width=13,height=6,command = lambda:BtnClick(b9))\r\nb9.place(x=200,y=300)\r\n\r\n###################################\r\n\r\nrestart = Button(root,text=\"Restart\",fg=\"blue\",bg=\"aquamarine\",width = 10,height=1,font=(\"Courier\",10,\"bold\"),command = Restart)\r\n##restart.place(x=105,y=470)\r\nrestart.place(x=1000,y=1000)\r\n\r\nroot.mainloop()\r\n","sub_path":"tic_tac_toe.py","file_name":"tic_tac_toe.py","file_ext":"py","file_size_in_byte":8013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"333707798","text":"import pygame\nimport importlib\nfrom Utils.ServiceLocator import ServiceLocator, ServiceNames\nfrom Tiled.TiledMap import TiledObjectItem\nfrom SpriteIntelligence import DefaultSpriteIntelligence\nfrom Utils.CollosionInfo import CollosionInfo\nfrom Utils.ViewPointer import ViewPoint\n\nclass SpriteMoveState():\n FallingDown = 1\n Standing = 2\n MoveLeft = 3\n MoveRight = 4\n\nclass SpritePropNames():\n Points = \"Points\"\n Style = \"Style\"\n KillSprite =\"KillSprite\"\n KillPlayer = \"KillPlayer\"\n Behavior = \"Behavior\"\n Supplies = \"Supplies\"\n Energy = \"Energy\"\n Sound = \"Sound\"\n Intelligence = \"Intelligence\"\n AssetName = \"AssetName\"\n\n\nclass SpriteBase(pygame.sprite.Sprite):\n \"\"\"The sprite base class.\"\"\"\n\n def __init__(self):\n \"\"\"Constructor of the sprite base class.\"\"\"\n super().__init__()\n self._name = None\n self._x = None\n self._y = None\n self._assetName = None # The path name for sprite resources.\n self._points = 0 # Points the player gets if this item is touched.\n self._energy = 0 # Energy points the player gets if this is touched.\n self._style = None # The animation style\n self._intelligence = None # artificial intelligence to drive this sprite.\n self._killSprite = True # True if this sprite dies if the player touch it\n self._killPlayer = False # True if the player dies on collision.\n self._sound = None # Contains the sound file that is played on collision.\n self._supplies = None # Items the player gets if sprite is touched.\n self._behavior = None # Special coded behavior that is executed if collided with the player sprite.\n self._viewPointer = ServiceLocator.getGlobalServiceInstance(ServiceNames.ViewPointer)\n self.rect = None\n self._moveState = None\n self._lastCollide = None\n pass\n\n def configureSprite(self, properties):\n \"\"\"Consume the configured properties and assign the sprite behavior.\"\"\"\n assert isinstance(properties, TiledObjectItem), \"Expected properties to be of type TiledObjectItem.\"\n self._name = properties.name\n self._x = properties.x\n # Fix the y-Coordinate from tiled bug:\n self._y = properties.y - properties.height\n self.configureFromProperties(properties.properties)\n pass\n\n def configureFromProperties(self, properties):\n \"\"\"Configures the sprite from tmx object properties.\"\"\"\n def strToBool(value):\n return value in ['1', 'true', 'True', 'yes', 'Yes', 'jupp']\n if SpritePropNames.AssetName in properties:\n self._assetName = properties[SpritePropNames.AssetName]\n else:\n self._assetName = self.name\n\n if SpritePropNames.Points in properties:\n self.points = int(properties[SpritePropNames.Points])\n if SpritePropNames.Energy in properties:\n self.energy = int(properties[SpritePropNames.Energy])\n if SpritePropNames.KillSprite in properties:\n self.killSprite = strToBool(properties[SpritePropNames.KillSprite])\n if SpritePropNames.KillPlayer in properties:\n self.killPlayer = strToBool(properties[SpritePropNames.KillPlayer])\n if SpritePropNames.Sound in properties:\n self.sound = properties[SpritePropNames.Sound]\n if SpritePropNames.Style in properties:\n self.style = self.styleFactory(properties[SpritePropNames.Style], properties)\n if SpritePropNames.Behavior in properties:\n self.behavior = self.behaviorFactory(properties[SpritePropNames.Behavior], properties)\n if SpritePropNames.Supplies in properties:\n self.supplies = self.suppliesFactory(properties[SpritePropNames.Supplies], properties)\n if SpritePropNames.Intelligence in properties:\n self.intelligence = self.intelligenceFactory(properties[SpritePropNames.Intelligence], properties)\n #else:\n # if not self.intelligence:\n # self.intelligence = DefaultSpriteIntelligence(self)\n\n pass\n\n def styleFactory(self, styleClassName, properties):\n \"\"\"Creates a style class.\"\"\"\n module_name = \"SpriteStyles.{0}\".format(styleClassName)\n styleClass = getattr(importlib.import_module(module_name), styleClassName)\n return styleClass(self, properties)\n\n def behaviorFactory(self, behaviorClassName, properties):\n \"\"\"Returns a behavior class.\"\"\"\n module_name = \"SpriteBehaviors.{0}\".format(behaviorClassName)\n spriteBehaviorClass = getattr(importlib.import_module(module_name), behaviorClassName)\n return spriteBehaviorClass(self, properties)\n\n def intelligenceFactory(self, intelligenceClassName, properties):\n \"\"\"Returns a sprite intelligence class.\"\"\"\n module_name = \"SpriteIntelligence.{0}\".format(intelligenceClassName)\n spriteIntelligenceClass = getattr(importlib.import_module(module_name), intelligenceClassName)\n return spriteIntelligenceClass(self, properties)\n\n\n def suppliesFactory(self, supplyClassName, properties):\n \"\"\"Returns a sprite supply class.\"\"\"\n module_name = \"SpriteSupplies.{0}\".format(supplyClassName)\n spriteSupplyClass = getattr(importlib.import_module(module_name), supplyClassName)\n return spriteSupplyClass(self, properties)\n\n def getCollideInfo(self):\n \"\"\"Is called when the player collides with this sprite.\"\"\"\n result = CollosionInfo(spriteDies = self._killSprite, playerDies = self._killPlayer, points = self.points, energy = self._energy, parent = self, sound = self.sound)\n self.behavior.doCollide()\n return result\n pass\n\n\n def doCollide(self):\n if not self._lastCollide:\n self._lastCollide = pygame.time.get_ticks()\n return self.getCollideInfo()\n else:\n now = pygame.time.get_ticks()\n if now - self._lastCollide > 300:\n self._lastCollide = now\n return self.getCollideInfo()\n else:\n return None \n \n\n def update(self, *args):\n \"\"\"Updates the sprite.\"\"\"\n ticks = pygame.time.get_ticks()\n \n self.image = self._style.getImage(self, ticks)\n if not self.rect:\n self.rect = self.image.get_rect()\n self._intelligence.updatePosition(self, ticks)\n\n super().update(*args)\n \n @property\n def name(self):\n \"\"\"The name of the sprite.\"\"\"\n return self._name\n \n @name.setter\n def name(self, value):\n self._name = value\n \n @property\n def x(self):\n \"\"\"The x-position of the sprite.\"\"\"\n return self._x\n @x.setter\n def x(self, value):\n self._x = value\n \n @property\n def y(self):\n \"\"\"The y-position of the sprite.\"\"\"\n return self._y\n\n @y.setter\n def y(self, value):\n self._y = value\n\n @property\n def position(self):\n return ViewPoint(self._x, self._y)\n\n @property\n def points(self):\n \"\"\"Points the player gets if this item is touched.\"\"\"\n return self._points\n @points.setter\n def points(self, value):\n self._points = value\n\n @property\n def energy(self):\n \"\"\"Energy points the player gets if this is touched.\"\"\"\n return self._energy\n @energy.setter\n def energy(self, value):\n self._energy = value\n\n @property\n def style(self):\n \"\"\"The animation style.\"\"\"\n return self._style\n @style.setter\n def style(self, value):\n self._style = value\n\n @property\n def intelligence(self):\n \"\"\"artificial intelligence to drive this sprite.\"\"\"\n return self._intelligence\n @intelligence.setter\n def intelligence(self, value):\n self._intelligence = value\n\n @property\n def killSprite(self):\n \"\"\" True if this sprite dies if the player touch it.\"\"\"\n return self._killSprite\n\n @killSprite.setter\n def killSprite(self, value):\n self._killSprite = value\n\n @property\n def killPlayer(self):\n \"\"\"True if the player dies on collision.\"\"\"\n return self._killPlayer\n @killPlayer.setter\n def killPlayer(self, value):\n self._killPlayer = value\n\n @property\n def sound(self):\n \"\"\"Contains the sound file that is played on collision.\"\"\"\n return self._sound\n @sound.setter\n def sound(self, value):\n self._sound = value\n\n @property\n def supplies(self):\n \"\"\" Items the player gets if sprite is touched.\"\"\"\n return self._supplies\n @supplies.setter\n def supplies(self, value):\n self._supplies = value\n\n @property\n def behavior(self):\n \"\"\"Special coded behavior that is executed if collided with the player sprite.\"\"\"\n return self._behavior\n @behavior.setter\n def behavior(self, value):\n self._behavior = value\n\n @property\n def assetName(self):\n return self._assetName\n\n @property\n def collideRect(self):\n \"\"\"Returns the collide rect. Override this property, if the collide rect is different.\"\"\"\n result = self.rect.copy()\n result.top = 0\n result.left = 0\n\n return result\n\n @property\n def moveState(self):\n return self._moveState\n\n @moveState.setter\n def moveState(self, value):\n if self._moveState != value:\n self._moveState = value\n self._style.setMoveState(value)\n\n\n \n\n\n\n\n","sub_path":"SimpleGame/SimpleGame/Src/Utils/sprites/SpriteBase.py","file_name":"SpriteBase.py","file_ext":"py","file_size_in_byte":9538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"108267344","text":"\"\"\"Packaging configuration.\"\"\"\nimport os\n\nfrom setuptools import setup, find_packages\n\nwith open(os.path.abspath('VERSION.txt'), 'r') as fd:\n VERSION = fd.read().strip()\n\nsetup(\n name='custom_resources',\n version=VERSION,\n description='Custom resources for Troposphere/CloudFormation.',\n url='',\n author='VRT DPC',\n author_email='dpc@vrt.be',\n license='',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Programming Language :: Python :: 3.9',\n ],\n keywords='cloudformation aws',\n packages=['custom_resources'],\n data_files=['VERSION.txt'],\n install_requires=['troposphere', 'six'],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"521043491","text":"from names import Names\nfrom devices import Devices\nfrom network import Network\nfrom monitors import Monitors\nfrom parse import Parser\nfrom scanner import Symbol\nfrom scanner import Scanner\nfrom error import Error\n\nimport sys\nimport os\n\n\ndef open_file(path):\n try:\n \"\"\"Open and return the file specified by path for reading\"\"\"\n return open(path, \"r\", encoding=\"utf-8\")\n except IOError:\n print(\"error, can't find or open file\")\n sys.exit()\n\ndef main():\n \"\"\"Preliminary exercises for Part IIA Project GF2.\"\"\"\n\n # Check command line arguments\n arguments = sys.argv[1:]\n if len(arguments) != 1:\n print(\"Error! One command line argument is required.\")\n sys.exit()\n\n else:\n print(\"\\nNow opening file...\")\n # Print the path provided and try to open the file for reading\n path = os.getcwd()+ \"/\" + arguments[0]\n print(path) #print path\n names = Names()\n devices = Devices(names)\n network = Network(names, devices)\n monitors = Monitors(names, devices, network)\n scanner = Scanner(path, names)\n parser = Parser(names, devices, network, monitors, scanner)\n Error.reset()\n parser.parse_network()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"final/practice_test_parser.py","file_name":"practice_test_parser.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"61619907","text":"# Title: reader.py\n# Author: Sean O'Bryan\n# Goal: Use rfid reader with raspberry pi.\n# Description: \n#\t1.\tWhen presented with an appropriate rfid tag (uem4100), rfid reader gives raspberry pi a message through serial (uart pins). \n#\t2.\tRaspberry pi (code below) parses key from valid message and checks the key against a text file (access control list). \n#\t3.\tRaspberry pi opens door.\n\n# Links: \trfid reader - http://www.seeedstudio.com/depot/Electronic-brick-125Khz-RFID-Card-Reader-p-702.html\n#\t\t\traspberry pi model b revision 2.0\n\n# The exception will generate a custom message (error_message)\n# The exception will generate a stacktrace\ndef throws(error_message):\n\traise RuntimeError(error_message)\n\n# Get the rfid message, log/break if message format is bad\ndef extract_message(rfidInput):\n\trfidInput = enclosing_tags_check(rfidInput)\n\thex_check(rfidInput)\n\tcompute_check_sum(rfidInput)\n\treturn rfidInput[:-2]\n\t\ndef hex_check(rfidInput):\n\timport string\n\tif not all(c in string.hexdigits for c in rfidInput):\n\t\tthrows(\"Message contains invalid hex characters\")\n\t\t\ndef compute_check_sum(rfidInput):\n\tgiven = hex(int(rfidInput[10:],16))\n\trfidInput = rfidInput[:-2]\n\tuncomputed = bytearray.fromhex(rfidInput)\n\tcomputed = hex(uncomputed[0] ^ uncomputed[1] ^ uncomputed[2] ^ uncomputed[3] ^ uncomputed[4])\n\tlogger.info(\"Given checksum is %s\" % given)\n\tlogger.info(\"Computed checksum is %s\" % computed)\n\tif computed != given:\n\t\tthrows(\"Checksum is bad\")\n\n# Validating the incoming message\n# upon success, input returned with message and checksum only \ndef enclosing_tags_check(rfidInput):\n\tstartTag = \"\\x02\"\n\tendTag = \"\\x03\"\n\tif rfidInput.startswith(startTag):\n\t\trfidInput = rfidInput.replace(startTag,'')\n\telse:\n\t\tthrows(\"Enclosing tag not present\")\n\tif rfidInput.endswith(endTag):\n\t\trfidInput = rfidInput.replace(endTag,'')\n\telse:\n\t\tthrows(\"Enclosing tag not present\")\n\tif len(rfidInput) != 12:\n\t\tthrows(\"Message is not correct length\")\n\treturn rfidInput\n\n# Query the access control list (acl)\n# check access list for the rfid tag\ndef query_acl(rfid):\n\twith open('acl') as text:\n\t\tfor line in text:\n\t\t\tmember = line.split('|')\n\t\t\tid = member[0]\n\t\t\tkey = member[1].strip()\n\t\t\tlogger.info(len(key))\n\t\t\tlogger.info(len(rfid))\n\t\t\tif rfid == key:\n\t\t\t\tlogger.info(\"id:%s has successfully authenticated\" % id)\n\t\t\t\ttext.close()\n\t\t\t\treturn True\n\tlogger.info(\"rfid did not authenticate\")\n\treturn False;\n\t\n# Open the door\ndef open_door():\n\tlogger.info(\"door is open\")\n\tGPIO.output(solenoid, True)\n\ttime.sleep(speed)\n\tGPIO.output(solenoid, False)\n\tlogger.info(\"door is closed\")\n\t\n# Take the incoming message and do stuff\ndef handle_message(incoming_message):\n\tlogger.info(\"******** Start Message ********\") # Start logging block\n\tlogger.info(\"Received a new message: %s\" % incoming_message) # log incoming message\n\ttry:\n\t\trfid_message = extract_message(incoming_message) # Get the rfid message, log/break if message format is bad\n\t\tif query_acl(rfid_message): # check access list for the rfid tag\n\t\t\tlogger.info(\"Opening door\")\n\t\t\topen_door() # Open the door\n\texcept:\n\t\tlogger.exception(\"Exception as follows\")\n\t\traise\n\tfinally:\n\t\tlogger.info(\"********* End Message *********\")\n\t\tlogger.info(\"\")\n\n\n\n# Setup GPIO (for later use)\nimport RPi.GPIO as GPIO\nimport time\nGPIO.setmode(GPIO.BOARD)\nsolenoid = 12\nGPIO.setup(solenoid, GPIO.OUT)\nspeed = 10 # this is 10 seconds\n# Setup logger\nimport logging\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n# create a file handler\nhandler = logging.FileHandler('reader.log')\nhandler.setLevel(logging.INFO)\n# create a logging format\nformatter = logging.Formatter('%(asctime)s|%(levelname)s|%(message)s')\nhandler.setFormatter(formatter)\n# add the handlers to the logger\nlogger.addHandler(handler)\n\n# Setup Serial port\nimport serial\nport = serial.Serial(\"/dev/ttyAMA0\", baudrate=9600, timeout=3.0)\nwhile True:\n\ttry:\n\t\tincoming_message = port.read(14) # Get the incoming message\n\t\tif incoming_message != '':\n\t\t\thandle_message(incoming_message) # Parse the incoming message\t\t\t\n\texcept:\n\t\tlogger.info(\"Exception\")\nlogger.info(\"Cleaning up pin resources...\")\nGPIO.cleanup()\nlogger.info(\"Exiting\")\n","sub_path":"reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":4135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"210455187","text":"# 複数の1次元配列を表示する3次元リアルタイムグラフ\n# Library \nimport numpy as np # プロットするデータ配列を作成するため\nimport matplotlib.pyplot as plt # グラフ表示のため\nfrom mpl_toolkits.mplot3d import Axes3D # 3Dグラフ作成のため\nimport pandas as pd\n\n# params\nframe = 15 # プロットするフレーム数\nsleepTime = 0.5 # 1フレーム表示する時間[s]\ndataLength = 60 # 1次元配列データの長さ\ndataAmount = 3 # 1度にプロットする1次元配列データの個数\nzMax = 1 # z軸最大値\nzMin = 0 # z軸最小値\nxlabel = \"x axis\"\nylabel = \"y axis\"\nzlabel = \"z axis\"\ncolorsets = 'skyblue'\nxfigSize = 14 # グラフを表示するウインドウのx方向の大きさ\nyfigSize = 10 # グラフを表示するウインドウのy方向の大きさ\nAlpha = 1.0 # プロットした線の透明度\n\n# making stylish graph\nif colorsets == 'skyblue':\n color1 = '#FFFFFF' # background\n color2 = '#C7D7FF' # background2\n color3 = '#5BB1E3' # accent color red: DE5E34 blue: 5BB1E3\n color4 = '#4C4C4C' # axis\n\nplt.rcParams.update({\n 'figure.figsize': [xfigSize, yfigSize],\n # 'axes.grid': False,\n 'axes3d.grid': True,\n 'grid.alpha': 0.2,\n 'grid.linestyle': '-',\n 'axes.grid.which': 'major',\n 'axes.grid.axis': 'y',\n 'grid.linewidth': 0.1,\n 'font.size': 10,\n 'grid.color': color4,\n 'xtick.color': color4, # x軸の色\n 'ytick.color': color4, # y軸の色\n 'figure.facecolor': color1, # 枠の外の背景色\n 'figure.edgecolor': color1,\n 'axes.edgecolor': color1, # 枠色\n 'axes.facecolor': 'none', # 背景色 noneにするとfigure.facecolorと同じ色になった\n 'axes.labelcolor': color4, # 軸ラベル色\n 'figure.dpi': 75.0,\n 'figure.frameon': False,\n})\n\n# making 3d figure object\nfig = plt.figure() # figureオブジェクトを作る\nax = Axes3D(fig)\n\nax.w_xaxis.set_pane_color((0., 0., 0., 0.)) # 3dグラフの背景を透明にする 最初の一回だけでOK\nax.w_yaxis.set_pane_color((0., 0., 0., 0.)) # 3dグラフの背景を透明にする\nax.w_zaxis.set_pane_color((0., 0., 0., 0.)) # 3dグラフの背景を透明にする\n\ncsv_input = pd.read_csv(\"1b.csv\")\ndatas = csv_input.values\n\n# print(datas[0,1])\n# print(datas[0])\n\nfor i in range(frame):\n # getting data\n data = datas[i]\n x = np.arange(0, dataLength, 1) # 0 ~ 10 の1次元配列\n y = np.arange(0, dataAmount, 1) # 0 ~ 10 の1次元配列\n gx, gy = np.meshgrid(x, y) # grid\n z = np.random.rand(y.shape[0], x.shape[0]) # 0 ~ 10 の1次元配列\n\n # data shape checking\n print('x.shape', x.shape)\n print('y.shape', y.shape)\n print('gx.shape', gx.shape)\n print('gy.shape', gy.shape)\n print('z.shape', z.shape)\n print('x.type', type(x))\n print('y.type', type(y))\n print('z.type', type(z), '\\n')\n # print(z)\n # print(type(z))\n\n # plot setting\n # ax.set_zlim(zMin, zMax) # z軸固定\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n ax.set_zlabel(zlabel)\n\n # plotting\n # ax.plot(x, y, z) # 直線プロット\n ax.plot_wireframe(gx, gy, z, rstride=1, cstride=0, color=color3, alpha=Alpha)\n plt.draw()\n plt.pause(sleepTime)\n plt.cla()\n\nprint(datas)\nprint(datas.shape)\nprint(datas[0])\nprint(type(datas))\n\n\n\n","sub_path":"datasOf2019/analysis_practice.py","file_name":"analysis_practice.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"13146395","text":"import zipfile, os # zipfileとosモジュールのインポート\n\ndef save_zip(folder):\n '''\n 指定されたフォルダーをZIPファイルにバックアップする関数\n folder : バックアップするフォルダーのパス\n '''\n # folderをルートディレクトリからの絶対パスにする\n folder = os.path.abspath(folder) \n\n # ZIPファイル末尾に付ける連番\n number = 1 # 初期値は1\n\n # ①バックアップ用のZIPファイル名を作成する部分\n # ZIPファイル名を作成して、既存のバックアップ用ZIPファイル名を出力\n while True:\n # 「ベースパス_連番.zip」の形式でZIPファイル名を作る\n zip_filename = os.path.basename(folder) + '_' + str(number) + '.zip'\n # 作成したZIPファイル名を出力\n print(\"zip = \" + zip_filename)\n # 作成した名前と同じZIPファイルが存在しなければwhileブロックを抜ける\n if not os.path.exists(zip_filename):\n break\n\t\t# ファイルが存在していれば連番を1つ増やして次のループへ進む\n number = number + 1\n\n # ②ZIPファイルを作成する部分\n # ZIPファイルの作成を通知\n print('Creating %s...' % (zip_filename))\n # ファイル名を指定してZIPファイルを書き換えモードで開く\n backup_zip = zipfile.ZipFile(zip_filename, 'w')\n\n # フォルダのツリーを巡回してファイルを圧縮する\n for foldername, subfolders, filenames in os.walk(folder):\n # 追加するファイル名を出力\n print('ZIPファイルに{}を追加します...'.format(foldername))\n # 現在のフォルダーをZIPファイルに追加する\n backup_zip.write(foldername)\n # 現在のフォルダーのファイル名のリストをループ処理\n for filename in filenames:\n\t # folderのベースパスに_を連結\n new_base = os.path.basename(folder) + '_'\n\t # ベースパス_で始まり、.zipで終わるファイル、\n\t # 既存のバックアップ用ZIPファイルはスキップする\n if filename.startswith(new_base) and filename.endswith('.zip'):\n continue # 次のforループに戻る\n # バックアップ用ZIPファイル以外は新規に作成したZIPファイルに追加する\n backup_zip.write(os.path.join(foldername, filename))\n\t# ZIPファイルをクローズ\n backup_zip.close()\n print('バックアップ完了')\n\n# プログラムの実行ブロック\nif __name__ == '__main__':\n # バックアップするフォルダーのパスを指定\n backup_folder = input('Backupするフォルダーのパスを入力してください >')\n # ZIPファイルへのバックアップ開始\n save_zip(backup_folder)\n","sub_path":"chap04/sec02/saveToZip.py","file_name":"saveToZip.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"400117845","text":"import xml.etree.cElementTree as ET\nimport mysql.connector\n\n# establish connection to database\ncnx = mysql.connector.connect(user='master', password='master', host='localhost', database='master')\ncursor = cnx.cursor()\n\n# read xes\ntree = ET.ElementTree(file='C:/Users/Christian/Google Drive/Uni/Master/5 Wintersemester 17-18/Masterarbeit/Test Data/ETM_Configuration1.xes')\nroot = tree.getroot()\n\nlog = dict()\n\n# Events in dictionary speichern\nfor traces in root:\n if traces.tag == '{http://www.xes-standard.org/}trace':\n for events in traces:\n if events.get('key') == 'concept:name':\n\n caseID = events.get('value')\n if events.tag == '{http://www.xes-standard.org/}event':\n for entry in events:\n if entry.get('key') == 'time:timestamp':\n timestamp = entry.get('value')\n if entry.get('key') == 'concept:name':\n eventName = entry.get('value')\n if entry.get('key') == 'lifecycle:transition':\n transition = entry.get('value')\n if caseID not in log:\n log[caseID] = []\n case = (timestamp, eventName, transition)\n log[caseID].append(case)\n\n# Ausgabe aller Events sortiert\n# for caseID in sorted(log.keys()):\n# for (timestamp, eventName, transition) in log[caseID]:\n# print(caseID, timestamp, eventName, transition)\n\n# Speichere mögliche Eventnamen in Liste\neventNames = ['A+complete', 'B+complete', 'C+complete', 'D+complete', 'E+complete', 'F+complete', 'G+complete']\n\n# for traces in root:\n# if traces.get('key') == 'meta_concept:named_events_total':\n# for events in traces:\n# eventNames.append(events.get('key'))\n# print(eventNames)\n\n# Anzahl verschiedene Folgeevents\nsequence = []\ni = 0\nj = 0\nsuccessors_dict = {}\nsuccessor = []\ncounter = 0\nrestart = True\nfor traces in root:\n if traces.get('key') == 'meta_general:classifiers':\n for keys in traces:\n if keys.get('key') == 'MXML Legacy Classifier':\n while restart:\n restart = False\n for elements in keys:\n if elements.get('key') == 'meta_general:different_traces':\n counter = 0\n for entries in elements:\n sequence = entries.get('key')\n seqsplit = sequence.split(';')\n print(seqsplit)\n\n # successor.append('A+complete')\n # for events in seqsplit:\n # if events == 'A+complete':\n # try:\n # if seqsplit[j+1] not in successor:\n # successor.append(seqsplit[j+1])\n # j += 1\n # except:\n # pass\n try:\n if eventNames[i] not in successor:\n successor.append(eventNames[i])\n if seqsplit[i+1] not in successor:\n successor.append(seqsplit[i+1])\n counter += 1\n except:\n pass\n query = (\"INSERT INTO successor (event, followingEvents) VALUES ('A+complete', '{0}')\".format(counter))\n cursor.execute(query)\n cnx.commit()\n successor = []\n sequence = \"\"\n seqsplit = []\n i += 1\n if i == 6:\n restart = False\n break\n if i < 6:\n restart = True\n break\n\n\n\nprint(successor)","sub_path":"Successor2.py","file_name":"Successor2.py","file_ext":"py","file_size_in_byte":4252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"351909501","text":"# coding=utf-8\nimport pymysql\n\n\nclass DataSource(object):\n def __init__(self):\n # 打开数据库连接\n self.db = pymysql.connect(host=\"localhost\", user=\"root\",\n password=\"123456\", db=\"spider_man\", port=3306, charset='utf8')\n\n def add(self, list):\n # 使用cursor()方法获取操作游标\n cur = self.db.cursor()\n\n sql_insert = \"insert into ershoufang_lianjian ( title, region_id, house_info, flood,position_info,follow_info,tag,total_price, unit_price, detail_url,create_time) values\"\n\n str_temp = \"\"\n for info in list:\n str_temp = \"('\" + info.get(\"title\") + \"','\" + str(info.get(\"region_id\")) + \"','\" + info.get(\n \"house_info\") + \"','\" \\\n + info.get(\"flood\") + \"','\" \\\n + info.get(\"position_info\") + \"','\" + info.get(\"follow_info\") + \"','\" + info.get(\"tag\") + \"','\" \\\n + str(info.get(\"total_price\")) + \"','\" + str(info.get(\"unit_price\")) + \"','\" + info.get(\n \"detail_url\") \\\n + \"', now()),\"\n sql_insert += str_temp\n try:\n cur.execute(sql_insert.rstrip(\",\"))\n # 提交\n self.db.commit()\n print(\"添加成功\")\n except Exception as e:\n # 错误回滚\n print(e)\n self.db.rollback()\n self.db.close()\n\n def closeCon(self):\n self.db.close()\n print(\"关闭资源\")\n","sub_path":".gitignore/mysql_datasource.py","file_name":"mysql_datasource.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"350680640","text":"__author__ = \"ResearchInMotion\"\n\nimport findspark\nfindspark.init()\nfrom pyspark import SparkConf\nfrom pyspark import SparkContext\n\nsparkconf = SparkConf().setAppName(\"WordCount\").setMaster(\"local[*]\")\nsparkcont = SparkContext(conf=sparkconf)\nsparkcont.setLogLevel(\"ERROR\")\n\ndef columns(lines):\n field = lines.split(\",\")\n country = field[3]\n name = field[2]\n return name,country\n\ndata = sparkcont.textFile(\"/Users/sahilnagpal/PycharmProjects/Python/Pyspark/InputData/airports.text\")\nnotInAmerica = data.map(columns).filter(lambda country : country != \"\\\"United States\\\"\").take(200)\n\n\nfor name , country in notInAmerica:\n print(\"{} , {} \".format(name , country))","sub_path":"Pyspark/PairRDD/airportsNotinAmerica.py","file_name":"airportsNotinAmerica.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"576917921","text":"import unittest\n\n# my class imports\n\nfrom quants.quantifiers import *\n\nquantifiers = [No(), The(), Both(), Few(), Some(), AFew(), Many(), Most(), All(), Not(Most()), N(3), ExactlyN(5),\n Between(5, 150), Between(2, 50), Between(8, 40), Between(12, 35), FirstN(3), ExactlyFirstN(5)]\n\ntest_case_parameters = ([1000, 200, 150, 100], [0, 100, 300, 0], [500, 400, 500, 200])\n\n\nclass TestQuantifiers(unittest.TestCase):\n def test_short_display(self):\n for quantifier in quantifiers:\n symbol_counts = defaultdict(int, zip(*np.unique(quantifier.generate_scene(), return_counts=True)))\n symbol_counts = {symbols[symbol]: symbol_counts[symbol] for symbol in range(len(symbols))}\n print(quantifier.name(), symbol_counts)\n\n def test_generation(self):\n \"\"\" generate quantifiers (this internally checks that the generated scenes are quantifier True) \"\"\"\n # do this for various scene length limits and overall scene length\n for scene_num, min_len, max_len in zip(*test_case_parameters):\n for quantifier in quantifiers:\n quantifier.generate_scenes(scene_num, min_len, max_len)\n\n def test_entailment(self):\n \"\"\" test all quantifier generated scenes are True for quantifiers that their generating quantifiers entail \"\"\"\n # No(), The(), Both(), Some(), AFew(), Few(), Many(), Most(), All()\n\n # do this for various scene length limits\n for scene_num, min_len, max_len in zip(*test_case_parameters):\n # All quantifiers q entail not Not(q)\n print(\"Running entailment tests for scene_num={scene_num} min_len={min_len} max_len={max_len}...\"\n .format(scene_num=scene_num, min_len=min_len, max_len=max_len))\n # The entails Some\n assert(all([Some().quantify(scene) and not Not(The()).quantify(scene)\n for scene in The().generate_scenes(scene_num, min_len, max_len)]))\n # Both entails AFew and Some\n assert(all([AFew().quantify(scene) and Some().quantify(scene) and not Not(Both()).quantify(scene)\n for scene in Both().generate_scenes(scene_num, min_len, max_len)]))\n # AFew entails Some\n assert(all([Some().quantify(scene) and not Not(AFew()).quantify(scene)\n for scene in AFew().generate_scenes(scene_num, min_len, max_len)]))\n # Few entails some\n assert(all([Some().quantify(scene) and not Not(Few()).quantify(scene)\n for scene in Few().generate_scenes(scene_num, min_len, max_len)]))\n # Most entails some\n assert(all([Some().quantify(scene) and not Not(Most()).quantify(scene)\n for scene in Most().generate_scenes(scene_num, min_len, max_len)]))\n # Many entails Most\n assert(all([Most().quantify(scene) and not Not(Many()).quantify(scene)\n for scene in Many().generate_scenes(scene_num, min_len, max_len)]))\n # All entails Most and Some\n assert(all([Most().quantify(scene) and Some().quantify(scene) and not Not(All()).quantify(scene)\n for scene in All().generate_scenes(scene_num, min_len, max_len)]))\n # Even entails not Odd\n assert(all([not Odd().quantify(scene) and not Not(Even()).quantify(scene)\n for scene in Even().generate_scenes(scene_num, min_len, max_len)]))\n # Odd entails not Even\n assert(all([not Even().quantify(scene) and not Not(Odd()).quantify(scene)\n for scene in Odd().generate_scenes(scene_num, min_len, max_len)]))\n # FirstN entails N\n for n in [3, 5, 7]:\n assert(all([N(n).quantify(scene)\n for scene in FirstN(n).generate_scenes(scene_num, min_len, max_len)]))\n # ExactylFirstN entails ExactlyN\n for n in [3, 5, 7]:\n assert(all([N(n).quantify(scene)\n for scene in ExactlyFirstN(n).generate_scenes(scene_num, min_len, max_len)]))\n # test Or and And conjunctions using Between (Between(n1,n2) entails (n1 and not n2)==(not(n2 or not n1)))\n for n1, n2 in zip([3, 5, 7], [7, 9, 20]):\n assert(all([And([N(n1), Not(N(n2 + 1))]).quantify(scene)\n and\n Not(Or([(N(n2 + 1)), Not(N(n1))])).quantify(scene)\n for scene in Between(n1, n2).generate_scenes(scene_num, min_len, max_len)]))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_quantifiers.py","file_name":"test_quantifiers.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"473473432","text":"from __future__ import division, print_function, unicode_literals\n\nimport os\n\nimport pytest\nfrom mock import DEFAULT, patch\nfrom pytest import raises\n\nfrom readthedocs.config import (\n BuildConfig, ConfigError, ConfigOptionNotSupportedError, InvalidConfig,\n ProjectConfig, load)\nfrom readthedocs.config.config import (\n CONFIG_NOT_SUPPORTED, NAME_INVALID, NAME_REQUIRED, PYTHON_INVALID,\n TYPE_REQUIRED)\nfrom readthedocs.config.validation import (\n INVALID_BOOL, INVALID_CHOICE, INVALID_LIST, INVALID_PATH, INVALID_STRING)\n\nfrom .utils import apply_fs\n\nenv_config = {\n 'output_base': '/tmp'\n}\n\n\nminimal_config = {\n 'name': 'docs',\n 'type': 'sphinx',\n}\n\n\nconfig_with_explicit_empty_list = {\n 'readthedocs.yml': '''\nname: docs\ntype: sphinx\nformats: []\n'''\n}\n\n\nminimal_config_dir = {\n 'readthedocs.yml': '''\\\nname: docs\ntype: sphinx\n'''\n}\n\n\nmultiple_config_dir = {\n 'readthedocs.yml': '''\nname: first\ntype: sphinx\n---\nname: second\ntype: sphinx\n ''',\n 'nested': minimal_config_dir,\n}\n\n\ndef get_build_config(config, env_config=None, source_file='readthedocs.yml',\n source_position=0):\n return BuildConfig(\n env_config or {},\n config,\n source_file=source_file,\n source_position=source_position)\n\n\ndef get_env_config(extra=None):\n \"\"\"Get the minimal env_config for the configuration object.\"\"\"\n defaults = {\n 'output_base': '',\n 'name': 'name',\n 'type': 'sphinx',\n }\n if extra is None:\n extra = {}\n defaults.update(extra)\n return defaults\n\n\ndef test_load_no_config_file(tmpdir):\n base = str(tmpdir)\n with raises(ConfigError):\n load(base, env_config)\n\n\ndef test_load_empty_config_file(tmpdir):\n apply_fs(tmpdir, {\n 'readthedocs.yml': ''\n })\n base = str(tmpdir)\n with raises(ConfigError):\n load(base, env_config)\n\n\ndef test_minimal_config(tmpdir):\n apply_fs(tmpdir, minimal_config_dir)\n base = str(tmpdir)\n config = load(base, env_config)\n assert isinstance(config, ProjectConfig)\n assert len(config) == 1\n build = config[0]\n assert isinstance(build, BuildConfig)\n\n\ndef test_build_config_has_source_file(tmpdir):\n base = str(apply_fs(tmpdir, minimal_config_dir))\n build = load(base, env_config)[0]\n assert build.source_file == os.path.join(base, 'readthedocs.yml')\n assert build.source_position == 0\n\n\ndef test_build_config_has_source_position(tmpdir):\n base = str(apply_fs(tmpdir, multiple_config_dir))\n builds = load(base, env_config)\n assert len(builds) == 2\n first, second = filter(\n lambda b: not b.source_file.endswith('nested/readthedocs.yml'),\n builds)\n assert first.source_position == 0\n assert second.source_position == 1\n\n\ndef test_build_config_has_list_with_single_empty_value(tmpdir):\n base = str(apply_fs(tmpdir, config_with_explicit_empty_list))\n build = load(base, env_config)[0]\n assert isinstance(build, BuildConfig)\n assert build.formats == []\n\n\ndef test_config_requires_name():\n build = BuildConfig(\n {'output_base': ''}, {},\n source_file='readthedocs.yml',\n source_position=0\n )\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'name'\n assert excinfo.value.code == NAME_REQUIRED\n\n\ndef test_build_requires_valid_name():\n build = BuildConfig(\n {'output_base': ''},\n {'name': 'with/slashes'},\n source_file='readthedocs.yml',\n source_position=0\n )\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'name'\n assert excinfo.value.code == NAME_INVALID\n\n\ndef test_config_requires_type():\n build = BuildConfig(\n {'output_base': ''}, {'name': 'docs'},\n source_file='readthedocs.yml',\n source_position=0\n )\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'type'\n assert excinfo.value.code == TYPE_REQUIRED\n\n\ndef test_build_requires_valid_type():\n build = BuildConfig(\n {'output_base': ''},\n {'name': 'docs', 'type': 'unknown'},\n source_file='readthedocs.yml',\n source_position=0\n )\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'type'\n assert excinfo.value.code == INVALID_CHOICE\n\n\ndef test_version():\n build = get_build_config({}, get_env_config())\n assert build.version == '1'\n\n\ndef test_empty_python_section_is_valid():\n build = get_build_config({'python': {}}, get_env_config())\n build.validate()\n assert build.python\n\n\ndef test_python_section_must_be_dict():\n build = get_build_config({'python': 123}, get_env_config())\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'python'\n assert excinfo.value.code == PYTHON_INVALID\n\n\ndef test_use_system_site_packages_defaults_to_false():\n build = get_build_config({'python': {}}, get_env_config())\n build.validate()\n # Default is False.\n assert not build.use_system_site_packages\n\n\n@pytest.mark.parametrize('value', [True, False])\ndef test_use_system_site_packages_repects_default_value(value):\n defaults = {\n 'use_system_packages': value,\n }\n build = get_build_config({}, get_env_config({'defaults': defaults}))\n build.validate()\n assert build.use_system_site_packages is value\n\n\ndef test_python_pip_install_default():\n build = get_build_config({'python': {}}, get_env_config())\n build.validate()\n # Default is False.\n assert build.pip_install is False\n\n\ndef describe_validate_python_extra_requirements():\n\n def it_defaults_to_list():\n build = get_build_config({'python': {}}, get_env_config())\n build.validate()\n # Default is an empty list.\n assert build.extra_requirements == []\n\n def it_validates_is_a_list():\n build = get_build_config(\n {'python': {'extra_requirements': 'invalid'}},\n get_env_config()\n )\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'python.extra_requirements'\n assert excinfo.value.code == PYTHON_INVALID\n\n @patch('readthedocs.config.config.validate_string')\n def it_uses_validate_string(validate_string):\n validate_string.return_value = True\n build = get_build_config(\n {'python': {'extra_requirements': ['tests']}},\n get_env_config()\n )\n build.validate()\n validate_string.assert_any_call('tests')\n\n\ndef describe_validate_use_system_site_packages():\n def it_defaults_to_false():\n build = get_build_config({'python': {}}, get_env_config())\n build.validate()\n assert build.use_system_site_packages is False\n\n def it_validates_value():\n build = get_build_config(\n {'python': {'use_system_site_packages': 'invalid'}},\n get_env_config()\n )\n with raises(InvalidConfig) as excinfo:\n build.validate()\n excinfo.value.key = 'python.use_system_site_packages'\n excinfo.value.code = INVALID_BOOL\n\n @patch('readthedocs.config.config.validate_bool')\n def it_uses_validate_bool(validate_bool):\n validate_bool.return_value = True\n build = get_build_config(\n {'python': {'use_system_site_packages': 'to-validate'}},\n get_env_config()\n )\n build.validate()\n validate_bool.assert_any_call('to-validate')\n\n\ndef describe_validate_setup_py_install():\n\n def it_defaults_to_false():\n build = get_build_config({'python': {}}, get_env_config())\n build.validate()\n assert build.python['setup_py_install'] is False\n\n def it_validates_value():\n build = get_build_config(\n {'python': {'setup_py_install': 'this-is-string'}},\n get_env_config()\n )\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'python.setup_py_install'\n assert excinfo.value.code == INVALID_BOOL\n\n @patch('readthedocs.config.config.validate_bool')\n def it_uses_validate_bool(validate_bool):\n validate_bool.return_value = True\n build = get_build_config(\n {'python': {'setup_py_install': 'to-validate'}},\n get_env_config()\n )\n build.validate()\n validate_bool.assert_any_call('to-validate')\n\n\ndef describe_validate_python_version():\n\n def it_defaults_to_a_valid_version():\n build = get_build_config({'python': {}}, get_env_config())\n build.validate()\n assert build.python_version == 2\n assert build.python_interpreter == 'python2.7'\n assert build.python_full_version == 2.7\n\n def it_supports_other_versions():\n build = get_build_config(\n {'python': {'version': 3.5}},\n get_env_config()\n )\n build.validate()\n assert build.python_version == 3.5\n assert build.python_interpreter == 'python3.5'\n assert build.python_full_version == 3.5\n\n def it_validates_versions_out_of_range():\n build = get_build_config(\n {'python': {'version': 1.0}},\n get_env_config()\n )\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'python.version'\n assert excinfo.value.code == INVALID_CHOICE\n\n def it_validates_wrong_type():\n build = get_build_config(\n {'python': {'version': 'this-is-string'}},\n get_env_config()\n )\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'python.version'\n assert excinfo.value.code == INVALID_CHOICE\n\n def it_validates_wrong_type_right_value():\n build = get_build_config(\n {'python': {'version': '3.5'}},\n get_env_config()\n )\n build.validate()\n assert build.python_version == 3.5\n assert build.python_interpreter == 'python3.5'\n assert build.python_full_version == 3.5\n\n build = get_build_config(\n {'python': {'version': '3'}},\n get_env_config()\n )\n build.validate()\n assert build.python_version == 3\n assert build.python_interpreter == 'python3.5'\n assert build.python_full_version == 3.5\n\n def it_validates_env_supported_versions():\n build = get_build_config(\n {'python': {'version': 3.6}},\n env_config=get_env_config(\n {\n 'python': {'supported_versions': [3.5]},\n 'build': {'image': 'custom'},\n }\n )\n )\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'python.version'\n assert excinfo.value.code == INVALID_CHOICE\n\n build = get_build_config(\n {'python': {'version': 3.6}},\n env_config=get_env_config(\n {\n 'python': {'supported_versions': [3.5, 3.6]},\n 'build': {'image': 'custom'},\n }\n )\n )\n build.validate()\n assert build.python_version == 3.6\n assert build.python_interpreter == 'python3.6'\n assert build.python_full_version == 3.6\n\n @pytest.mark.parametrize('value', [2, 3])\n def it_respects_default_value(value):\n defaults = {\n 'python_version': value\n }\n build = get_build_config(\n {},\n get_env_config({'defaults': defaults})\n )\n build.validate()\n assert build.python_version == value\n\n\ndef describe_validate_formats():\n\n def it_defaults_to_empty():\n build = get_build_config({}, get_env_config())\n build.validate()\n assert build.formats == []\n\n def it_gets_set_correctly():\n build = get_build_config({'formats': ['pdf']}, get_env_config())\n build.validate()\n assert build.formats == ['pdf']\n\n def formats_can_be_null():\n build = get_build_config({'formats': None}, get_env_config())\n build.validate()\n assert build.formats == []\n\n def formats_with_previous_none():\n build = get_build_config({'formats': ['none']}, get_env_config())\n build.validate()\n assert build.formats == []\n\n def formats_can_be_empty():\n build = get_build_config({'formats': []}, get_env_config())\n build.validate()\n assert build.formats == []\n\n def all_valid_formats():\n build = get_build_config(\n {'formats': ['pdf', 'htmlzip', 'epub']},\n get_env_config()\n )\n build.validate()\n assert build.formats == ['pdf', 'htmlzip', 'epub']\n\n def cant_have_none_as_format():\n build = get_build_config(\n {'formats': ['htmlzip', None]},\n get_env_config()\n )\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'format'\n assert excinfo.value.code == INVALID_CHOICE\n\n def formats_have_only_allowed_values():\n build = get_build_config(\n {'formats': ['htmlzip', 'csv']},\n get_env_config()\n )\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'format'\n assert excinfo.value.code == INVALID_CHOICE\n\n def only_list_type():\n build = get_build_config({'formats': 'no-list'}, get_env_config())\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'format'\n assert excinfo.value.code == INVALID_LIST\n\n\ndef describe_validate_setup_py_path():\n\n def it_defaults_to_source_file_directory(tmpdir):\n apply_fs(\n tmpdir,\n {\n 'subdir': {\n 'readthedocs.yml': '',\n 'setup.py': '',\n },\n }\n )\n with tmpdir.as_cwd():\n source_file = tmpdir.join('subdir', 'readthedocs.yml')\n setup_py = tmpdir.join('subdir', 'setup.py')\n build = get_build_config(\n {},\n env_config=get_env_config(),\n source_file=str(source_file))\n build.validate()\n assert build.python['setup_py_path'] == str(setup_py)\n\n def it_validates_value(tmpdir):\n with tmpdir.as_cwd():\n build = get_build_config({'python': {'setup_py_path': 'this-is-string'}})\n with raises(InvalidConfig) as excinfo:\n build.validate_python()\n assert excinfo.value.key == 'python.setup_py_path'\n assert excinfo.value.code == INVALID_PATH\n\n def it_uses_validate_file(tmpdir):\n path = tmpdir.join('setup.py')\n path.write('content')\n path = str(path)\n patcher = patch('readthedocs.config.config.validate_file')\n with patcher as validate_file:\n validate_file.return_value = path\n build = get_build_config(\n {'python': {'setup_py_path': 'setup.py'}})\n build.validate_python()\n args, kwargs = validate_file.call_args\n assert args[0] == 'setup.py'\n\n\ndef test_valid_build_config():\n build = BuildConfig(env_config,\n minimal_config,\n source_file='readthedocs.yml',\n source_position=0)\n build.validate()\n assert build.name == 'docs'\n assert build.type == 'sphinx'\n assert build.base\n assert build.python\n assert 'setup_py_install' in build.python\n assert 'use_system_site_packages' in build.python\n assert build.output_base\n\n\ndef describe_validate_base():\n\n def it_validates_to_abspath(tmpdir):\n apply_fs(tmpdir, {'configs': minimal_config, 'docs': {}})\n with tmpdir.as_cwd():\n source_file = str(tmpdir.join('configs', 'readthedocs.yml'))\n build = BuildConfig(\n get_env_config(),\n {'base': '../docs'},\n source_file=source_file,\n source_position=0)\n build.validate()\n assert build.base == str(tmpdir.join('docs'))\n\n @patch('readthedocs.config.config.validate_directory')\n def it_uses_validate_directory(validate_directory):\n validate_directory.return_value = 'path'\n build = get_build_config({'base': '../my-path'}, get_env_config())\n build.validate()\n # Test for first argument to validate_directory\n args, kwargs = validate_directory.call_args\n assert args[0] == '../my-path'\n\n def it_fails_if_base_is_not_a_string(tmpdir):\n apply_fs(tmpdir, minimal_config)\n with tmpdir.as_cwd():\n build = BuildConfig(\n get_env_config(),\n {'base': 1},\n source_file=str(tmpdir.join('readthedocs.yml')),\n source_position=0)\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'base'\n assert excinfo.value.code == INVALID_STRING\n\n def it_fails_if_base_does_not_exist(tmpdir):\n apply_fs(tmpdir, minimal_config)\n build = BuildConfig(\n get_env_config(),\n {'base': 'docs'},\n source_file=str(tmpdir.join('readthedocs.yml')),\n source_position=0)\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'base'\n assert excinfo.value.code == INVALID_PATH\n\n\ndef describe_validate_build():\n\n def it_fails_if_build_is_invalid_option(tmpdir):\n apply_fs(tmpdir, minimal_config)\n build = BuildConfig(\n get_env_config(),\n {'build': {'image': 3.0}},\n source_file=str(tmpdir.join('readthedocs.yml')),\n source_position=0)\n with raises(InvalidConfig) as excinfo:\n build.validate()\n assert excinfo.value.key == 'build'\n assert excinfo.value.code == INVALID_CHOICE\n\n def it_fails_on_python_validation(tmpdir):\n apply_fs(tmpdir, minimal_config)\n build = BuildConfig(\n {},\n {\n 'build': {'image': 1.0},\n 'python': {'version': '3.3'},\n },\n source_file=str(tmpdir.join('readthedocs.yml')),\n source_position=0)\n build.validate_build()\n with raises(InvalidConfig) as excinfo:\n build.validate_python()\n assert excinfo.value.key == 'python.version'\n assert excinfo.value.code == INVALID_CHOICE\n\n def it_works_on_python_validation(tmpdir):\n apply_fs(tmpdir, minimal_config)\n build = BuildConfig(\n {},\n {\n 'build': {'image': 'latest'},\n 'python': {'version': '3.3'},\n },\n source_file=str(tmpdir.join('readthedocs.yml')),\n source_position=0)\n build.validate_build()\n build.validate_python()\n\n def it_works(tmpdir):\n apply_fs(tmpdir, minimal_config)\n build = BuildConfig(\n get_env_config(),\n {'build': {'image': 'latest'}},\n source_file=str(tmpdir.join('readthedocs.yml')),\n source_position=0)\n build.validate()\n assert build.build_image == 'readthedocs/build:latest'\n\n def default(tmpdir):\n apply_fs(tmpdir, minimal_config)\n build = BuildConfig(\n get_env_config(),\n {},\n source_file=str(tmpdir.join('readthedocs.yml')),\n source_position=0)\n build.validate()\n assert build.build_image == 'readthedocs/build:2.0'\n\n @pytest.mark.parametrize(\n 'image', ['latest', 'readthedocs/build:3.0', 'rtd/build:latest'])\n def it_priorities_image_from_env_config(tmpdir, image):\n apply_fs(tmpdir, minimal_config)\n defaults = {\n 'build_image': image,\n }\n build = BuildConfig(\n get_env_config({'defaults': defaults}),\n {'build': {'image': 'latest'}},\n source_file=str(tmpdir.join('readthedocs.yml')),\n source_position=0\n )\n build.validate()\n assert build.build_image == image\n\n\ndef test_use_conda_default_false():\n build = get_build_config({}, get_env_config())\n build.validate()\n assert build.use_conda is False\n\n\ndef test_use_conda_respects_config():\n build = get_build_config(\n {'conda': {}},\n get_env_config()\n )\n build.validate()\n assert build.use_conda is True\n\n\ndef test_validates_conda_file(tmpdir):\n apply_fs(tmpdir, {'environment.yml': ''})\n build = get_build_config(\n {'conda': {'file': 'environment.yml'}},\n get_env_config(),\n source_file=str(tmpdir.join('readthedocs.yml'))\n )\n build.validate()\n assert build.use_conda is True\n assert build.conda_file == str(tmpdir.join('environment.yml'))\n\n\ndef test_requirements_file_empty():\n build = get_build_config({}, get_env_config())\n build.validate()\n assert build.requirements_file is None\n\n\ndef test_requirements_file_repects_default_value(tmpdir):\n apply_fs(tmpdir, {'myrequirements.txt': ''})\n defaults = {\n 'requirements_file': 'myrequirements.txt'\n }\n build = get_build_config(\n {},\n get_env_config({'defaults': defaults}),\n source_file=str(tmpdir.join('readthedocs.yml'))\n )\n build.validate()\n assert build.requirements_file == 'myrequirements.txt'\n\n\ndef test_requirements_file_respects_configuration(tmpdir):\n apply_fs(tmpdir, {'requirements.txt': ''})\n build = get_build_config(\n {'requirements_file': 'requirements.txt'},\n get_env_config(),\n source_file=str(tmpdir.join('readthedocs.yml'))\n )\n build.validate()\n assert build.requirements_file == 'requirements.txt'\n\n\n\ndef test_build_validate_calls_all_subvalidators(tmpdir):\n apply_fs(tmpdir, minimal_config)\n build = BuildConfig(\n {},\n {},\n source_file=str(tmpdir.join('readthedocs.yml')),\n source_position=0)\n with patch.multiple(BuildConfig,\n validate_base=DEFAULT,\n validate_name=DEFAULT,\n validate_type=DEFAULT,\n validate_python=DEFAULT,\n validate_output_base=DEFAULT):\n build.validate()\n BuildConfig.validate_base.assert_called_with()\n BuildConfig.validate_name.assert_called_with()\n BuildConfig.validate_type.assert_called_with()\n BuildConfig.validate_python.assert_called_with()\n BuildConfig.validate_output_base.assert_called_with()\n\n\ndef test_validate_project_config():\n with patch.object(BuildConfig, 'validate') as build_validate:\n project = ProjectConfig([\n BuildConfig(\n env_config,\n minimal_config,\n source_file='readthedocs.yml',\n source_position=0)\n ])\n project.validate()\n assert build_validate.call_count == 1\n\n\ndef test_load_calls_validate(tmpdir):\n apply_fs(tmpdir, minimal_config_dir)\n base = str(tmpdir)\n with patch.object(BuildConfig, 'validate') as build_validate:\n load(base, env_config)\n assert build_validate.call_count == 1\n\n\ndef test_raise_config_not_supported():\n build = get_build_config({}, get_env_config())\n build.validate()\n with raises(ConfigOptionNotSupportedError) as excinfo:\n build.redirects\n assert excinfo.value.configuration == 'redirects'\n assert excinfo.value.code == CONFIG_NOT_SUPPORTED\n","sub_path":"readthedocs/config/tests/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":23748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"466110833","text":"import sys, errno\nimport argparse\nimport json\nimport requests\n\n# Ensure empty strings can't be passed for required arguments\ndef non_empty_string(s):\n if not s:\n raise ValueError(\"Must not be empty string\")\n return s\n\n# Define arguments\nparser = argparse.ArgumentParser()\nparser.add_argument('--apiKey', required=True, type=non_empty_string)\nparser.add_argument('--version', required=True, type=non_empty_string)\nparser.add_argument('--authToken', required=True, type=non_empty_string)\nparser.add_argument('--ownerName')\nparser.add_argument('--emailAddress')\nparser.add_argument('--comment')\nparser.add_argument('--scmIdentifier')\nparser.add_argument('--scmType')\nparser.add_argument('--createdAt')\n\nparser.add_argument('--ghAction', action='store_true')\n\n# Parse arguments\nargs, extra = parser.parse_known_args()\n\n# Remove empty arguments\ndata = vars(args)\nfor key, value in list(data.items()):\n if value is None: del data[key]\n\n# Build URL, remove auth token from payload\nurl = \"https://app.raygun.com/deployments?authToken={}\".format(data[\"authToken\"])\ndel data[\"authToken\"]\n\n# Check if we should output in the Github Action format\nghAction = \"ghAction\" in data\nif ghAction:\n del data[\"ghAction\"]\n\n# Make request\nresponse = requests.post(url, json.dumps(data))\n\nif response.ok:\n result = json.loads(response.text)\n\n if ghAction:\n for output,value in result.items():\n print(\"::set-output name={}::{}\".format(output, value))\n else:\n print(result)\n sys.exit(0)\nelse:\n error = {}\n error[\"error\"] = response.reason\n print(error)\n sys.exit(errno.ECONNABORTED)\n","sub_path":"deployment.py","file_name":"deployment.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"654219849","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of REANA.\n# Copyright (C) 2021, 2022 CERN.\n#\n# REANA is free software; you can redistribute it and/or modify it\n# under the terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"REANA client parameters validation.\"\"\"\n\nimport sys\nfrom typing import Dict\n\nfrom reana_commons.validation.parameters import build_parameters_validator\nfrom reana_commons.errors import REANAValidationError\n\nfrom reana_client.printer import display_message\n\n\ndef validate_parameters(reana_yaml: Dict) -> None:\n \"\"\"Validate the presence of input parameters in workflow step commands and viceversa.\n\n :param reana_yaml: REANA YAML specification.\n \"\"\"\n\n validator = build_parameters_validator(reana_yaml)\n try:\n validator.validate_parameters()\n display_messages(validator)\n except REANAValidationError as e:\n display_messages(validator)\n display_message(\n str(e),\n msg_type=\"error\",\n indented=True,\n )\n sys.exit(1)\n\n\ndef display_messages(validator) -> None:\n \"\"\"Display messages in console.\"\"\"\n _display_reana_params_warnings(validator)\n _display_workflow_params_warnings(validator)\n _display_operations_warnings(validator)\n\n\ndef _display_reana_params_warnings(validator) -> None:\n \"\"\"Display REANA specification parameter validation warnings.\"\"\"\n _display_messages_type(\n info_msg=\"Verifying REANA specification parameters... \",\n success_msg=\"REANA specification parameters appear valid.\",\n messages=validator.reana_params_warnings,\n )\n\n\ndef _display_workflow_params_warnings(validator) -> None:\n \"\"\"Display REANA workflow parameter and command validation warnings.\"\"\"\n _display_messages_type(\n info_msg=\"Verifying workflow parameters and commands... \",\n success_msg=\"Workflow parameters and commands appear valid.\",\n messages=validator.workflow_params_warnings,\n )\n\n\ndef _display_operations_warnings(validator) -> None:\n \"\"\"Display dangerous workflow operation warnings.\"\"\"\n _display_messages_type(\n info_msg=\"Verifying dangerous workflow operations... \",\n success_msg=\"Workflow operations appear valid.\",\n messages=validator.operations_warnings,\n )\n\n\ndef _display_messages_type(info_msg, success_msg, messages) -> None:\n display_message(info_msg, msg_type=\"info\")\n for msg in messages:\n display_message(msg[\"message\"], msg_type=msg[\"type\"], indented=True)\n if not messages:\n display_message(success_msg, msg_type=\"success\", indented=True)\n","sub_path":"reana_client/validation/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"506148288","text":"\nimport gym\nimport os\nimport numpy as np\nfrom neat import nn, population, statistics, parallel\nimport pickle\n\n\n\ndef run(first_game,second_game):\n\n\n def simulate_species(net, env, episodes, steps, render):\n fitnesses = []\n \n for runs in range(episodes):\n\n inputs= my_env.reset()\n \n cum_reward = 0.0\n for j in range(steps):\n outputs = net.serial_activate(inputs)\n action = np.argmax(outputs)\n \n inputs, reward, done, _ = env.step(action)\n \n if render:\n env.render()\n if done:\n break\n cum_reward += reward\n\n fitnesses.append(cum_reward)\n\n fitness = (np.array(fitnesses).mean())\n print(\"Species fitness: %s\" % str(fitness))\n return fitness\n\n\n to_choose=(\"Please enter 1 if you want to test \",first_game,\" or 2 if you want to test \",second_game)\n\n choice=input(to_choose)\n\n if choice==1:\n\n my_env = gym.make(first_game)\n\n else:\n\n my_env = gym.make(second_game)\n\n file = open('winner.pkl', 'rb')\n winner=pickle.load(file)\n file.close()\n\n\n\n\n winner_net = nn.create_feed_forward_phenotype(winner)\n for i in range(100):\n simulate_species(winner_net,my_env, 1, 8000, True)\n\n\n\n train_network(my_env)\n","sub_path":"Code_FinalReport_Ekiz_Parolo_Bujari/two_games/run_winner.py","file_name":"run_winner.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"162084444","text":"import cv2 as cv\nimport numpy as np\nimport pytesseract\npath = r\"C:\\Users\\Matthew Prata\\source\\repos\\Python\\Reciept.jpeg\"\nimg = cv.imread(path)\ndef resize_image(img,scale=0.75):\n width = int (img.shape[1]*scale) \n height = int (img.shape[0]*scale)\n dimensions = (width,height)\n return cv.resize(img, dimensions, interpolation=cv.INTER_AREA)\npytesseract.pytesseract.tesseract_cmd = 'C:\\\\Program Files\\\\Tesseract-OCR\\\\tesseract.exe'\n\n### Detecting Characters with Boxes\ndef boximg(img):\n Wimg = img.shape[1]\n Height = img.shape[0]\n boxes = pytesseract.image_to_boxes(img)\n #print(boxes)\n for b in boxes.splitlines():\n b = b.split(' ')\n \n \n x,y,w,h = int(b[1]),int(b[2]),int(b[3]),int(b[4])\n if(int(ord(b[0])) < 58 and int(ord(b[0])) > 47):\n cv.rectangle(img,(x,Height-y),(w,Height-h),(0,0,255),1)\n \n return img\n\n\n###Inverts the Image\n\n\ndef invimg(img,avg_color):\n i,j=0,0\n width = img.shape[1]\n height = img.shape[0]\n\n for i in range(width):\n for j in range(height):\n color = img[j,i]\n \n if color[2] > avg_color[2]- 50: \n \n \n #if color[0] < 116 and color[1] < 90 and color[2] < 100:\n color = [255,255,255]\n \n else: \n color = [0,0,0]\n img[j,i] = color\n #img = abs(img-255)\n print(\"Returning the inverted image\")\n return img\n\ndef OrganizeInfo(info):\n info = info.upper()\n\n info = info.replace('\\n',\" \")\n WORDLIST = info.split(' ')\n val = ''\n \n try: \n while True:\n WORDLIST.remove(val)\n except ValueError:\n pass\n try: \n while True:\n WORDLIST.remove('E')\n except ValueError:\n pass\n try: \n while True:\n WORDLIST.remove('|')\n except ValueError:\n pass\n \n #print(WORDLIST)\n return WORDLIST\n#resizes the image\ndef PriceofItems(WORDLIST,NumItems, Total):\n \n i = j = 0\n Prices = []\n for i in range(len(WORDLIST)):\n string = WORDLIST[i]\n try:\n #if it is an integer \n \n if(float(WORDLIST[i]) or WORDLIST[i] == '0.00'):\n #Finding if the value has a decimal\n if(WORDLIST[i].find('.') != -1):\n item = float(WORDLIST[i])\n item = \"{:.2f}\".format(item)\n Prices.append(item)\n \n else:\n continue\n else:\n continue\n except ValueError:\n continue\n if str(Total) in Prices:\n Prices.remove(str(Total))\n Prices = Prices[:int(NumItems)+1]\n print(Prices)\n return Prices\ndef NameofItems(WORDLIST,Prices):\n ItemNames = []\n i = 0\n for i in range(len(Prices)):\n if(str(Prices[i]) in WORDLIST):\n index = WORDLIST.index(str(Prices[i]))\n ItemNames.append(WORDLIST[index-1])\n if(Prices[i] == 0.0):\n index = WORDLIST.index('0.00')\n ItemNames.append(WORDLIST[index-1])\n print('Items are:',ItemNames)\n return ItemNames\n \ndef Questionare(WORDLIST, Prices, NumofItems, ItemNames):\n NumofItems = int(NumofItems)\n Totals = {'Matt':[0], 'Sahil': [0],'Tim':[0],'Adrian':[0] } \n i = 0\n print(Totals)\n #Row 0 = Matt\n #Row 1 = Tim\n #Row 2 = Sahil\n #Row 3 = Adrian\n for i in range(NumofItems+1):\n print(f\"Who paid for {ItemNames[i]}: {Prices[i]}\")\n payment = input()\n payment = sorted(payment)\n if(len(payment)== 0):\n break\n owed = float(Prices[i])/len(payment)\n if('M' in payment or 'm' in payment):\n Totals['Matt'].append(owed)\n\n if('T' in payment or 't' in payment):\n Totals['Tim'].append(owed)\n if('S' in payment or 's' in payment):\n Totals['Sahil'].append(owed)\n if('A' in payment or 'a' in payment):\n Totals['Adrian'].append(owed)\n\n print(f\"Matt Owes: {sum(Totals['Matt']) }\")\n print(f\"Tim Owes: {sum(Totals['Tim']) }\")\n print(f\"Sahil Owes: {sum(Totals['Sahil']) }\")\n print(f\"Adrian Owes: {sum(Totals['Adrian'])}\")\n \n print(Totals)\n \n return Totals\n \ndef avg(img):\n average_color = np.average(img, axis = 0)\n average_color = np.average(average_color,axis = 0)\n print(average_color)\n return average_color\naverage_color = avg(img)\n\nprint(f\"IMG COLOR {img[50,50]}\")\nsmall_img = resize_image(img,.4)\nlarge_img = resize_image(img,1.6)\n\nimg = invimg(img,average_color)\nsmall_img = resize_image(img,.4)\n#changing color of image (type)\n#large_img = cv.cvtColor(large_img,cv.COLOR_BGR2GRAY)\n#small_img = cv.cvtColor(small_img,cv.COLOR_BGR2GRAY)\nsmall_img = cv.cvtColor(small_img,cv.COLOR_BGR2RGB)\nlarge_img = cv.cvtColor(large_img,cv.COLOR_BGR2RGB)\nimg = cv.cvtColor(img,cv.COLOR_BGR2RGB)\n\n\n\n\ninfo = pytesseract.image_to_string(img)\n\n#grabs information from image\nprint(info)\nWORDLIST = OrganizeInfo(info)\n#comment Here\n\nNumofItems = WORDLIST[WORDLIST.index('SOLD')+2]\nTotal = float(WORDLIST[WORDLIST.index('SUBTOTAL')+1]) + float(WORDLIST[WORDLIST.index('TAX')+1])\nprint(\"The Total of this trip was: \",Total)\nprint(\"Number of Items is:\", NumofItems)\nPrices = PriceofItems(WORDLIST,NumofItems,Total)\nItemNames = NameofItems(WORDLIST,Prices)\n\nTotals = Questionare(WORDLIST,Prices,NumofItems, ItemNames)\n#End Comment\n\n#drawing boxes\nimg = boximg(img)\nsmall_img = boximg(small_img)\n#small_img = boximg(small_img)\n\n#Finding Number of Items \n#TotalItems = FindTotal(img)\n#print(\"The total Number of Items is:\",TotalItems)\n\ncv.imshow('Reciept',img)\ncv.waitKey(0)\n","sub_path":"RecieptReader2.py","file_name":"RecieptReader2.py","file_ext":"py","file_size_in_byte":5657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"170106305","text":"import requests, os, json, sys\n\nBASE_URL = 'https://app.nanonets.com/api/v2/ImageCategorization/'\nAUTH_KEY = os.environ.get('NANONETS_API_KEY')\nurl = BASE_URL + \"Model/\"\n\ncategories = [\"OL风服装\",\"中性风服装\", \"可爱系服装\", \"嘻哈风服装\", \"学院风服装\", \"朋克风服装\", \"欧美风服装\", \"民族风服装\", \"洛丽塔风服装\", \"淑女系服装\", \"田园风服装\",\"百搭系服装\",\"简约风服装\",\"街头风服装\",\"通勤风服装\",\"韩版系服装\"]\next = ['.jpeg', '.jpg', \".JPG\", \".JPEG\"]\n\ndata = {'categories' : categories}\nheaders = {\n 'accept': 'application/x-www-form-urlencoded'\n }\n\nresponse = requests.request(\"POST\", url, headers=headers, auth=requests.auth.HTTPBasicAuth(AUTH_KEY, ''), data=data)\nresult = json.loads(response.text)\nif not(\"model_id\" in result.keys()):\n print('Error')\n print(result)\n sys.exit(1)\nmodel_id = result[\"model_id\"]\n\nprint(\"NEXT RUN: export NANONETS_MODEL_ID=\" + model_id)\nprint(\"THEN RUN: python ./code/upload-training.py\")\n","sub_path":"NanoNet_fashionStyle/code/create-model.py","file_name":"create-model.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"536564016","text":"import requests\nfrom lxml import html\nimport runeclan.scraper_utils as scraper\n\nBASEPATH='http://www.runeclan.com/clan/'\nXP_TRACKER_PATH='/xp-tracker/'\n\nCRITERIA1_PARAM='criteria_set1'\nCRITERIA2_PARAM='criteria_set2'\nSKILL_PARAM='skill'\n\nLAST_MONTH_CRITERIA='last_month'\nCURRENT_MONTH_CRITERIA='month'\nDOUBLE_WP_WEEKEND_CRITERIA='double_xp_weekend'\nLAST_YEAR_CRITERIA='last_year'\n\nACTIVE_PER_PAGE=50\n\nOVERALL_SKILL_LABEL='Overall'\n\n\ndef get_users(clan, skill, top, mode):\n page = 0\n result = {'skill': '', 'highscores': []}\n basepath = BASEPATH + __get_clan_identifier(clan)\n while True:\n page = page + 1\n users = __get_active_users_page(basepath, skill, page, mode)\n result['highscores'].extend(users['highscores'])\n result['skill'] = users['skill']\n if len(users['highscores']) < ACTIVE_PER_PAGE or (len(result['highscores']) >= top and users['skill'] != OVERALL_SKILL_LABEL):\n break\n return result\n\n\ndef __get_clan_identifier(clan):\n return clan.replace(' ', '_')\n\n\ndef __get_active_users_page(basepath, skill, page, duration):\n response = requests.get(basepath + XP_TRACKER_PATH + str(page), params=__get_parameters(duration, skill))\n dom = html.fromstring(response.content)\n return {'highscores':scraper.get_active_users(dom), 'skill': scraper.get_active_skill(dom)}\n\n\ndef __get_parameters(mode, skill):\n if mode == 'preview':\n return {CRITERIA1_PARAM: CURRENT_MONTH_CRITERIA, CRITERIA2_PARAM: LAST_MONTH_CRITERIA, SKILL_PARAM: skill}\n elif mode == 'normal':\n return {CRITERIA1_PARAM: LAST_MONTH_CRITERIA, CRITERIA2_PARAM: CURRENT_MONTH_CRITERIA, SKILL_PARAM: skill}\n elif mode == 'year':\n return {CRITERIA1_PARAM: LAST_YEAR_CRITERIA, CRITERIA2_PARAM: CURRENT_MONTH_CRITERIA, SKILL_PARAM: skill}\n else:\n return {CRITERIA1_PARAM: DOUBLE_WP_WEEKEND_CRITERIA, CRITERIA2_PARAM: LAST_MONTH_CRITERIA, SKILL_PARAM: skill}","sub_path":"runeclan/xp_tracker.py","file_name":"xp_tracker.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"176416716","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('resorts', '0026_auto_20160221_0621'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='resortlocation',\n name='location_name',\n field=models.CharField(default='', max_length=140, verbose_name=b'location name',\n db_column=b'location_name'),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='resortlocation',\n name='map_lat',\n field=models.FloatField(default=0.0, verbose_name=b'map lat', db_column=b'map_lat'),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='resortlocation',\n name='map_long',\n field=models.FloatField(default=0.0, verbose_name=b'map long', db_column=b'map_long'),\n preserve_default=False,\n )\n ]\n","sub_path":"project/apps/resorts/migrations/0027_auto_20160311_0608.py","file_name":"0027_auto_20160311_0608.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"121691775","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nAuthor: Sergiy Kolodyazhnyy\nDate: August 2nd, 2016\nWritten for: http://askubuntu.com/q/806212/295286\nTested on Ubuntu 16.04 LTS\n\nusage: dynamic_mouse_speed.py [-h] [-q] [-p POINTER] [-s SCROLL] [-v]\n\nSets mouse pointer and scroll speed per window\n\noptional arguments:\n -h, --help show this help message and exit\n -q, --quiet Blocks GUI dialogs.\n -p POINTER, --pointer POINTER\n mouse pointer speed,floating point number from -1 to 1\n -s SCROLL, --scroll SCROLL\n mouse scroll speed,integer value , -10 to 10\n recommended\n -v, --verbose prints debugging information on command line\n\n\n\"\"\"\nfrom __future__ import print_function\nimport gi\ngi.require_version('Gdk', '3.0')\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gdk, Gtk,Gio\nimport time\nimport subprocess\nimport sys\nimport os\nimport argparse\n\n\ndef run_cmd(cmdlist):\n \"\"\" Reusable function for running shell commands\"\"\"\n try:\n stdout = subprocess.check_output(cmdlist)\n except subprocess.CalledProcessError:\n print(\">>> subprocess:\",cmdlist)\n sys.exit(1)\n else:\n if stdout:\n return stdout\n\n\n\ndef get_user_window():\n \"\"\"Select two windows via mouse. \n Returns integer value of window's id\"\"\"\n window_id = None\n while not window_id:\n for line in run_cmd(['xwininfo', '-int']).decode().split('\\n'):\n if 'Window id:' in line:\n window_id = line.split()[3]\n return int(window_id)\n\ndef gsettings_get(schema,path,key):\n \"\"\"Get value of gsettings schema\"\"\"\n if path is None:\n gsettings = Gio.Settings.new(schema)\n else:\n gsettings = Gio.Settings.new_with_path(schema,path)\n return gsettings.get_value(key)\n\ndef gsettings_set(schema,path,key,value):\n \"\"\"Set value of gsettings schema\"\"\"\n if path is None:\n gsettings = Gio.Settings.new(schema)\n else:\n gsettings = Gio.Settings.new_with_path(schema,path)\n return gsettings.set_double(key,value)\n\ndef parse_args():\n \"\"\" Parse command line arguments\"\"\"\n arg_parser = argparse.ArgumentParser(\n description=\"\"\"Sets mouse pointer and scroll \"\"\" + \n \"\"\"speed per window \"\"\")\n arg_parser.add_argument(\n '-q','--quiet', action='store_true',\n help='Blocks GUI dialogs.',\n required=False)\n\n arg_parser.add_argument(\n '-p','--pointer',action='store',\n type=float, help=' mouse pointer speed,' + \n 'floating point number from -1 to 1', required=False)\n\n arg_parser.add_argument(\n '-s','--scroll',action='store',\n type=int, help=' mouse scroll speed,' + \n 'integer value , -10 to 10 recommended', required=False)\n\n arg_parser.add_argument(\n '-v','--verbose', action='store_true',\n help=' prints debugging information on command line',\n required=False)\n return arg_parser.parse_args()\n\ndef get_mouse_id():\n \"\"\" returns id of the mouse as understood by\n xinput command. This works only with one\n mouse attatched to the system\"\"\"\n devs = run_cmd( ['xinput','list','--id-only'] ).decode().strip()\n for dev_id in devs.split('\\n'):\n props = run_cmd( [ 'xinput','list-props', dev_id ] ).decode()\n if \"Evdev Scrolling Distance\" in props:\n return dev_id\n\n\ndef write_rcfile(scroll_speed):\n \"\"\" Writes out user-defined scroll speed\n to ~/.imwheelrc file. Necessary for\n speed increase\"\"\"\n \n number = str(scroll_speed)\n user_home = os.path.expanduser('~')\n with open( os.path.join(user_home,\".imwheelrc\") ,'w' ) as rcfile:\n rcfile.write( '\".*\"\\n' )\n rcfile.write(\"None, Up, Button4, \" + number + \"\\n\" ) \n rcfile.write(\"None, Down, Button5, \" + number + \"\\n\")\n rcfile.write(\"Control_L, Up, Control_L|Button4 \\n\" +\n \"Control_L, Down, Control_L|Button5 \\n\" +\n \"Shift_L, Up, Shift_L|Button4 \\n\" +\n \"Shift_L, Down, Shift_L|Button5 \\n\" )\n\n\n\ndef set_configs(mouse_speed,scroll_speed,mouse_id):\n \"\"\" sets user-defined values\n when the desired window is in focus\"\"\"\n if mouse_speed:\n gsettings_set('org.gnome.desktop.peripherals.mouse',None, 'speed', mouse_speed)\n\n if scroll_speed:\n if scroll_speed > 0:\n subprocess.call(['killall','imwheel'])\n # Is it better to write config here\n # or in main ?\n write_rcfile(scroll_speed)\n subprocess.call(['imwheel'])\n else:\n prop=\"Evdev Scrolling Distance\"\n scroll_speed = str(abs(scroll_speed))\n run_cmd(['xinput','set-prop',mouse_id,prop,scroll_speed,'1','1']) \n \n\n \ndef set_defaults(mouse_speed,scroll_speed,mouse_id):\n \"\"\" restore values , when user-defined window\n looses focus\"\"\"\n if mouse_speed:\n gsettings_set('org.gnome.desktop.peripherals.mouse', None, \n 'speed', mouse_speed)\n\n if scroll_speed:\n if scroll_speed > 0:\n subprocess.call(['killall','imwheel'])\n if scroll_speed < 0:\n prop=\"Evdev Scrolling Distance\"\n run_cmd(['xinput','set-prop',mouse_id,prop,'1','1','1'])\n \n\ndef main():\n \"\"\"Entry point for when program is executed directly\"\"\"\n args = parse_args()\n\n # Get a default configs\n # gsettings returns GVariant, but\n # setting same schema and key requires \n # floating point number\n screen = Gdk.Screen.get_default()\n default_pointer_speed = gsettings_get('org.gnome.desktop.peripherals.mouse', \n None, \n 'speed')\n default_pointer_speed = float(str(default_pointer_speed))\n\n \n # Ask user for values , or check if those are provided via command line\n if not args.quiet:\n text='--text=\"Select window to track\"'\n mouse_speed = run_cmd(['zenity','--info',text])\n \n user_window = get_user_window() \n\n scroll_speed = args.scroll \n pointer_speed = args.pointer\n mouse_id = get_mouse_id()\n\n if pointer_speed: \n if pointer_speed > 1 or pointer_speed < -1:\n\n run_cmd(['zenity','--error',\n '--text=\"Value out of range:' + \n str(pointer_speed) + '\"'])\n sys.exit(1)\n\n # ensure that we will raise the user selected window\n # and activate all the preferences \n flag = True\n for window in screen.get_window_stack():\n if user_window == window.get_xid():\n window.focus(time.time())\n window.get_update_area()\n try:\n while True:\n time.sleep(0.25) # Necessary for script to catch active window\n if screen.get_active_window().get_xid() == user_window:\n if flag:\n set_configs(pointer_speed,scroll_speed,mouse_id) \n flag=False\n \n else:\n if not flag:\n set_defaults(default_pointer_speed, scroll_speed,mouse_id)\n flag = True\n \n if args.verbose: \n print('ACTIVE WINDOW:',str(screen.get_active_window().get_xid()))\n print('MOUSE_SPEED:', str(gsettings_get(\n 'org.gnome.desktop.peripherals.mouse',\n None, 'speed')))\n print('Mouse ID:',str(mouse_id))\n print(\"----------------------\")\n except:\n print(\">>> Exiting main, resetting values\")\n set_defaults(default_pointer_speed,scroll_speed,mouse_id)\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"dynamic_mouse_speed.py","file_name":"dynamic_mouse_speed.py","file_ext":"py","file_size_in_byte":7878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"221005559","text":"from flask_restplus import Resource, fields\nfrom ads.rest import ns_jobgeocount\nfrom ads.repositories import auranest as auranestRepro\nfrom ads.rest.model import queries\nfrom ads.rest.model.auranest_results import auranest_listd\nimport requests\nfrom ads.apiresources import helper\n\n\n@ns_jobgeocount.route('')\nclass JobGeoCount(Resource):\n @ns_jobgeocount.doc(description='get job count for a free text query')\n @ns_jobgeocount.expect(queries.job_query)\n def get(self):\n args = queries.allJobs_query.parse_args()\n args['show-expired'] = 'false'\n query_result = auranestRepro.findAds(args)\n\n loc_resp = {\n 'total': 0,\n 'lan': []\n }\n # GeoKomp add location\n httpSession = requests.Session()\n for ad in query_result['hits']['hits']:\n if ad['_source']['location']:\n loc_text = ad['_source']['location']['translations']['sv-SE']\n loc = helper.get_location_data('POSTORT', loc_text, httpSession)\n if len(loc):\n loc_resp = helper.location_response_builder(loc_resp, loc)\n httpSession.close()\n loc_resp['total'] = helper.get_total_jobCount(loc_resp['lan'])\n return self.marshal_default(loc_resp)\n\n @ns_jobgeocount.marshal_with(auranest_listd)\n def marshal_default(self, results):\n return results\n","sub_path":"ads/rest/endpoint/job_geocount.py","file_name":"job_geocount.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"583481349","text":"from typing import List\nfrom numpy.lib.function_base import average\n\nfrom palloq import compiler\nimport pandas as pd\nfrom pandas.core.base import DataError\nfrom pandas.core.frame import DataFrame\nfrom qiskit.circuit.quantumcircuit import QuantumCircuit\n\n# import qiskit tools\nfrom qiskit.compiler import assemble, transpile, schedule\nfrom qiskit.providers.ibmq import IBMQBackend\n\n\nfrom palloq.compiler.dynamic_multiqc_compose import dynamic_multiqc_compose\nfrom utils.get_backend import get_IBM_backend\nfrom utils.process_counts_distribution import separate_multi_counts\nfrom utils.pickle_tools import pickle_dump, pickle_load\n\n\ndef prep_experiments(qc_list: List[QuantumCircuit], backend: IBMQBackend, physical_dist_list:List[int], save_path, output=False):\n \"\"\"prepare experiments multiple qcs varing hardware usage\"\"\"\n\n # prepare pandas dataframe\n columns = [\"Backend\", \"Physical distance\", \"Hardware Usage (%)\", \"Total Circuit Duration Time\",\"Quantum Circuits\", \"Scheduled Pulse\"]\n df = pd.DataFrame(columns=columns)\n\n # backend info\n num_hw_qubit = backend.configuration().num_qubits\n\n\n for physical_dist in physical_dist_list:\n transpiled, num_usage = dynamic_multiqc_compose(\n queued_qc = qc_list,\n backend= backend,\n routing_method=\"sabre\",\n scheduling_method=\"alap\",\n num_hw_dist=physical_dist,\n return_num_usage = True, \n )\n\n scheduled = [schedule(_tqc, backend = backend) for _tqc in transpiled]\n usage = \"{:.2%}\".format(average([_usage/num_hw_qubit for _usage in num_usage[0:-1]]))\n tdt = sum([_sched._duration for _sched in scheduled])\n df = df.append(\n {\n \"Backend\": backend.name, \n \"Physical distance\": physical_dist, \n \"Hardware Usage (%)\": usage, \n \"Total Circuit Duration Time\": tdt,\n \"Quantum Circuits\": transpiled, \n \"Scheduled Pulse\": scheduled, \n },\n ignore_index=True\n )\n \n # save the DataFrame as pickle file\n pickle_dump(obj = df, path = save_path)\n\n if output: \n return df\n\ndef run_experiments_on_backend(backend, simlator, experiments_df: DataFrame, save_path: str, output=False):\n \"\"\"run the experiments you prepared and save the job information as csv file\n\n Args:\n backend (IBMQBackend): [description]\n experiments_df ([type]): [description]\n save_path ([type]): [description]\n output (bool, optional): If output = True, return dataframe. Defaults to False.\n\n Returns:\n DataFrame: if output = True return dataframe\n \"\"\"\n # define properties of experiments\n shots = 8192\n\n # define simulator\n simulator = get_IBM_backend(\"ibmq_qasm_simulator\")\n\n # prepare pandas dataframe to collect data\n columns = [\"Job ID\", \"Sim Jos ID\", \"Backend\", \"Physical distance\", \"Hardware Usage (%)\", \"Total Circuit Duration Time\",\"Quantum Circuits\", \"Scheduled Pulse\"]\n df = pd.DataFrame(columns=columns)\n\n # run on backends\n for row in experiments_df.itertuples():\n # print(\"0: \", type(row[0]), row[0])\n # print(\"1: \", type(row[1]), row[1])\n # print(\"2: \", type(row[2]), row[2])\n # print(\"3: \", type(row[3]), row[3])\n # print(\"4: \", type(row[4]), row[4])\n # print(\"5: \", type(row[5]), row[5])\n print(\"6: \", type(row[6][0]), row[6][1])\n\n # backend integrity check\n \"\"\"TODO コードのテストが終わったらあとでコメント外す\"\"\"\n # if backend.name != row[1]:\n # raise BackendIntegrityError(\"Backend is not the same as experiments info\")\n \n job_sim_id = simlator.run(\n assemble(experiments=row[6], backend=simlator, shots=shots)\n ).job_id()\n job_id = backend.run(\n assemble(experiments=row[6], backend=backend, shots=shots)\n ).job_id()\n\n df = df.append(\n {\n \"Job ID\": job_id,\n \"Sim Jos ID\": job_sim_id,\n \"Backend\": row[1], \n \"Physical distance\": row[2], \n \"Hardware Usage (%)\": row[3], \n \"Total Circuit Duration Time\": row[4],\n \"Quantum Circuits\": row[5], \n \"Scheduled Pulse\":row[6], \n }\n )\n\n # save the DataFrame as pickle file\n pickle_dump(obj = df, path = save_path)\n\n if output: \n return df\n\n\ndef results_experiments(backend, job_id_path):\n pass\n\nclass BackendIntegrityError(Exception):\n \"\"\"バックエンドが異なる場合のエラー\"\"\"\n pass","sub_path":"physical_distance_layout_pass/execution_time_and_density/exp_tools.py","file_name":"exp_tools.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"637250862","text":"from tag_bag import *\nfrom scivq import *\nfrom user_data import *\nfrom gensim.models import Word2Vec\nfrom gensim import matutils\nfrom numpy import float32 as REAL,array,sum,zeros\nfrom scipy.stats.stats import pearsonr\n\nclass data(object):\n def __init__(self,tag_data,user_data,k,path):\n self.tag_data = tag_data\n self.user_data = user_data\n self.k = k\n self.model = Word2Vec.load_word2vec_format(path, binary=True)\n self.minimium_model = {}\n self.no_match_tag = []\n self.vec_dict = {}\n self.corr_dict = {}\n\n def get_minimium_model(self):\n '''\n :return: minimium model: dict contain just the tag in the bank and corresponding 300 dim vector\n '''\n for item in self.tag_data:\n try:\n vec = self.model[item]\n self.minimium_model[item] = vec\n except KeyError:\n try:\n mean = []\n for word in item.split():\n mean.append(self.model[word])\n mean = matutils.unitvec(array(mean).mean(axis=0)).astype(REAL)\n self.minimium_model[item] = mean\n except KeyError:\n print('ooops!',item,\"does not appear in the google database\")\n self.no_match_tag.append(item)\n if self.no_match_tag != []:\n print('missing tags', self.no_match_tag)\n\n\n\n def clustering(self):\n '''\n :return: dict that tells which tag belongs to which cluster {key: tag, value: cluster id}\n '''\n if self.minimium_model == {}:\n print('minimium model has not been load')\n raise AttributeError\n elif type(self.minimium_model) != dict:\n raise TypeError\n else:\n vec = []\n vec_key = []\n for key in self.minimium_model.keys():\n vec_key.append(key)\n vec.append(self.minimium_model[key])\n vec_array = array(vec).reshape((-1,300))\n centers,dist = kmeans(vec_array,self.k)\n code,distance = vq(vec_array,centers)\n for i in range(len(code)):\n self.vec_dict[vec_key[i]] = code[i]\n\n\n def vote(self,topn = 3):\n '''\n :param vec_dict: dict that tells which tag belongs to which cluster {key: tag, value: cluster id}\n :param user_data: user data\n :param k: number of cluster\n :param topn: optional, default 3, return top n similar user\n :return: dict that contain top n most similar user {key : user, value: suggest users}\n '''\n if self.vec_dict == {}:\n print('clustering not completed')\n raise AttributeError\n elif type(self.vec_dict) != dict:\n raise TypeError\n else:\n user_item_dict = {}\n for key in self.user_data.keys():\n vote_array = zeros((self.k,1))\n for item in self.user_data[key]:\n vote_array[self.vec_dict[item]] += 1\n user_item_dict[key] = vote_array/sum(vote_array)\n\n for key1 in self.user_data.keys():\n temp_dict = {}\n short_list = []\n for key2 in self.user_data.keys():\n if key2!=key1:\n temp_dict[key2] = (pearsonr(user_item_dict[key1],user_item_dict[key2])[0])\n most_similar = sorted(temp_dict, key=temp_dict.get,reverse=True)\n for i in range(topn):\n short_list.append(most_similar[i])\n self.corr_dict[key1] = short_list\n","sub_path":"mysite/similarity/similarity.py","file_name":"similarity.py","file_ext":"py","file_size_in_byte":3642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"105040502","text":"from flask import Flask, render_template, request, send_file\nfrom flask_sqlalchemy import SQLAlchemy\nfrom send_email import send_email\nfrom sqlalchemy.sql import func\nfrom werkzeug import secure_filename\n\napp= Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI']=\"postgres://akezcdllpanpyq:80a8d64c47a482d3aa77e616047fd535a9dec0979ca6952f070b1611a0f15f2a@ec2-52-6-143-153.compute-1.amazonaws.com:5432/dc5ei6gj8fe59g?sslmode=require\"\ndb=SQLAlchemy(app)\n\nclass Data(db.Model):\n __tablename__=\"data\"\n id=db.Column(db.Integer, primary_key=True)\n email=db.Column(db.String(120), unique=True)\n shoe=db.Column(db.Integer)\n\n def __init__(self, email, shoe):\n self.email=email\n self.shoe=shoe\n\n@app.route (\"/\")\ndef index():\n return render_template (\"index.html\")\n\n@app.route(\"/success\", methods=['POST'])\ndef success():\n global file\n if request.method=='POST':\n Email=request.form[\"email_name\"]\n Shoe=request.form[\"shoe_name\"]\n if db.session.query(Data).filter(Data.email==Email).count() == 0:\n data=Data(Email,Shoe)\n db.session.add(data)\n db.session.commit()\n average_shoe=db.session.query(func.avg(Data.shoe)).scalar()\n average_shoe=round(average_shoe,2)\n count=db.session.query(Data.shoe).count()\n send_email(Email,Shoe,average_shoe,count)\n return render_template(\"success.html\")\n return render_template(\"index.html\", text=\"It looks like we already have data from this email address\")\n\n\n@app.route(\"/download\")\ndef download():\n return send_file(\"Uploaded\"+file.filename, attachment_filename=\"yourfile.csv\", as_attachment=True)\n\n\nif __name__ == \"__main__\": #meaning- if script is executed, not imported we will execute those lines\n app.debug=True\n app.run() #we will run the app\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"310863390","text":"import cv2\nimport numpy as np\nimport json\nfrom trackbar import Trackbars\nfrom trackbar2 import Trackbar\nimport shapeDetection as shape\n\nHSV = 0\nCANNY = 1\n\n\"\"\"\nPress 'q' to quit\n 'w' to toggle HSV trackbars\n 'e' to toggle Canny threshold trackbars\n\"\"\"\n\ndef startWebcam():\n cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) # open the default camera\n cap.set(3, 640) # CV_CAP_PROP_FRAME_WIDTH\n cap.set(4, 480) # CV_CAP_PROP_FRAME_HEIGHT\n cap.set(10, 150) # CV_CAP_PROP_BRIGHTNESS\n\n # retrieve saved values\n with open('trackbarValues.json') as json_file:\n raw = json.load(json_file)\n hsv = raw[str(HSV)]\n lowerHSV = np.array(hsv[\"LowerHSV\"])\n upperHSV = np.array(hsv[\"UpperHSV\"])\n canny = raw[str(CANNY)]\n\n # for trackbars\n trackbarOn = [False, False] # [HSV, CANNY]\n tb = Trackbars(lowerHSV, upperHSV)\n cannyTb = Trackbar(canny, \"Canny Thresholds\")\n\n\n while True:\n success, img = cap.read()\n imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n mask = cv2.inRange(imgHSV, lowerHSV, upperHSV)\n\n # ==== key controls ====\n keyPressed = cv2.waitKey(1)\n # quit \n if (keyPressed & 0xFF) == ord('q'):\n cap.release()\n cv2.destroyAllWindows()\n\n # quit with saving\n elif (keyPressed & 0xFF) == ord('s'):\n raw[str(HSV)][\"LowerHSV\"] = lowerHSV.tolist()\n raw[str(HSV)][\"UpperHSV\"] = upperHSV.tolist()\n with open('trackbarValues.json', 'w') as json_file:\n json.dump(raw, json_file)\n\n cap.release()\n cv2.destroyAllWindows()\n \n # HSV trackbar\n elif (keyPressed & 0xFF) == ord('w'):\n # turn on trackbar\n if not trackbarOn[HSV]:\n tb.startTrackbars()\n trackbarOn[HSV] = True\n else:\n values = tb.closeTrackbars()\n trackbarOn[HSV] = False\n\n # Canny trackbar\n elif (keyPressed & 0xFF) == ord('e'):\n if not trackbarOn[CANNY]:\n cannyTb.startTrackbars()\n trackbarOn[CANNY] = True\n else:\n cannyTb.closeTrackbars()\n trackbarOn[CANNY] = False\n # =======================\n\n # Necessary operations when respective trackbar is on\n if trackbarOn[HSV]:\n cv2.imshow(\"Mask\", mask)\n if trackbarOn[CANNY]:\n cannyTb.getTrackbarValues()\n\n # Detection operations\n img2 = np.ones((480,640,3))\n shape.detectShape(img, mask, img2)\n shape.detectLines(img, canny[\"Threshold1\"][0], canny[\"Threshold2\"][0], img2)\n\n cv2.imshow(\"Webcam\", img)\n cv2.imshow(\"Result\", img2)\n \n\nstartWebcam()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"137834696","text":"\"\"\"有五个人坐在一起,问第五个人多少岁?他说比第四个人大2岁。问第四个人岁数,他说比\r\n第三个人大2岁。问第三个人,又说比第二个大两岁。问第二个人,说比第一个人大两岁。最后\r\n问第一个人,他说是10岁。请问第五个人多大?\"\"\"\r\n\r\ndef age(n):\r\n if n == 1:\r\n a = 10\r\n else:\r\n a = 2 + age(n-1)\r\n return a\r\n\r\nprint(age(5))","sub_path":"lizi/diguihuitui.py","file_name":"diguihuitui.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"232241098","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom utilities import data, utilities\n\n\nnb_states = 10\nfiles = data.files\nsides = data.sides\nframes = data.frames\nhills = utilities.get_index(frames, files, sides)\n\npathsZ, pathsY = utilities.make_toe(files, hills, sides)\n\nf1, ax1 = plt.subplots(1, 1)\nf2, ax2 = plt.subplots(1, 1)\n\nfor pz, py in zip(pathsZ, pathsY):\n\n ax1.plot(pz)\n# ax1.legend(['subject 00', 'subject 01', 'subject 02', 'subject 03', 'subject 05',\n# 'subject 07', 'subject 09', 'subject 10'])\n ax1.set_xlabel(\"Frames\")\n ax1.set_ylabel(\"Position (mm)\")\n ax1.set_title(\"Z Trajectories\")\n\n ax2.plot(py)\n# ax2.legend(['subject 00', 'subject 01', 'subject 02', 'subject 03', 'subject 05',\n# 'subject 07', 'subject 09', 'subject 10'])\n ax2.set_xlabel(\"Frames\")\n ax2.set_ylabel(\"Position (mm)\")\n ax2.set_title(\"Y Trajectories\")\n\nplt.show()\n","sub_path":"stair_climbing_paper/Plot_Traj.py","file_name":"Plot_Traj.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"550309090","text":"import xlrd \n\nloc=(\"Test-Cases-IT302-Lab-Program-5.xlsx\")\nwb = xlrd.open_workbook(loc) \nmysheet = wb.sheet_by_index(0) \nr=[]\nfor i in range(0,mysheet.nrows):\n\tfor j in range(0,mysheet.ncols):\n\t\tif mysheet.cell_value(i,j)==\"f(x,y)\":\n\t\t\tr.append([i,j])\n\t\t\tbreak\nr1=[]\nr2=[]\ncheck=0\nfor c1 in r:\n\tcheck=0\n\tfor i in range(c1[1]+2,mysheet.ncols):\n\t\t\n\t\tif mysheet.cell(c1[0]+1,i).value == xlrd.empty_cell.value:\n\t\t\tr1.append([c1[1]+2,i])\n\t\t\tcheck=1\n\t\t\tbreak\n\tif check==0:\n\t\tr1.append([c1[1]+2,i+1])\nfor c1 in r:\n\tcheck=0\n\tfor i in range(c1[0]+2,mysheet.nrows):\n\t\tif mysheet.cell(i,c1[1]+1).value == xlrd.empty_cell.value:\n\t\t\tr2.append([c1[0]+2,i])\n\t\t\tcheck=1\n\t\t\tbreak\n\tif check==0:\n\t\tr2.append([c1[0]+2,i+1])\n\n\nl=len(r1)\nfor t in range(0,l):\n\n\tf={}\n\toutput=open(f\"181IT237_IT302_P5_Output_TC{t+1}.txt\",\"a\")\n\tfor i in range(r1[t][0],r1[t][1]):\n\t\tfor j in range(r2[t][0],r2[t][1]):\n\t\t\tf[str(int(mysheet.cell_value(r2[t][0]-1, i)))+\",\"+str(int(mysheet.cell_value(j, r1[t][0]-1)))]=mysheet.cell_value(j, i)\n\n\tprint(f\"F(x,y) {t+1}: \",f)\n\tfor i in f:\n\t\tif f[i]>1:\n\t\t\toutput.write(f\"\\nF({i}): \"+str(round(f[i],2))+\" is invalid because it's greater than one\")\n\t\t\tbreak\n\t\toutput.write(f\"\\nF({i}): \"+str(round(f[i],2)))\n\tegxy=0\n\tfor i in f:\n\t\txyvalue=i.split(\",\")\n\t\tx=int(xyvalue[0])\n\t\ty=int(xyvalue[1])\n\t\tegxy+=(x*y)*f[i]\n\tprint(f\"Value of g(X,Y)=XY for f{t+1}: \"+str(round(egxy,2)))\n\toutput.write(f\"\\nValue of g(X,Y)=XY for f{t+1}: \"+str(round(egxy,2)))\n\tmeanx=0\n\tfor i in f:\n\t\txyvalue=i.split(\",\")\n\t\tx=int(xyvalue[0])\n\t\ty=int(xyvalue[1])\n\t\tmeanx+=x*f[i]\n\tprint(\"μX : \"+ str(round(meanx,2)))\n\toutput.write(f\"\\nμX : \"+str(round(meanx,2)))\n\n\tmeany=0\n\tfor i in f:\n\t\txyvalue=i.split(\",\")\n\t\tx=int(xyvalue[0])\n\t\ty=int(xyvalue[1])\n\t\tmeany+=y*f[i]\n\tprint(\"μY : \"+str(round(meany,2)))\n\tprint(\"Covariance of X and Y is : \"+str(round(egxy-(meanx*meany),2)))\n\toutput.write(f\"\\nμY : \"+str(round(meany,2)))\n\toutput.close()\n","sub_path":"pns/lab6/181IT237_IT302_P6.py","file_name":"181IT237_IT302_P6.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"340181393","text":"#import random.py\nfrom random import *\n\ndef quickSort(A,start,end):\n if(start >= end):\n return\n pIndex = randomizePartition(A,start,end)\n quickSort(A,start,pIndex-1)\n quickSort(A,pIndex+1,end)\n return A\n\ndef randomizePartition(A,start,end):\n pIndex = randint(start,end)\n temp = A[end]\n A[end] = A[pIndex]\n A[pIndex] = temp\n return partition(A,start,end)\n\ndef partition(A,start,end):\n #print(\"Gets in here\")\n pivot = A[end]\n pIndex = start\n for i in range(start,end):\n if A[i] <= pivot:\n temp = A[i]\n A[i] = A[pIndex]\n A[pIndex] = temp\n pIndex += 1\n temp = A[end]\n A[end] = A[pIndex]\n A[pIndex] = temp\n return pIndex\n\ndef main():\n l = [2,4,5,1,6,3,9,7,8]\n print(\"Original List: \",l)\n print(\"Sorted List: \", quickSort(l,0,len(l)-1))\nmain()\n","sub_path":"quickSort.py","file_name":"quickSort.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"325671692","text":"\"\"\" Compiled: 2020-09-18 10:38:51 \"\"\"\n\n#__src_file__ = \"extensions/BankDebtWSO/etc/FWSOFile.py\"\n\"\"\"-------------------------------------------------------------------------------------------------------\nMODULE\n FWSOFile -\n\n (c) Copyright 2015 SunGard FRONT ARENA. All rights reserved.\n\nDESCRIPTION\n Responsible for reading data from WSO XML-file and making it accessible via a class.\n\n-------------------------------------------------------------------------------------------------------\"\"\"\n\nfrom FWSOFileFormatHook import ParseXMLReconciliationDocument\n\n\nclass WSOFile(object):\n ''' Represents a WSO file. Can construct an item handler-object\n from where the data can easily be accessed.\n '''\n def __init__(self, filePath, primaryKeyName):\n self.filePath = filePath\n self.primaryKeyName = primaryKeyName\n \n def WsoDict(self):\n wsoDict = dict()\n fileHandler = open(self.filePath, 'r')\n itemDicts = ParseXMLReconciliationDocument(fileHandler)\n \n for itemDict in itemDicts:\n primaryKey = itemDict.get(self.primaryKeyName)\n wsoDict[primaryKey] = itemDict\n return wsoDict\n","sub_path":"Extensions/WSO Bank Debt/FPythonCode/FWSOFile.py","file_name":"FWSOFile.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"207594793","text":"\"\"\"Modify a column Survey Table\n\nRevision ID: 8c59ff6b5ccf\nRevises: 2afe09f9d656\nCreate Date: 2018-11-19 00:49:37.668848\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '8c59ff6b5ccf'\ndown_revision = '2afe09f9d656'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('survey', 'reply_when')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('survey', sa.Column('reply_when', mysql.DATETIME(), nullable=True))\n # ### end Alembic commands ###\n","sub_path":"database/versions/8c59ff6b5ccf_modify_a_column_survey_table.py","file_name":"8c59ff6b5ccf_modify_a_column_survey_table.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"118537894","text":"'''\ncrie um programa que leia duas notas de um aluno\ne calcule sua média, mostrando uma mensagem no final\nde acordo com a média atingida:\n\nmédia abaixo de 5.0: reprovado\nmédia entre 5.0 e 6.0: recuperação\nmédia 7.0 ou superior: aprovado\n'''\n\nnota1 = float(input('Digite a primeira nota: '))\nnota2 = float(input('Digite a segunda nota: '))\nmedia = (nota1 + nota2)/2\n\nif media >= 7:\n print('O aluno está aprovado com média {}'.format(media))\nelif media >= 5:\n print('O alunoe está de recuperação com média {}'.format(media))\nelse:\n print('O aluno está reprovado com média {}'.format(media))","sub_path":"cursoEmVideo/resolucaoPessoal/040.py","file_name":"040.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"515442979","text":"from __future__ import unicode_literals\nfrom django.db import models\n\n\nclass Order(models.Model):\n \"\"\"\n Order table contains info about orders.\n No relations between other apps or tables.\n\n user_id - id from Customer table, got from Django session\n total - sum of all items in order\n destination_address - exactly what it sounds like\n customer_phone - get from customer table\n create_date - order create date\n update_date - order update date\n status - order status\n payment_method - exactly what it sounds like, but does not use\n \"\"\"\n user_id = models.IntegerField()\n total = models.FloatField(default=0)\n destination_address = models.CharField(max_length=255, blank=True, null=True)\n telephone = models.CharField(max_length=32, blank=True, null=True)\n additional_info = models.TextField(blank=True, null=True)\n created_date = models.DateTimeField(auto_now=True, verbose_name=u'Created date')\n updated_date = models.DateTimeField(auto_now=True, verbose_name=u'Updated date')\n status = models.CharField(default='new', max_length=10, choices=(\n (u'new', 'new order'),\n (u'processing', u'order is processing'),\n (u'delivering', u'order is delivering'),\n (u'delivered', u'order delivered'),\n (u'completed', u'order complete'),\n (u'canceled', u'order canceled')\n ))\n payment_method = models.CharField(default='cash', max_length=4, choices=(\n (u'cash', 'cash on delivery'),\n (u'card', u'credit/debit card')\n ))\n\n def __unicode__(self):\n return unicode('{} {}'.format(self.customer, self.total))\n\n @staticmethod\n def create_order(user_d):\n order = Order(user_id=user_d)\n order.save()\n return order.id\n\n @staticmethod\n def recalculate_total(order_id):\n # Get all items from cart\n total = 0\n exist_items = OrderItem.objects.filter(order_id=order_id)\n\n # Recalculate total\n for item in exist_items:\n total += item.price * item.quantity\n\n # Get cart from db\n order = Order.objects.get(pk=order_id)\n order.total = total\n order.save()\n\n\nclass OrderItem(models.Model):\n order = models.ForeignKey(Order)\n p_code = models.CharField(max_length=15)\n title = models.CharField(max_length=255)\n price = models.FloatField(default=0)\n quantity = models.PositiveIntegerField(default=1)\n\n def __unicode__(self):\n return unicode('{} {}'.format(self.title, self.quantity))\n\n def delete(self, *args, **kwargs):\n super(OrderItem, self).delete(*args, **kwargs)\n Order.recalculate_total(order_id=self.order_id)\n\n def save(self, *args, **kwargs):\n super(OrderItem, self).save(*args, **kwargs)\n Order.recalculate_total(order_id=self.order_id)\n\n @staticmethod\n def add_items_to_order(order_id, session_cart):\n # Get all items from cart\n products = session_cart['products']\n\n # Insert into OrderItem table\n for p_code, params in products.items():\n\n # If item already in order\n try:\n item = OrderItem.objects.get(order_id=order_id, p_code=p_code)\n item.quantity += params['n']\n item.save()\n\n except OrderItem.DoesNotExist:\n\n # Create new item\n item = OrderItem(order_id=order_id, p_code=p_code,\n title=params['title'], price=params['price'],\n quantity=params['n'])\n item.save()\n\n","sub_path":"django_app/agregator/order/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"587405741","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nimport time\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import metrics\nfrom sklearn.metrics import matthews_corrcoef,make_scorer\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import cross_validate\n\n\n\nt1 = time.time()\ndata=pd.read_csv('inputfile_for_ML_fivemer.csv',header = None,index_col = 0)\n#print(data)\nx=data.iloc[:,:32]\n#print(x)\ny=data.iloc[:,32]\n#print(y)\nx=(x.div(x.sum(axis=1), axis=0)) # divide each row by sum of row\nx = x.to_numpy()\n\ny = y[:,np.newaxis]\n\n\nknn=KNeighborsClassifier( n_neighbors=5)\n\nt1 = time.time()\n\nscoring = {'accuracy':'accuracy','f1_weighted':'f1_weighted','mcc_scorer': make_scorer(matthews_corrcoef),'precision': 'precision','recall':'recall','roc_auc':'roc_auc'}\n\nfrom sklearn.model_selection import ShuffleSplit\ncv = ShuffleSplit(n_splits=10, test_size=0.1)\ncv_precision=np.zeros(10)\ncv_recall=np.zeros(10)\ncv_roc_auc=np.zeros(10)\ncv_mcc=np.zeros(10)\ncv_accuracy=np.zeros(10)\ncv_f1_weighted=np.zeros(10)\nfor i in range(0,10):\n cv_score = (cross_validate( knn, x, y, scoring=scoring, cv=cv))\n cv_precision[i]=np.mean(cv_score['test_precision'])\n cv_recall[i]=np.mean(cv_score['test_recall'])\n cv_roc_auc[i]=np.mean(cv_score['test_roc_auc'])\n cv_mcc[i]=np.mean(cv_score['test_mcc_scorer']) \n cv_accuracy[i]=np.mean(cv_score['test_accuracy']) \n cv_f1_weighted[i]=np.mean(cv_score['test_f1_weighted']) \n \n \nt2 = time.time() \n\n\nprint(np.mean(cv_accuracy))\nprint(np.mean(cv_f1_weighted))\nprint(np.mean(cv_precision))\nprint(np.mean(cv_recall))\nprint(np.mean(cv_roc_auc))\nprint(np.mean(cv_mcc))\nprint(f\"It took {t2 - t1} seconds to process.\")\n\n\n\n\n\n\n\n\n","sub_path":"kNN_script.py","file_name":"kNN_script.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"219120389","text":"# Copyright (c) 2014 Rackspace Hosting\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 copy\n\nimport six\n\nfrom designate.openstack.common import importutils\n\n\nclass NotSpecifiedSentinel:\n pass\n\n\ndef get_attrname(name):\n \"\"\"Return the mangled name of the attribute's underlying storage.\"\"\"\n return '_%s' % name\n\n\ndef make_class_properties(cls):\n \"\"\"Build getter and setter methods for all the objects attributes\"\"\"\n cls.FIELDS = list(cls.FIELDS)\n\n for supercls in cls.mro()[1:-1]:\n if not hasattr(supercls, 'FIELDS'):\n continue\n for field in supercls.FIELDS:\n if field not in cls.FIELDS:\n cls.FIELDS.append(field)\n\n for field in cls.FIELDS:\n def getter(self, name=field):\n return getattr(self, get_attrname(name), None)\n\n def setter(self, value, name=field):\n if (self.obj_attr_is_set(name) and value != self[name]\n or not self.obj_attr_is_set(name)):\n self._obj_changes.add(name)\n\n if (self.obj_attr_is_set(name) and value != self[name]\n and name not in self._obj_original_values.keys()):\n self._obj_original_values[name] = self[name]\n\n return setattr(self, get_attrname(name), value)\n\n setattr(cls, field, property(getter, setter))\n\n\nclass DesignateObjectMetaclass(type):\n def __init__(cls, names, bases, dict_):\n make_class_properties(cls)\n\n\nclass DictObjectMixin(object):\n \"\"\"\n Mixin to allow DesignateObjects to behave like dictionaries\n\n Eventually, this should be removed.\n \"\"\"\n def __getitem__(self, key):\n return getattr(self, key)\n\n def __setitem__(self, key, value):\n setattr(self, key, value)\n\n def __contains__(self, item):\n return item in self.FIELDS\n\n def get(self, key, default=NotSpecifiedSentinel):\n if key not in self.FIELDS:\n raise AttributeError(\"'%s' object has no attribute '%s'\" % (\n self.__class__, key))\n\n if default != NotSpecifiedSentinel and not self.obj_attr_is_set(key):\n return default\n else:\n return getattr(self, key)\n\n def update(self, values):\n for k, v in values.iteritems():\n setattr(self, k, v)\n\n def iteritems(self):\n for field in self.FIELDS:\n if self.obj_attr_is_set(field):\n yield field, getattr(self, field)\n\n def __iter__(self):\n for field in self.FIELDS:\n if self.obj_attr_is_set(field):\n yield field, getattr(self, field)\n\n items = lambda self: list(self.iteritems())\n\n\nclass PersistentObjectMixin(object):\n \"\"\"\n Mixin class for Persistent objects.\n\n This adds the fields that we use in common for all persisent objects.\n \"\"\"\n FIELDS = ['id', 'created_at', 'updated_at', 'version']\n\n\n@six.add_metaclass(DesignateObjectMetaclass)\nclass DesignateObject(DictObjectMixin):\n FIELDS = []\n\n @staticmethod\n def from_primitive(primitive):\n \"\"\"\n Construct an object from primitive types\n\n This is used while deserializing the object.\n\n NOTE: Currently all the designate objects contain primitive types that\n do not need special handling. If this changes we need to modify this\n function.\n \"\"\"\n cls = importutils.import_class(primitive['designate_object.name'])\n\n instance = cls()\n\n for field, value in primitive['designate_object.data'].items():\n if isinstance(value, dict) and 'designate_object.name' in value:\n instance[field] = DesignateObject.from_primitive(value)\n else:\n instance[field] = value\n\n instance._obj_changes = set(primitive['designate_object.changes'])\n instance._obj_original_values = \\\n primitive['designate_object.original_values']\n\n return instance\n\n def __init__(self, **kwargs):\n self._obj_changes = set()\n self._obj_original_values = dict()\n\n for name, value in kwargs.items():\n if name in self.FIELDS:\n setattr(self, name, value)\n else:\n raise TypeError(\"'%s' is an invalid keyword argument\" % name)\n\n def to_primitive(self):\n \"\"\"\n Convert the object to primitive types so that the object can be\n serialized.\n NOTE: Currently all the designate objects contain primitive types that\n do not need special handling. If this changes we need to modify this\n function.\n \"\"\"\n class_name = self.__class__.__name__\n if self.__module__:\n class_name = self.__module__ + '.' + self.__class__.__name__\n\n data = {}\n\n for field in self.FIELDS:\n if self.obj_attr_is_set(field):\n if isinstance(self[field], DesignateObject):\n data[field] = self[field].to_primitive()\n else:\n data[field] = self[field]\n\n return {\n 'designate_object.name': class_name,\n 'designate_object.data': data,\n 'designate_object.changes': list(self._obj_changes),\n 'designate_object.original_values': dict(self._obj_original_values)\n }\n\n def obj_attr_is_set(self, name):\n \"\"\"\n Return True or False depending of if a particular attribute has had\n an attribute's value explicitly set.\n \"\"\"\n return hasattr(self, get_attrname(name))\n\n def obj_what_changed(self):\n \"\"\"Returns a set of fields that have been modified.\"\"\"\n return set(self._obj_changes)\n\n def obj_get_changes(self):\n \"\"\"Returns a dict of changed fields and their new values.\"\"\"\n changes = {}\n\n for key in self.obj_what_changed():\n changes[key] = self[key]\n\n return changes\n\n def obj_reset_changes(self, fields=None):\n \"\"\"Reset the list of fields that have been changed.\"\"\"\n if fields:\n self._obj_changes -= set(fields)\n for field in fields:\n self._obj_original_values.pop(field, None)\n\n else:\n self._obj_changes.clear()\n self._obj_original_values = dict()\n\n def obj_get_original_value(self, field):\n \"\"\"Returns the original value of a field.\"\"\"\n if field in self._obj_original_values.keys():\n return self._obj_original_values[field]\n elif self.obj_attr_is_set(field):\n return getattr(self, field)\n else:\n raise KeyError(field)\n\n def __deepcopy__(self, memodict=None):\n \"\"\"\n Efficiently make a deep copy of this object.\n\n \"Efficiently\" is used here a relative term, this will be faster\n than allowing python to naively deepcopy the object.\n \"\"\"\n\n memodict = memodict or {}\n\n c_obj = self.__class__()\n\n for field in self.FIELDS:\n if self.obj_attr_is_set(field):\n c_field = copy.deepcopy(getattr(self, field), memodict)\n setattr(c_obj, field, c_field)\n\n c_obj._obj_changes = set(self._obj_changes)\n\n return c_obj\n\n def __eq__(self, other):\n if self.__class__ != other.__class__:\n return False\n\n return self.to_primitive() == other.to_primitive()\n\n def __ne__(self, other):\n return not(self.__eq__(other))\n","sub_path":"designate/objects/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":7954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"474474473","text":"import setuptools\n\nwith open('README.md', 'r') as f:\n\tlong_description = f.read()\n\nsetuptools.setup(\n\tname='gaugan',\n\tversion='1.1',\n\tauthor='Erik Keresztes',\n\tauthor_email='erik@erik.cash',\n\tdescription='An interface for NVIDIA\\'s gauGAN project that turns crude drawings into realistic images using AI.',\n\tlong_description=long_description,\n\tlong_description_content_type='text/markdown',\n\turl='https://github.com/erikKeresztes/gaugan.py',\n\tpackages=setuptools.find_packages(),\n\tclassifiers=[\n\t\t\"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: The Unlicense (Unlicense)\",\n\t\t\"Operating System :: OS Independent\"\n\t],\n\tpython_requires='>=3',\n\tinstall_requires=[\n\t\t'requests'\n\t]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"352413212","text":"import os\nimport sys\nfrom pathlib import Path\n\nimport numpy as np\nfrom distutils.core import Extension\nfrom Cython.Build import cythonize\n\nfrom distutils.errors import CCompilerError, DistutilsExecError, DistutilsPlatformError\nfrom distutils.command.build_ext import build_ext\n\nextensions = [\n Extension(\n \"distance_calc\",\n [\"backend/geotools/distance_calc.pyx\"],\n libraries=[\"shp\", \"proj\"],\n library_dirs=[\"usr/lib64\"],\n include_dirs=[\n '/usr/include',\n np.get_include(),\n str(Path(\"../../tools/cShapeTools/include/PathFinder\").absolute())\n ],\n )\n]\n\n\n# class BuildFailed(Exception):\n\n# pass\n\n\nclass ExtBuilder(build_ext):\n # This class allows C extension building to fail.\n\n def run(self):\n # try:\n build_ext.run(self)\n # except (DistutilsPlatformError, FileNotFoundError):\n # pass\n\n def build_extension(self, ext):\n # try:\n build_ext.build_extension(self, ext)\n self.inplace = 1\n build_ext.build_extension(self, ext)\n # except (CCompilerError, DistutilsExecError, DistutilsPlatformError, ValueError):\n # pass\n\n\ndef build(setup_kwargs):\n \"\"\"\n This function is mandatory in order to build the extensions.\n \"\"\"\n setup_kwargs.update(\n {\"ext_modules\": cythonize(extensions), \"cmdclass\": {\"build_ext\": ExtBuilder}}\n )\n","sub_path":"webapp/backend/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"641020075","text":"data_frame_data = []\nfor i, person in enumerate(persons[:100]):\n print(person)\n data_frame_data.append(person)\n for j, pred in enumerate(prediction[i]):\n if pred:\n if labels[j] == 'other':\n print('other')\n data_frame_data.append('Other')\n else:\n data_frame_data.append(translate_label_dict[labels[j]])\n print(translate_label_dict[labels[j]])\n\ndf = pd.DataFrame({'Person and Precited job': data_frame_data})\nwriter = ExcelWriter('person_and_predicted.xlsx')\ndf.to_excel(writer,'Sheet1',index=False)\nwriter.save()\n","sub_path":"functions/write_to_excell.py","file_name":"write_to_excell.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"406284081","text":"import pyrefactor\nimport os\n\n\ndef refactor(func, data_dir=None):\n\n data_dir = data_dir if data_dir else os.path.join(os.getcwd(), \".refactor\")\n compare_dir = os.path.join(data_dir, f\"{data_dir}/compare\")\n full_data_dir = os.path.join(data_dir, f\"{data_dir}/full\")\n\n compare_loader = pyrefactor.DataLoader.get_loader(func, compare_dir)\n full_loader = pyrefactor.DataLoader.get_loader(func, full_data_dir)\n change_detector = pyrefactor.ChangeDetector(func, compare_loader, full_loader)\n\n def function_wrapper(*args, **kwargs):\n args = args if args is not None else ()\n kwargs = kwargs if kwargs is not None else {}\n result = func(*args, **kwargs)\n if change_detector.has_data_for_args(*args, **kwargs):\n change_detector.assert_result_has_not_changed(result, *args, **kwargs)\n else:\n change_detector.add_data_for_args(result, *args, **kwargs)\n return result\n\n return function_wrapper\n","sub_path":"pyrefactor/refactor.py","file_name":"refactor.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"239315577","text":"'''@docstring Common.py\n\nHome to commonly used tools available for use that can be generic or TIMBER specific\n\n'''\n\nimport json, ROOT, os\nfrom ROOT import RDataFrame\nimport CMS_lumi, tdrstyle\nfrom contextlib import contextmanager\nfrom collections import OrderedDict\n###################\n# TIMBER specific #\n###################\n# Draws a cutflow histogram using the report feature of RDF.\ndef CutflowHist(name,node):\n filters = node.DataFrame.GetFilterNames()\n rdf_report = node.DataFrame.Report()\n ncuts = len(filters)\n h = ROOT.TH1F(name,name,ncuts,0,ncuts)\n for i,filtername in enumerate(filters): \n cut = rdf_report.At(filtername)\n h.GetXaxis().SetBinLabel(i+1,filtername)\n h.SetBinContent(i+1,cut.GetPass())\n\n return h\n\ndef CutflowTxt(name,node):\n filters = node.DataFrame.GetFilterNames()\n rdf_report = node.DataFrame.Report()\n ncuts = len(filters)\n out = open(name,'w')\n for i,filtername in enumerate(filters): \n cut = rdf_report.At(filtername)\n out.write('%s %s'%(filtername,cut.GetPass()))\n out.close()\n\n\n###########\n# Generic #\n###########\ndef CompileCpp(blockcode,library=False):\n if os.environ[\"TIMBERPATH\"] not in ROOT.gSystem.GetIncludePath():\n ROOT.gInterpreter.AddIncludePath(os.environ[\"TIMBERPATH\"]+'/')\n\n if not library:\n if '.cc' not in blockcode:\n ROOT.gInterpreter.Declare(blockcode)\n else:\n blockcode_str = open(blockcode,'r').read()\n ROOT.gInterpreter.Declare(blockcode_str)\n elif '.c' in blockcode:\n lib_path = blockcode.replace('.','_')+'.so'\n # If library exists and is older than the cc file, just load\n loaded = False\n if os.path.exists(lib_path):\n mod_time_lib = os.path.getmtime(lib_path)\n mod_time_cc = os.path.getmtime(blockcode)\n if mod_time_lib > mod_time_cc:\n print ('Loading library...')\n ROOT.gSystem.Load(lib_path)\n loaded = True\n \n # Else compile a new lib\n if not loaded:\n ROOT.gSystem.AddIncludePath(\" -I%s \"%os.getcwd())\n print ('Processing library...')\n ROOT.gROOT.ProcessLine(\".L \"+blockcode+\"+\")\n\ndef openJSON(f):\n return json.load(open(f,'r'), object_hook=ascii_encode_dict) \n\ndef ascii_encode_dict(data): \n ascii_encode = lambda x: x.encode('ascii') if isinstance(x, unicode) else x \n return dict(map(ascii_encode, pair) for pair in data.items())\n\ndef GetHistBinningTuple(h):\n # At least 1D (since TH2 and TH3 inherit from TH1)\n if isinstance(h,ROOT.TH1):\n # Variable array vs fixed binning\n if h.GetXaxis().GetXbins().GetSize() > 0:\n xbinning = (h.GetNbinsX(),h.GetXaxis().GetXbins())\n else:\n xbinning = (h.GetNbinsX(),h.GetXaxis().GetXmin(),h.GetXaxis().GetXmax())\n ybinning = ()\n zbinning = ()\n dimension = 1\n else:\n raise TypeError('ERROR: GetHistBinningTuple() does not support a template histogram of type %s. Please provide a TH1, TH2, or TH3.'%type(h))\n\n # Check if 2D\n if isinstance(h,ROOT.TH2):\n # Y variable vs fixed binning\n if h.GetYaxis().GetXbins().GetSize() > 0:\n ybinning = (h.GetNbinsY(),h.GetYaxis().GetXbins())\n else:\n ybinning = (h.GetNbinsY(),h.GetYaxis().GetXmin(),h.GetYaxis().GetXmax())\n zbinning = ()\n dimension = 2\n # Check if 3D\n elif isinstance(h,ROOT.TH3):\n # Y variable vs fixed binning\n if h.GetYaxis().GetXbins().GetSize() > 0:\n ybinning = (h.GetNbinsY(),h.GetYaxis().GetXbins())\n else:\n ybinning = (h.GetNbinsY(),h.GetYaxis().GetXmin(),h.GetYaxis().GetXmax())\n # Z variable vs fixed binning\n if h.GetZaxis().GetXbins().GetSize() > 0:\n zbinning = (h.GetNbinsZ(),h.GetZaxis().GetXbins())\n else:\n zbinning = (h.GetNbinsZ(),h.GetZaxis().GetXmin(),h.GetZaxis().GetXmax())\n dimension = 3\n\n return xbinning + ybinning + zbinning, dimension\n\ndef colliMate(myString,width=18):\n sub_strings = myString.split(' ')\n new_string = ''\n for i,sub_string in enumerate(sub_strings):\n string_length = len(sub_string)\n n_spaces = width - string_length\n if i != len(sub_strings)-1:\n if n_spaces <= 0:\n n_spaces = 2\n new_string += sub_string + ' '*n_spaces\n else:\n new_string += sub_string\n return new_string\n\ndef dictStructureCopy(inDict):\n newDict = {}\n for k1,v1 in inDict.items():\n if type(v1) == dict:\n newDict[k1] = dictStructureCopy(v1)\n else:\n newDict[k1] = 0\n return newDict\n\ndef dictCopy(inDict):\n newDict = {}\n for k1,v1 in inDict.items():\n if type(v1) == dict:\n newDict[k1] = dictCopy(v1)\n else:\n newDict[k1] = v1\n return newDict\n\ndef executeCmd(cmd,dryrun=False):\n print('Executing: '+cmd)\n if not dryrun:\n subprocess.call([cmd],shell=True)\n\ndef dictToLatexTable(dict2convert,outfilename,roworder=[],columnorder=[]):\n # First set of keys are row, second are column\n if len(roworder) == 0:\n rows = sorted(dict2convert.keys())\n else:\n rows = roworder\n if len(columnorder) == 0:\n columns = []\n for r in rows:\n thesecolumns = dict2convert[r].keys()\n for c in thesecolumns:\n if c not in columns:\n columns.append(c)\n columns.sort()\n else:\n columns = columnorder\n\n latexout = open(outfilename,'w')\n latexout.write('\\\\begin{table}[] \\n')\n latexout.write('\\\\begin{tabular}{|c|'+len(columns)*'c'+'|} \\n')\n latexout.write('\\\\hline \\n')\n\n column_string = ' &'\n for c in columns:\n column_string += str(c)+'\\t& '\n column_string = column_string[:-2]+'\\\\\\ \\n'\n latexout.write(column_string)\n\n latexout.write('\\\\hline \\n')\n for r in rows:\n row_string = '\\t'+r+'\\t& '\n for c in columns:\n if c in dict2convert[r].keys():\n row_string += str(dict2convert[r][c])+'\\t& '\n else:\n row_string += '- \\t& '\n row_string = row_string[:-2]+'\\\\\\ \\n'\n latexout.write(row_string)\n\n latexout.write('\\\\hline \\n')\n latexout.write('\\\\end{tabular} \\n')\n latexout.write('\\\\end{table}')\n latexout.close()\n\ndef easyPlot(name, tag, histlist, bkglist=[],signals=[],colors=[],titles=[],logy=False,rootfile=False,xtitle='',ytitle='',dataOff=False,datastyle='pe'): \n # histlist is just the generic list but if bkglist is specified (non-empty)\n # then this function will stack the backgrounds and compare against histlist as if \n # it is data. The important bit is that bkglist is a list of lists. The first index\n # of bkglist corresponds to the index in histlist (the corresponding data). \n # For example you could have:\n # histlist = [data1, data2]\n # bkglist = [[bkg1_1,bkg2_1],[bkg1_2,bkg2_2]]\n\n if len(histlist) == 1:\n width = 800\n height = 700\n padx = 1\n pady = 1\n elif len(histlist) == 2:\n width = 1200\n height = 700\n padx = 2\n pady = 1\n elif len(histlist) == 3:\n width = 1600\n height = 700\n padx = 3\n pady = 1\n elif len(histlist) == 4:\n width = 1200\n height = 1000\n padx = 2\n pady = 2\n elif len(histlist) == 6 or len(histlist) == 5:\n width = 1600\n height = 1000\n padx = 3\n pady = 2\n else:\n raise ValueError('histlist of size ' + str(len(histlist)) + ' not currently supported')\n\n tdrstyle.setTDRStyle()\n\n myCan = TCanvas(name,name,width,height)\n myCan.Divide(padx,pady)\n\n # Just some colors that I think work well together and a bunch of empty lists for storage if needed\n default_colors = [kRed,kMagenta,kGreen,kCyan,kBlue]\n if len(colors) == 0: \n colors = default_colors\n stacks = []\n tot_hists = []\n legends = []\n mains = []\n subs = []\n pulls = []\n logString = ''\n\n # For each hist/data distribution\n for hist_index, hist in enumerate(histlist):\n # Grab the pad we want to draw in\n myCan.cd(hist_index+1)\n # if len(histlist) > 1:\n thisPad = myCan.GetPrimitive(name+'_'+str(hist_index+1))\n thisPad.cd()\n\n # If this is a TH2, just draw the lego\n if hist.ClassName().find('TH2') != -1:\n if logy == True:\n gPad.SetLogy()\n gPad.SetLeftMargin(0.2)\n hist.GetXaxis().SetTitle(xtitle)\n hist.GetYaxis().SetTitle(ytitle)\n hist.GetXaxis().SetTitleOffset(1.5)\n hist.GetYaxis().SetTitleOffset(2.3)\n hist.GetZaxis().SetTitleOffset(1.8)\n if len(titles) > 0:\n hist.SetTitle(titles[hist_index])\n\n hist.Draw('lego')\n if len(bkglist) > 0:\n print('ERROR: It seems you are trying to plot backgrounds with data on a 2D plot. This is not supported since there is no good way to view this type of distribution.')\n \n # Otherwise it's a TH1 hopefully\n else:\n alpha = 1\n if dataOff:\n alpha = 0\n hist.SetLineColorAlpha(kBlack,alpha)\n if 'pe' in datastyle.lower():\n hist.SetMarkerColorAlpha(kBlack,alpha)\n hist.SetMarkerStyle(8)\n if 'hist' in datastyle.lower():\n hist.SetFillColorAlpha(0,0)\n \n # If there are no backgrounds, only plot the data (semilog if desired)\n if len(bkglist) == 0:\n hist.GetXaxis().SetTitle(xtitle)\n hist.GetYaxis().SetTitle(ytitle)\n if len(titles) > 0:\n hist.SetTitle(titles[hist_index])\n hist.Draw(datastyle)\n \n # Otherwise...\n else:\n # Create some subpads, a legend, a stack, and a total bkg hist that we'll use for the error bars\n if not dataOff:\n mains.append(TPad(hist.GetName()+'_main',hist.GetName()+'_main',0, 0.3, 1, 1))\n subs.append(TPad(hist.GetName()+'_sub',hist.GetName()+'_sub',0, 0, 1, 0.3))\n\n else:\n mains.append(TPad(hist.GetName()+'_main',hist.GetName()+'_main',0, 0.1, 1, 1))\n subs.append(TPad(hist.GetName()+'_sub',hist.GetName()+'_sub',0, 0, 0, 0))\n\n legends.append(TLegend(0.65,0.6,0.95,0.93))\n stacks.append(THStack(hist.GetName()+'_stack',hist.GetName()+'_stack'))\n tot_hist = hist.Clone(hist.GetName()+'_tot')\n tot_hist.Reset()\n tot_hist.SetTitle(hist.GetName()+'_tot')\n tot_hist.SetMarkerStyle(0)\n tot_hists.append(tot_hist)\n\n\n # Set margins and make these two pads primitives of the division, thisPad\n mains[hist_index].SetBottomMargin(0.0)\n mains[hist_index].SetLeftMargin(0.16)\n mains[hist_index].SetRightMargin(0.05)\n mains[hist_index].SetTopMargin(0.1)\n\n subs[hist_index].SetLeftMargin(0.16)\n subs[hist_index].SetRightMargin(0.05)\n subs[hist_index].SetTopMargin(0)\n subs[hist_index].SetBottomMargin(0.3)\n mains[hist_index].Draw()\n subs[hist_index].Draw()\n\n # Build the stack\n for bkg_index,bkg in enumerate(bkglist[hist_index]): # Won't loop if bkglist is empty\n # bkg.Sumw2()\n tot_hists[hist_index].Add(bkg)\n bkg.SetLineColor(kBlack)\n if logy:\n bkg.SetMinimum(1e-3)\n\n if bkg.GetName().find('qcd') != -1:\n bkg.SetFillColor(kYellow)\n\n else:\n if colors[bkg_index] != None:\n bkg.SetFillColor(colors[bkg_index])\n else:\n bkg.SetFillColor(default_colors[bkg_index])\n\n stacks[hist_index].Add(bkg)\n\n legends[hist_index].AddEntry(bkg,bkg.GetName().split('_')[0],'f')\n \n # Go to main pad, set logy if needed\n mains[hist_index].cd()\n\n # Set y max of all hists to be the same to accomodate the tallest\n histList = [stacks[hist_index],tot_hists[hist_index],hist]\n\n yMax = histList[0].GetMaximum()\n maxHist = histList[0]\n for h in range(1,len(histList)):\n if histList[h].GetMaximum() > yMax:\n yMax = histList[h].GetMaximum()\n maxHist = histList[h]\n for h in histList:\n h.SetMaximum(yMax*1.1)\n if logy == True:\n h.SetMaximum(yMax*10)\n\n \n mLS = 0.06\n # Now draw the main pad\n data_leg_title = hist.GetTitle()\n if len(titles) > 0:\n hist.SetTitle(titles[hist_index])\n hist.SetTitleOffset(1.5,\"xy\")\n hist.GetYaxis().SetTitle('Events')\n hist.GetYaxis().SetLabelSize(mLS)\n hist.GetYaxis().SetTitleSize(mLS)\n if logy == True:\n hist.SetMinimum(1e-3)\n hist.Draw(datastyle)\n\n stacks[hist_index].Draw('same hist')\n\n # Do the signals\n if len(signals) > 0: \n signals[hist_index].SetLineColor(kBlue)\n signals[hist_index].SetLineWidth(2)\n if logy == True:\n signals[hist_index].SetMinimum(1e-3)\n legends[hist_index].AddEntry(signals[hist_index],signals[hist_index].GetName().split('_')[0],'L')\n signals[hist_index].Draw('hist same')\n\n tot_hists[hist_index].SetFillColor(kBlack)\n tot_hists[hist_index].SetFillStyle(3354)\n\n tot_hists[hist_index].Draw('e2 same')\n # legends[hist_index].Draw()\n\n if not dataOff:\n legends[hist_index].AddEntry(hist,'data',datastyle)\n hist.Draw(datastyle+' same')\n\n gPad.RedrawAxis()\n\n # Draw the pull\n subs[hist_index].cd()\n # Build the pull\n pulls.append(Make_Pull_plot(hist,tot_hists[hist_index]))\n pulls[hist_index].SetFillColor(kBlue)\n pulls[hist_index].SetTitle(\";\"+hist.GetXaxis().GetTitle()+\";(Data-Bkg)/#sigma\")\n pulls[hist_index].SetStats(0)\n\n LS = .13\n\n pulls[hist_index].GetYaxis().SetRangeUser(-2.9,2.9)\n pulls[hist_index].GetYaxis().SetTitleOffset(0.4)\n pulls[hist_index].GetXaxis().SetTitleOffset(0.9)\n \n pulls[hist_index].GetYaxis().SetLabelSize(LS)\n pulls[hist_index].GetYaxis().SetTitleSize(LS)\n pulls[hist_index].GetYaxis().SetNdivisions(306)\n pulls[hist_index].GetXaxis().SetLabelSize(LS)\n pulls[hist_index].GetXaxis().SetTitleSize(LS)\n\n pulls[hist_index].GetXaxis().SetTitle(xtitle)\n pulls[hist_index].GetYaxis().SetTitle(\"(Data-Bkg)/#sigma\")\n pulls[hist_index].Draw('hist')\n\n if logy == True:\n mains[hist_index].SetLogy()\n\n CMS_lumi.CMS_lumi(thisPad, 4, 11)\n\n if rootfile:\n myCan.Print(tag+'plots/'+name+'.root','root')\n else:\n myCan.Print(tag+'plots/'+name+'.png','png')\n\ndef findCommonString(string_list):\n to_match = '' # initialize the string we're looking for/building\n for s in string_list[0]: # for each character in the first string\n passed = True\n for istring in range(1,len(string_list)): # compare to_match+s against strings in string_list\n string = string_list[istring]\n if to_match not in string: # if in the string, add more\n passed = False\n \n if passed == True:\n to_match+=s\n\n if to_match[-2] == '_':\n return to_match[:-2] \n else:\n return to_match[:-1] # if not, return to_match minus final character\n\n return to_match[:-2]\n \ndef makePullPlot( DATA,BKG):\n BKGUP, BKGDOWN = Make_up_down(BKG)\n pull = DATA.Clone(DATA.GetName()+\"_pull\")\n pull.Add(BKG,-1)\n sigma = 0.0\n FScont = 0.0\n BKGcont = 0.0\n for ibin in range(1,pull.GetNbinsX()+1):\n FScont = DATA.GetBinContent(ibin)\n BKGcont = BKG.GetBinContent(ibin)\n if FScont>=BKGcont:\n FSerr = DATA.GetBinErrorLow(ibin)\n BKGerr = abs(BKGUP.GetBinContent(ibin)-BKG.GetBinContent(ibin))\n if FScont= 2:\n r = q % 2\n binary += str(r)\n q = q // 2\n if q < 2:\n if q != 0:\n binary += str(q)\n\n return binary[::-1]\n\n\ndef solution(s):\n binary_convert_cnt = 0\n delete_zero_cnt = 0\n\n while True:\n new_s = []\n binary_convert_cnt += 1\n for one_ch in s:\n if one_ch == \"0\":\n delete_zero_cnt += 1\n else:\n new_s.append(s)\n length = len(new_s)\n converted = get_binary(length)\n\n if converted == \"1\":\n break\n s = converted\n\n answer = [binary_convert_cnt, delete_zero_cnt]\n\n return answer\n","sub_path":"Programmers/monthly/repeat_binary_conversion.py","file_name":"repeat_binary_conversion.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"365308731","text":"from bs4 import BeautifulSoup\nimport re\n\ndef parse_ram(html_data):\n car_type = None\n car_size = None\n monthly_price_type = None\n car_info = {}\n name = None\n msrp = None\n city_mpg = None\n hwy_mpg = None\n car_type_dict = {\n \"suv\":[],\n \"truck\":[\"1500\",\"2500\",\"3500\"],\n }\n car_size_dict = {\n \"mid-size\":[\"1500\"],\n \"large\":[\"2500\",\"3500\"],\n }\n #skip 1st line\n for line in html_data:\n\n if line.find('city_mpg') == 0:\n tmp_mpg = line.split('=')\n city_mpg = float(tmp_mpg[1].strip())\n continue\n elif line.find('hwy_mpg') == 0:\n tmp_mpg2 = line.split('=')\n hwy_mpg = float(tmp_mpg2[1].strip())\n continue\n elif line.find('range') == 0:\n tmp_range = line.split('=')\n range = float(tmp_range[1].strip())\n continue\n elif line.find('charge_time') == 0:\n tmp_chtime = line.split('=')\n charge_time = float(tmp_chtime[1].strip())\n continue\n\n soup = BeautifulSoup(line,'lxml')\n\n span = soup.find('span')\n if span != None:\n# print span.attrs\n if 'class' in span.attrs:\n if span.attrs['class']== ['msrp-amount']:\n msrp = int(span.text)\n continue\n else:\n tmp_str = span.text.split('Ram')\n year = int(tmp_str[0].strip())\n name = tmp_str[1].strip()\n# print year, name \n\n #out of for line loop\n #figure out car type and size for this car\n for type_tmp in car_type_dict.keys():\n if name in car_type_dict[type_tmp]:\n car_type = type_tmp\n break\n for size_tmp in car_size_dict.keys():\n for item in car_size_dict[size_tmp]:\n if name in item:\n car_size = size_tmp\n break\n\n car_info['name'] = name\n car_info['type'] = car_type\n car_info['size'] = car_size\n car_info['year'] = year\n if msrp != None:\n car_info['msrp_from'] = msrp\n if city_mpg != None:\n car_info['city_mpg'] = city_mpg\n if hwy_mpg != None:\n car_info['hwy_mpg'] = hwy_mpg\n if monthly_price_type == 'lease':\n car_info['lease'] = monthly_price_value\n car_info['leasing_months'] = leasing_months\n car_info['due_at_signing'] = due_at_signing\n if monthly_price_type == 'financing':\n car_info['financing'] = monthly_price_value\n if car_type == 'ev':\n car_info['range'] = range\n car_info['charge_time'] = charge_time\n\n return (car_info)\n\n","sub_path":"libwhichv/libwhichv_ram.py","file_name":"libwhichv_ram.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"124769848","text":"import tensorflow as tf\nimport tensorflow_datasets as tfds\n\nimport torch\nimport torchvision\nimport torch.optim as optim\n\nimport numpy as np\n\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.utils.data import Dataset, TensorDataset, DataLoader\n\nbatch_size = int(1e2)\n\ntry:\n device = torch.device('cuda:0')\nexcept:\n device = torch.device('cpu')\n \ndef reset_weights(model):\n \n #Function: reset_weights\n #Input: model (Pytorch Model)\n #Process: resets model weights\n #Example: model.apply(DAL.reset_weights)\n #Output: none\n \n if isinstance(model, nn.Conv2d) or isinstance(model, nn.Linear) or isinstance(model, nn.BatchNorm2d):\n model.reset_parameters()\n \ndef create_data_loader(images,labels):\n \n #Function: create_data_loader\n #Input: images (Pytorch Tensor), \n # labels (Pytorch Tensor)\n #Process: Creates dataloader\n #Example: data_loader = create_data_loader(images,labels)\n #Output: data_loader (Pytorch dataloader)\n \n dataset = TensorDataset(images, labels)\n data_loader = DataLoader(dataset, batch_size=batch_size)\n \n return data_loader\n\ndef train_step(net,train_loader,test_loader,criterion,optimizer):\n \n #Function: train_step\n #Input: net (Pytorch Model), \n # train_loader (Pytorch dataloader)\n # test_loader (Pytorch dataloader)\n # criterion (Pytorch loss function)\n # optimizer (Pytorch optimizer)\n #Process: training step\n #Example: loss = train_step(net,train_loader,test_loader,criterion,optimizer)\n #Output: np.mean(loss_array) (numpy value)\n \n loss_array = []\n accuracy_array = []\n \n net.train()\n \n for i,data in enumerate(train_loader):\n \n image,label = data\n \n optimizer.zero_grad()\n\n out = net(image.to(device))\n loss = criterion(out,label.long().to(device))\n loss.backward()\n\n optimizer.step()\n \n loss_array.append(loss.item())\n \n return np.mean(loss_array)\n \ndef train(net,train_loader,test_loader,criterion,optimizer):\n\n #Function: train\n #Input: net (Pytorch Model), \n # train_loader (Pytorch dataloader)\n # test_loader (Pytorch dataloader)\n # criterion (Pytorch loss function)\n # optimizer (Pytorch optimizer)\n #Process: training process\n #Example: loss_array = train(net,train_loader,test_loader,criterion,optimizer)\n #Output: loss_array (list)\n \n numIters = 25\n loss_array = []\n\n for epoch in range(numIters):\n\n loss = train_step(net,train_loader,test_loader,criterion,optimizer)\n loss_array.append(loss)\n \n return loss_array\n\ndef check_accuracy(net,test_loader):\n \n #Function: check_accuracy\n #Input: net (Pytorch Model), \n # test_loader (Pytorch dataloader)\n #Process: check network accuracy\n #Example: loss_array = check_accuracy(net,test_loader)\n #Output: np.mean(accuracy_array) (numpy value)\n \n accuracy_array = []\n \n net.eval()\n \n for i,data in enumerate(test_loader):\n \n image,label = data\n \n out = net(image.to(device))\n accuracy = (out.max(1)[1].cpu()==label).sum()/float(len(label))*100.0\n \n accuracy_array.append(accuracy.item())\n \n return np.mean(accuracy_array)\n\nclass Node():\n \n #Class: Node\n #Input: net (Pytorch Model), \n # data_points (numpy array)\n # images (Pytorch Tensor)\n # labels (Pytorch Tensor)\n #Value: node within network\n \n def __init__(self,data_points,images,labels):\n \n self.data_points = data_points\n \n self.images = images\n self.labels = labels\n \n self.used_points = []\n \n def add_used_point(self,point):\n \n for ii in range(len(point)):\n if point[ii] in self.data_points and point[ii] not in self.used_points:\n self.used_points.append(point[ii])\n \n def reset_used_point(self):\n \n self.used_points = []\n \nclass Node_Network():\n \n #Class: Node_Network\n #Input: num_nodes (integer)\n # train_images (Pytorch Tensor)\n # train_labels (Pytorch Tensor)\n # dim_out (integer)\n #Value: network with nodes and hub\n \n def __init__(self,num_nodes,train_images,train_labels,dim_out):\n \n self.num_nodes = num_nodes-1\n self.num_examples = int(5e4)//num_nodes\n self.distribution = np.random.randint(int(5e4),size = (self.num_examples,num_nodes))\n \n self.node = []\n self.dim_out = dim_out\n \n self.alpha_hub = np.zeros([self.num_examples,self.dim_out])\n self.alpha_node = np.zeros([self.num_nodes,self.num_examples,self.dim_out])\n\n for n in range(self.num_nodes):\n \n r = self.distribution[:,n]\n \n images = train_images[r,:,:,:]\n labels = train_labels[r]\n \n self.node.append(Node(r,images,labels))\n \n r = self.distribution[:,n+1]\n \n images = train_images[r,:,:,:]\n labels = train_labels[r]\n\n self.hub = Node(r,images,labels)\n \n self.images = train_images\n self.labels = train_labels\n \n def compression(self,net):\n \n self.alpha_values = torch.zeros([int(5e4),self.dim_out])\n \n for node_ii in range(self.num_nodes): \n data_points = torch.Tensor(self.node[node_ii].data_points).long()\n image = self.images[data_points,:,:,:]\n \n self.alpha_values[data_points,:] = net(image.to(device)).cpu().detach()\n\n data_points = torch.Tensor(self.hub.data_points).long()\n image = self.images[data_points,:,:,:]\n\n self.alpha_values[data_points,:] = net(image.to(device)).cpu().detach() \n \n def reset_data_points(self):\n \n for n in range(self.num_nodes):\n \n self.node[n].reset_used_point()\n \nclass Data_Optimizer():\n \n #Class: Data_Optimizer\n #Input: network (Node_Network object)\n # iterations (integer)\n #Value: optimizer for data selection from nodes\n \n def __init__(self,network,iterations):\n \n self.network = network\n\n self.w = torch.randn([int(5e4),1],requires_grad=False)\n \n self.x = torch.randn([int(5e4),1],requires_grad=True)\n self.y = torch.randn([int(5e4),1],requires_grad=False)\n self.s = torch.randn([int(5e4),1],requires_grad=False)\n\n self.theta = 1\n self.lambda_val = 10\n \n self.iterations = iterations\n self.optimizer = optim.SGD([self.x],lr=1e-2,weight_decay=0)\n \n self.removed_points = torch.Tensor([]).long()\n \n def update_values(self,network):\n \n self.A = torch.matmul((self.network.alpha_values - self.network.alpha_values.mean(0)),((self.network.alpha_values - self.network.alpha_values.mean(0))).transpose(0,1))\n self.P = (self.theta*torch.eye(int(5e4)) + self.A)#.to(device)\n \n def Lagrangian(self):\n \n f = - torch.norm(torch.matmul(torch.sigmoid(self.x).transpose(0,1),(self.network.alpha_values - self.network.alpha_values.mean(0))))\n g = self.lambda_val*torch.norm(self.y,1)\n \n C = (self.theta/2)*torch.norm(self.x-self.y+self.s,2) - (self.theta/2)*torch.norm(self.s,2)\n \n return f + g + C\n\n def optimize(self):\n \n for k in range(self.iterations):\n \n Loss = self.Lagrangian()\n \n Loss.backward()\n self.optimizer.step()\n \n with torch.no_grad():\n\n self.y = F.softshrink((self.theta/self.lambda_val)*(self.x+self.s),(self.theta/self.lambda_val))\n self.s = self.s + (self.x - self.y)\n \n if torch.norm(self.x - self.y) < float(1e-8):\n break\n \n Loss = self.Lagrangian()\n \n self.w = self.x\n \n def select_points(self):\n \n chosen_points = torch.zeros([self.network.num_nodes]).long()\n \n W = self.w.squeeze()\n W = W.detach()\n \n if len(self.removed_points) > 0:\n W[self.removed_points] = - int(1e8)*torch.ones([len(self.removed_points)])\n \n for ii in range(self.network.num_nodes):\n chosen_points[ii] = (W[self.network.num_examples*(ii):self.network.num_examples*(ii+1)].argmax()+self.network.num_examples*(ii)).long()\n \n self.removed_points = torch.cat((self.removed_points,chosen_points),0)\n \n return chosen_points\n \ndef grab_examples(network,data_selector,hub_images,hub_labels,num_examples_increase):\n\n #Function: grab_examples_random\n #Input: network (Node_Network Object), \n # hub_images (Pytorch Tensor)\n # hub_labels (Pytorch Tensor)\n #Process: gives chosen examples from each node based on Data_Optimizer\n #Example: hub_images,hub_labels = grab_examples_random(network,hub_images,hub_labels,random_points)\n #Output: hub_images (Pytorch Tensor)\n # hub_labels (Pytorch Tensor)\n \n new_images = torch.zeros([network.num_nodes,3,32,32])\n new_labels = torch.zeros([network.num_nodes])\n \n data_selector.update_values(network)\n data_selector.optimize()\n \n new_alpha = torch.Tensor([])\n var_image = torch.Tensor([])\n \n for ii in range(num_examples_increase):\n \n selected_points = data_selector.select_points()\n\n new_images = network.images[selected_points,:,:,:]\n new_labels = network.labels[selected_points]\n \n hub_images,hub_labels = add_points_to_hub(hub_images,hub_labels,new_images,new_labels)\n\n for n in range(network.num_nodes):\n\n network.node[n].add_used_point(selected_points)\n \n return hub_images,hub_labels\n\ndef grab_examples_random(network,hub_images,hub_labels,random_points):\n\n #Function: grab_examples_random\n #Input: network (Node_Network Object), \n # hub_images (Pytorch Tensor)\n # hub_labels (Pytorch Tensor)\n # random_points (numpy array)\n #Process: gives random examples from each node\n #Example: hub_images,hub_labels = grab_examples_random(network,hub_images,hub_labels,random_points)\n #Output: hub_images (Pytorch Tensor)\n # hub_labels (Pytorch Tensor)\n \n new_images = torch.zeros([network.num_nodes,3,32,32])\n new_labels = torch.zeros([network.num_nodes])\n \n new_images = network.images[random_points,:,:,:]\n new_labels = network.labels[random_points]\n \n hub_images,hub_labels = add_points_to_hub(hub_images,hub_labels,new_images,new_labels)\n \n return hub_images,hub_labels\n\ndef add_points_to_hub(current_images,current_labels,new_images,new_labels):\n \n #Function: add_points_to_hub\n #Input: current_images (Pytorch Tensor)\n # current_labels (Pytorch Tensor)\n # new_images (Pytorch Tensor)\n # new_labels (Pytorch Tensor)\n #Process: concatenates two tensors\n #Example: hub_images,hub_labels = add_points_to_hub(current_images,current_labels,new_images,new_labels)\n #Output: hub_images (Pytorch Tensor)\n # hub_labels (Pytorch Tensor)\n \n hub_images = torch.zeros([len(current_labels)+len(new_labels),3,32,32])\n hub_labels = torch.zeros([len(current_labels)+len(new_labels)])\n \n hub_images[:len(current_labels),:,:,:] = current_images\n hub_images[len(current_labels):,:,:,:] = new_images\n \n hub_labels[:len(current_labels)] = current_labels\n hub_labels[len(current_labels):] = new_labels\n \n return hub_images,hub_labels\n\ndef train_model(net,hub_images,hub_labels,test_loader,criterion,optimizer):\n \n #Function: train_model\n #Input: net (Pytorch Model)\n # hub_images (Pytorch Tensor)\n # hub_labels (Pytorch Tensor)\n # test_loader (Pytorch dataloader)\n # criterion (Pytorch loss function)\n # optimizer (Pytorch optimizer)\n #Process: trains model\n #Example: train_model(net,hub_images,hub_labels,test_loader,criterion,optimizer)\n #Output: none\n \n torch.save(net.state_dict(), r'untrain_model.pt')\n \n hub_loader = create_data_loader(hub_images,hub_labels)\n loss = train(net,hub_loader,test_loader,criterion,optimizer)\n \n torch.save(net.state_dict(), r'train_model.pt')\n \ndef run_test(net,data_selector,test_loader,criterion,optimizer,iterations,num_examples_increase,network,hub_images,hub_labels):\n\n #Function: run_test\n #Input: net (Pytorch Model)\n # data_selector (Data_Optimizer Object)\n # test_loader (Pytorch dataloader)\n # criterion (Pytorch loss function)\n # optimizer (Pytorch optimizer)\n # iterations (integer)\n # num_examples_increase (integer)\n # network (Node_Network object)\n # hub_images (Pytorch Tensor)\n # hub_labels (Pytorch Tensor)\n #Process: runs test with Data_Optimizer Object\n #Example: loss_array,accuracy_array = run_test(net,iterations,num_examples_increase,network,hub_images,hub_labels)\n #Output: loss_array (numpy array)\n # accuracy_array (numpy array)\n \n loss_array = []\n accuracy_array = []\n alpha_array = torch.Tensor([])\n var_img_array = torch.Tensor([])\n\n for iter_num in range(iterations):\n\n hub_loader = create_data_loader(hub_images,hub_labels)\n\n net.load_state_dict(torch.load(r'untrain_model.pt'))\n network.compression(net)\n net.load_state_dict(torch.load(r'train_model.pt'))\n\n accuracy = check_accuracy(net,test_loader)\n accuracy_array.append(accuracy)\n\n hub_images,hub_labels = grab_examples(network,data_selector,hub_images,hub_labels,num_examples_increase)\n\n net.load_state_dict(torch.load(r'untrain_model.pt'))\n \n hub_loader = create_data_loader(hub_images,hub_labels)\n alpha_array = output_alpha(net,hub_loader,hub_labels)\n var_img_array = hub_images.reshape(-1,3*32*32).var(0)\n \n loss = train(net,hub_loader,test_loader,criterion,optimizer)\n network.compression(net)\n\n loss_array.append(loss[len(loss)-1])\n\n accuracy = check_accuracy(net,test_loader)\n accuracy_array.append(accuracy)\n \n print('---------------------------------Optimization Output Final---------------------------------')\n print()\n print()\n print('Loss: ' + str(round(loss[len(loss)-1],2)))\n print('Accuracy: ' + str(accuracy))\n print()\n print()\n\n return loss_array,accuracy_array,alpha_array,var_img_array\n\ndef sample_random_points(network,iterations,num_examples_increase):\n\n #Function: sample_random_points\n #Input: network (Node_Network object)\n # iterations (integer)\n # num_examples_increase (integer)\n #Process: creates random sampling schedule for each of the nodes\n #Example: random_list = sample_random_points(network,iterations,num_examples_increase)\n #Output: random_list (numpy array)\n \n random_list = np.zeros([network.num_nodes,num_examples_increase,iterations])\n\n for n in range(network.num_nodes):\n\n r = network.node[n].data_points\n np.random.shuffle(r)\n\n num = 0\n\n for ee in range(num_examples_increase):\n for ii in range(iterations):\n\n random_list[n,ee,ii] = r[num]\n\n num += 1\n \n return random_list\n\ndef output_alpha(net,hub_loader,hub_labels):\n \n #Function: sample_random_points\n #Input: network (Node_Network object)\n # iterations (integer)\n # num_examples_increase (integer)\n #Process: creates random sampling schedule for each of the nodes\n #Example: random_list = sample_random_points(network,iterations,num_examples_increase)\n #Output: random_list (numpy array)\n \n alpha_values = torch.zeros(len(hub_labels),10)\n \n net.eval()\n \n n = 0\n for i,data in enumerate(hub_loader):\n image,label = data\n out = net(image.to(device)).detach().cpu()\n for ii in range(len(out)):\n alpha_values[n,:] = out[ii,:]\n n += 1\n \n return alpha_values\n \ndef run_test_random(net,test_loader,criterion,optimizer,iterations,num_examples_increase,network,hub_images,hub_labels,random_list):\n\n #Function: run_test_random\n #Input: net (Pytorch Model)\n # test_loader (Pytorch dataloader)\n # test_loader (Pytorch dataloader)\n # criterion (Pytorch loss function)\n # optimizer (Pytorch optimizer)\n # iterations (integer)\n # num_examples_increase (integer)\n # network (Node_Network object)\n # hub_images (Pytorch Tensor)\n # hub_labels (Pytorch Tensor)\n # random_list (numpy array)\n #Process: runs test with random sampling\n #Example: loss_array,accuracy_array = run_test_random(net,test_loader,criterion,optimizer,iterations,num_examples_increase,network,hub_images,hub_labels,random_list)\n #Output: loss_array (numpy array)\n # accuracy_array (numpy array)\n \n loss_array = []\n accuracy_array = []\n \n for iter_num in range(iterations):\n\n hub_loader = create_data_loader(hub_images,hub_labels)\n\n net.load_state_dict(torch.load(r'untrain_model.pt'))\n network.compression(net)\n net.load_state_dict(torch.load(r'train_model.pt'))\n \n accuracy = check_accuracy(net,test_loader)\n accuracy_array.append(accuracy)\n\n for i in range(num_examples_increase):\n r = random_list[:,i,iter_num]\n hub_images,hub_labels = grab_examples_random(network,hub_images,hub_labels,r)\n \n net.load_state_dict(torch.load(r'untrain_model.pt'))\n \n hub_loader = create_data_loader(hub_images,hub_labels)\n alpha_array = output_alpha(net,hub_loader,hub_labels)\n var_img_array = hub_images.reshape(-1,3*32*32).var(0)\n \n loss = train(net,hub_loader,test_loader,criterion,optimizer)\n network.compression(net)\n\n loss_array.append(loss[len(loss)-1])\n\n accuracy = check_accuracy(net,test_loader)\n accuracy_array.append(accuracy)\n\n print('---------------------------------Random Output Final---------------------------------')\n print()\n print()\n print('Loss: ' + str(round(loss[len(loss)-1],2)))\n print('Accuracy: ' + str(accuracy))\n print()\n print()\n\n return loss_array,accuracy_array,alpha_array,var_img_array\n","sub_path":"DAL.py","file_name":"DAL.py","file_ext":"py","file_size_in_byte":19125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"642982564","text":"import requests\nimport re\n\nfrom lxml import etree\nimport pymysql\n\nurl = \"http://192.168.2.15:7090/api/v2/users/signin\"\n\ns = requests.session()\nuser = 'chen.chen@ptmind.com'\npsw = 'e10adc3949ba59abbe56e057f20f883e'\n\ndef login(s, user, psw):\n '''登录'''\n r = requests.get(url)\n # re 知道前面和后面,取中间值\n waretoken = \"\"\n # try:\n # token = re.findall('name=\"csrfmiddlewaretokenxx\" value=\"(.+?)\"', r.text)\n # print(\"获取到登录页面token:%s\" % token[0])\n # waretoken = token[0]\n # except:\n # print(\"获取页面token失败\")\n # waretoken = \"\"\n\n body = {\n \"rememberMe\": True,\n \"userEmail\": user,\n \"userPassword\": psw\n }\n r2 = s.post(url, data=body)\n if \"登录成功\" in r2.text:\n print(\"登录成功!\")\n else:\n print(\"登录失败,检查账号密码!\")\n return r2.text\n\ndef is_login_sucess(t):\n result = False # 立 flag\n if \"登录成功\" in t:\n result = True\n return result\n\nif __name__ == \"__main__\":\n r = login(s, user, psw)\n print(r)\n res = is_login_sucess(r)\n print(res)\n","sub_path":"APITestProject/cases/test_login.py","file_name":"test_login.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"195180230","text":"## Python SCRIPT: EmployeeDiscovery.py\n## \n## Description: Sample Code Python Tutorial - LocalFile\n## \n## \n## Parameters : None\n##\n## License: \n##\n## Repository: \n## \n## Documentation: In the code\n\n##\n##\n## Date\t\t\t\t Developer\t\t \tAction\n## ---------------------------------------------------------------------\n## Jan 15, 2019 \t\tSteve Young\t\t\tInital development \n## \n## \n## \n## \n## \n\n\n#%%\nimport matplotlib.pyplot as plt\nimport numpy as nump\n\nx = [3,4,6,3,4,3,8,9,7,8,] # Create a list of numbers\nplt.plot(x) # Plot the sine of each x point\nplt.show() # Display the plot\n \n#%%\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as pp\n\n\n\n#%%\nEmployees = pd.read_csv(r'C:\\Users\\steveyoung\\Documents\\GitHub\\PythonTutorial\\Excel_PowerBI_StarterDataSet_2019_Mini_v1.csv')\n\n#%%\n#Clean UP\n\nEmployees_trimmed = Employees.apply(lambda x: x.str.strip() if x.dtype == \"object\" else x)\n\n\n#%%\n#give me a good description and initial analysis of my data\nEmployees.describe()\nEmployees.columns\n#%%\n#distribution \nEmployees['GrossPay'].hist(bins=50)\nEmployees.boxplot(column='GrossPay')\nEmployees.boxplot(column='GrossPay', by = 'MaritalStatus')\nEmployees.boxplot(column='GrossPay', by = 'Gender')\n\n#%%\nEmployees\n\n#%%\nEmployees.index\n\n\n#%%\nEmployees.loc[0]\n\n\n#%%\nEmployees.set_index('NameFull',inplace=True)\nEmployees_trimmed.set_index('NameFull',inplace=True)\n#%%\nEmployees.loc[' Ashley Berry']\n\n#%%\nEmployees_trimmed.loc['Ashley Berry']\n#%%\nEmployees\n\n\n#%%\nEmployees.info()\n\n\n#%%\nlen(Employees)\n\n\n#%%\nEmployees.columns\n\n\n#%%\npd.to_datetime(Employees.HireDate)\n\n\n#%%\n#give me a good description and initial analysis of my data\nEmployees\n\n#%%\n#give me a good description and initial analysis of my data\nEmployees.describe()\n#%%\nEmployees['GrossPay'].hist(bins=50)\n#%%\npp.hist(Employees['GrossPay'], color = \"skyblue\", ec=\"skyblue\", bins=50, )\n\n#%%\n#loandata['ApplicantIncome'].hist(by=df['Letter'])\nEmployees['GrossPay'].plot(kind='box', figsize=[16,8])\n#%%\nEmployees.boxplot(column='GrossPay')\nEmployees.boxplot(column='GrossPay', by = 'JobTitle')\n\n\n\n\n","sub_path":"EmployeeDiscovery.py","file_name":"EmployeeDiscovery.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"169852458","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\ndef divide_subgraph(graph,n):\n subgraph = []\n node = []\n for i in range(len(graph)):\n local = []\n if i not in node:\n node.append(i)\n local.append(i)\n link = [i]\n while link:\n v = link.pop()\n for j in range(len(graph[i])):\n if graph[v][j] == 1 and j not in node:\n node.append(j)\n local.append(j)\n link.append(j)\n subgraph.append(local)\n return subgraph\n\ndef count_dis(con_mat,a,b):\n '''\n 计算邻接矩阵中任意两点的距离\n 返回-1代表两点间无通路连接\n 采用广度优先搜索(Breadth First Search)\n '''\n to_search = [a]\n finish_search = []\n dis = 0\n flag = -1\n while to_search:\n tmp = []\n for node in to_search:\n finish_search.append(node)\n cur = con_mat[node]\n for i in range(len(cur)):\n if cur[i] == 1:\n if i == b:\n dis += 1\n return dis\n if i not in finish_search and i not in to_search:\n tmp.append(i)\n dis += 1\n to_search = tmp\n return flag\n\ndef diameter(con_mat,subgraph):\n d = 0\n for i in range(len(subgraph)):\n for j in range(i+1,len(subgraph)):\n d = max(d,count_dis(con_mat,subgraph[i],subgraph[j]))\n return d\n\nwith open('/users/lyle/downloads/graph2.txt', 'r') as f:\n s = f.read()\n g = s.split()\n n = int(len(g)**0.5)\n gra = []\n for i in range(n):\n gra.append([int(x) for x in g[n*i:n*(i+1)]])\n subg = divide_subgraph(gra,n)\n if 1 not in subg[0]:\n print('can not transmit')\n else:\n at = {x:-1 for x in subg[0][1:]}\n link1 = [0]\n link2 = []\n t = 1\n a = 0\n while -1 in at.values(): #无权无向图找最短路径(传输时间),v0为原点\n if a == 0:\n v = link1.pop()\n for i in subg[0][1:]:\n if gra[v][i] == 1 and at[i] == -1:\n at[i] = t\n link2.append(i)\n if len(link1) == 0:\n t += 1\n a = 1\n else:\n v = link2.pop()\n for i in subg[0][1:]:\n if gra[v][i] == 1 and at[i] == -1:\n at[i] = t\n link1.append(i)\n if len(link2) == 0:\n t += 1\n a = 0\n print('the least time to transmit from v0 to v1 is %d' %at[1])\n if count_dis(gra,0,1) == -1:\n print('can not transmit')\n else:\n print(count_dis(gra,0,1))","sub_path":"BFS.py","file_name":"BFS.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"336489971","text":"import random\nfrom collections import Counter\n# pair/ two pair/ three of a kind/ 4 of a kind \n\n\n\nclass Card(object):\n def __init__(self, suit, val):\n self.suit = suit\n self.value = val\n\n # This will print the card!\n def show(self):\n print(\"{} of {}\".format(self.value, self.suit))\n\n\nclass Deck(object):\n def __init__(self):\n self.cards = []\n self.build()\n\n def build(self):\n for s in [\"Spades\" , \"Harts\", \"Clubs\", \"Dimands\"]:\n for v in range(1,14):\n self.cards.append(Card(s,v))\n\n def show(self):\n for c in self.cards:\n c.show()\n\n\n def shuffle(self):\n #decriment from end of list to start\n for i in range(len(self.cards)-1, 0, -1):\n #pick a random number between the first and the current index your on\n r = random.randint(0,i)\n #swaps the r (random index) with the current index\n self.cards[i], self.cards[r] = self.cards[r], self.cards[i]\n\n #this will allow you to pick the top card\n def drawCard(self):\n return self.cards.pop()\n\n# Player has a stack and cards\nclass Player(object):\n def __init__(self, name, stack):\n self.name = name\n self.hand = []\n self.stack = stack\n self.position = 0\n self.turn = False\n self.call = False\n self.fold = False\n self.bet = False\n self.allin = False\n self.check = False\n self.button = False\n self.inpos = 3\n\n\n def stacklevel(self, amount):\n self.stack = self.stack + amount \n return self.stack \n\n def draw(self, deck):\n self.hand.append(deck.drawCard())\n #this allows you to call more than one card\n return self\n\n def showHand(self):\n for card in self.hand:\n card.show()\n return self.hand\n\n def Position(self, pos):\n self.position = pos\n\n def showPosisiotn(self):\n return self.position\n \n def blindpos(self):\n return self.inpos\n \n \n\n \n \n\n\n \n\n \n\n\n# In a hand there is:\n# Players, Deal, Button and blinds, Pot, Ceck, Bet, Fold, Burn, Flop, Burn, Turn, Burn, River, Winner\nclass Rules(object):\n def __inti__(self):\n pass\n \n def hands(self):\n pass\n\n \n def consective_numbers(self,numbers_sorted):\n cur_max = 0\n max_ = 0\n cur_index = 0\n index = 0\n for number in numbers_sorted:\n if number == len(numbers_sorted):\n return max_, index\n else:\n if number == 0:\n prev = number\n else:\n if prev + 1 == number:\n cur_max += 1\n if cur_max > max_:\n max_ = cur_max\n index = number - cur_max\n cur_max = 0\n\n\n # Hands combos with only one posibility - High card (all diff), Pair, Two Pair, 4 of a kind\n # Hand combos with more - Tree of a kind(two 3 of kind)\n # - Straight(1234567) -> pick the highest 5\n # - Flush -> pick the highest values \n # - Full house -> 2 3 of a kind -> higher 3 of a kind is the 3 other is 2\n # - Straight Flush -> pick the highest \n def Ranks(self, hand, board):\n total = hand + board\n numbers = []\n suits = []\n numbers_sorted = []\n for t in total:\n numbers.append(total.val)\n suits.append(total.suit)\n #this returns a list of tuples with 1st element -> val and second how many times it shows up\n most_common_number = [number for number in Counter(numbers).most_common(2)]\n most_common_suit = [suit for suit in Counter(suits).most_common(1)]\n #this is a list o \n numbers_sorted = numbers.sort()\n # Gets no. of sequence and where they start\n number_sequence = []\n\n cons_numbs = consective_(numbers_sorted)\n \n suit_frequ = most_common_suit[0][1]\n suit_val = most_common_suit[0][0]\n num_frequ = most_common_number[0][1]\n num_val = most_common_number[0][0]\n num_frequ2 = most_common_number[1][1]\n num_val2 = most_common_number[1][0]\n \n\n\n # startements to work out best hand - start from best to worst, frst hand found return it!\n #Royal Flush\n if suit_frequ > 4 and cons_numbs[1] > 4:\n for x in range(cons_numbs[2], cons_numbs[2] + 5):\n pass\n\n #Straight Flush\n #4 ofa kind\n #Full House\n #Flush\n #Straight\n #3 of a Kind\n #2 pair\n #Pair\n #High Card\n\n def Handnames(self, rank):\n if rank == 0:\n return 'High Card'\n elif rank == 1:\n return 'One Pair'\n elif rank == 2:\n return 'Two Pair'\n elif rank == 3:\n return 'Three of a Kind'\n elif rank == 4:\n return 'Straight'\n elif rank == 5:\n return 'Flush'\n elif rank == 6:\n return 'Full House'\n elif rank == 7:\n return 'Four of a kind'\n elif rank == 8:\n return 'Straight Flush'\n else:\n return 'Role Flush'\n\n def handval(self):\n pass\n\n def betterhand(self, hand1, hand2):\n pass\n\n \n\n \n\n\n#make a list of players!\n\nclass Hand(object):\n def __inti__(self, Plaeyers):\n self.Players = Players\n self.handId = 0\n self.button = 0\n self.BB = 1\n self.SM = 2\n self.pot = pot\n self.flop = flop\n self.burn = burn\n self.turn = turn\n self.river = rover\n self.winner = winner\n self.split = split\n self.sidepot = sidepot\n\n # this should call the player rotaion, and pot renule etc.\n def handinc(self):\n self.handId += 1\n return self.handId\n\n # This sets up the players in a seating positon and gives them the dealer, BB and SM \n def Playerposition(self):\n for player in Players:\n Players[player].position = player\n Players[0].blindpos = 0\n Players[0].button = True\n Players[1].blindpos = 1\n Players[2].blindpos = 2\n\n # This rotates the dealer, BB and SB\n def buttonrotaion(self):\n index = 0\n for player in Players:\n if Players[player].button == True:\n Players[player].button == False\n Players[player].blindpos = 3\n index = player + 1\n break\n for x in range(0,3):\n if index > len(Players):\n Players[0] = x\n else:\n Players[index] = x\n\n def Pot(self):\n print(\"Pot: \", self.pot)\n\n def winner(self):\n pass\n \n\n\n \n \n \n\n\n\n\n\n \nclass Table(object):\n def __init__ (self):\n pass\n\n\n\n\n\n\n\n#testing\n\n\nprint('-------GAME PLAY!!--------')\n\nprint('Creating players')\nplayer1 = Player(\"Ste\", 2000)\nplayer2 = Player(\"Adam\", 2000)\nplayer3 = Player(\"Richie\", 2000)\nplayer4 = Player(\"Keith\", 2000)\nplayer5 = Player(\"Luke\", 2000)\nplayer6 = Player(\"Alex\", 2000)\n\nPlayers = [player1, player2, player3, player4, player5, player6]\n\nBlinds = [10,20]\n\ndeck = Deck()\ndeck.shuffle()\n\nhand = Hand()\nhand.Playerposition()\n\n\n\n\n\nhand.handId()\n\n\n\n\n\n\n\n\n","sub_path":"cards.py","file_name":"cards.py","file_ext":"py","file_size_in_byte":7463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"72841390","text":"# Created by Bibigon for RT T0 28.12.07\r\n\r\nimport sys\r\nfrom net.sf.l2j.gameserver.datatables import SkillTable\r\nfrom net.sf.l2j.gameserver.model.quest import State\r\nfrom net.sf.l2j.gameserver.model.quest import QuestState\r\nfrom net.sf.l2j.gameserver.model.quest.jython import QuestJython as JQuest\r\n\r\nqn = \"20081_SantaHelp\"\r\n\r\nclass Quest (JQuest) :\r\n\r\n def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr)\r\n\r\n def onEvent (self,event,st) :\r\n htmltext = event\r\n \r\n if event == \"WindWalk\":\r\n st.getPlayer().useMagic(SkillTable.getInstance().getInfo(4262,2),False,False)\r\n st.getPlayer().setCurrentMp(st.getPlayer().getMaxMp())\r\n htmltext = \"31863-2.htm\"\r\n\r\n elif event == \"Haste\":\r\n st.getPlayer().useMagic(SkillTable.getInstance().getInfo(4263,1),False,False)\r\n st.getPlayer().setCurrentMp(st.getPlayer().getMaxMp())\r\n htmltext = \"31863-6.htm\"\r\n\r\n elif event == \"Empower\":\r\n st.getPlayer().useMagic(SkillTable.getInstance().getInfo(4264,1),False,False)\r\n st.getPlayer().setCurrentMp(st.getPlayer().getMaxMp())\r\n htmltext = \"31863-3.htm\"\r\n\r\n elif event == \"Might\":\r\n st.getPlayer().useMagic(SkillTable.getInstance().getInfo(4265,3),False,False)\r\n st.getPlayer().setCurrentMp(st.getPlayer().getMaxMp())\r\n htmltext = \"31863-5.htm\"\r\n\r\n elif event == \"Shield\":\r\n st.getPlayer().useMagic(SkillTable.getInstance().getInfo(4266,3),False,False)\r\n st.getPlayer().setCurrentMp(st.getPlayer().getMaxMp())\r\n htmltext = \"31863-4.htm\"\r\n \r\n if htmltext != event:\r\n st.setState(COMPLETED)\r\n st.exitQuest(1)\r\n\r\n return htmltext\r\n\r\n\r\n def onTalk (self,npc,player):\r\n st = player.getQuestState(qn)\r\n if not st : return \r\n npcId = npc.getNpcId()\r\n if npcId == 31863 :\r\n htmltext = \"31863-1.htm\"\r\n st.setState(STARTED)\r\n return htmltext\r\n\r\n\r\n\r\nQUEST = Quest(2008,qn,\"custom\")\r\nCREATED = State('Start', QUEST)\r\nSTARTED = State('Started', QUEST)\r\nCOMPLETED = State('Completed', QUEST)\r\n\r\nQUEST.setInitialState(CREATED)\r\n\r\nQUEST.addStartNpc(31863)\r\nQUEST.addTalkId(31863)\r\n","sub_path":"Datapack/gameserver/optional/Events/ChristmasRT/data/jscript/custom/20081_SantaHelp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"38010031","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('seouser', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='post',\n name='social_bound',\n field=models.CharField(default=b'vkontakte', max_length=10, choices=[(b'vk', b'vkontakte'), (b'fb', b'facebook'), (b'tw', b'twitter')]),\n ),\n ]\n","sub_path":"seouser/migrations/0002_auto_20150922_1728.py","file_name":"0002_auto_20150922_1728.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"567389806","text":"#! /usr/bin/python2\n# -*- coding: utf-8 -*-\n\nimport time\n\nclass ConditionChecker:\n\n def __init__(self, log, client, notifier_object):\n self.log = log\n self.client = client\n self.notifier = notifier_object\n self.checked = {}\n\n def check_queue_conditions(self, arguments):\n response = self.client.get_queue()\n if response is None:\n return\n\n messages_ready = response.get(\"messages_ready\")\n messages_unacknowledged = response.get(\"messages_unacknowledged\")\n messages = response.get(\"messages\")\n consumers = response.get(\"consumers\")\n\n queue = arguments[\"server_queue\"]\n queue_conditions = arguments[\"conditions\"][queue]\n ready_size = queue_conditions.get(\"conditions_ready_queue_size\")\n unack_size = queue_conditions.get(\"conditions_unack_queue_size\")\n total_size = queue_conditions.get(\"conditions_total_queue_size\")\n consumers_connected_min = queue_conditions.get(\"conditions_queue_consumers_connected\")\n\n wait = self.get_time_to_wait(arguments)\n\n if ready_size is not None and messages_ready > ready_size:\n if self.needNotify(queue + '__' + 'messages_ready', wait):\n self.notifier.send_notification(\"%s: messages_ready = %d > %d\" % (queue, messages_ready, ready_size))\n self.clean(queue + '__' + 'messages_ready')\n else:\n self.clean(queue + '__' + 'messages_ready')\n\n if unack_size is not None and messages_unacknowledged > unack_size:\n if self.needNotify(queue + '__' + 'messages_unacknowledged', wait):\n self.notifier.send_notification(\"%s: messages_unacknowledged = %d > %d\" % (queue, messages_unacknowledged, unack_size))\n self.clean(queue + '__' + 'messages_unacknowledged')\n else:\n self.clean(queue + '__' + 'messages_unacknowledged')\n\n if total_size is not None and messages > total_size:\n if self.needNotify(queue + '__' + 'messages', wait):\n self.notifier.send_notification(\"%s: messages = %d > %d\" % (queue, messages, total_size))\n self.clean(queue + '__' + 'messages')\n else:\n self.clean(queue + '__' + 'messages')\n\n if consumers_connected_min is not None and consumers < consumers_connected_min:\n if self.needNotify(queue + '__' + 'consumers_connected', wait):\n self.notifier.send_notification(\"%s: consumers_connected = %d < %d\" % (queue, consumers, consumers_connected_min))\n self.clean(queue + '__' + 'consumers_connected')\n else:\n self.clean(queue + '__' + 'consumers_connected')\n\n def check_consumer_conditions(self, arguments):\n response = self.client.get_consumers()\n if response is None:\n return\n\n consumers_connected = len(response)\n consumers_connected_min = arguments[\"generic_conditions\"].get(\"conditions_consumers_connected\")\n wait = self.get_time_to_wait(arguments)\n\n if consumers_connected is not None and consumers_connected < consumers_connected_min:\n if self.needNotify('consumer_conditions', wait):\n self.notifier.send_notification(\"consumers_connected = %d < %d\" % (consumers_connected, consumers_connected_min))\n self.clean('consumer_conditions')\n else:\n self.clean('consumer_conditions')\n\n def check_connection_conditions(self, arguments):\n response = self.client.get_connections()\n if response is None:\n return\n\n open_connections = len(response)\n\n open_connections_min = arguments[\"generic_conditions\"].get(\"conditions_open_connections\")\n wait = self.get_time_to_wait(arguments)\n\n if open_connections is not None and open_connections < open_connections_min:\n if self.needNotify('open_connections', wait):\n self.notifier.send_notification(\"open_connections = %d < %d\" % (open_connections, open_connections_min))\n self.clean('open_connections')\n else:\n self.clean('open_connections')\n\n def check_node_conditions(self, arguments):\n response = self.client.get_nodes()\n if response is None:\n return\n\n nodes_running = len(response)\n\n conditions = arguments[\"generic_conditions\"]\n nodes_run = conditions.get(\"conditions_nodes_running\")\n node_memory = conditions.get(\"conditions_node_memory_used\")\n wait = self.get_time_to_wait(arguments)\n\n\n if nodes_run is not None and nodes_running < nodes_run:\n if self.needNotify('nodes_running', wait):\n self.notifier.send_notification(\"nodes_running = %d < %d\" % (nodes_running, nodes_run))\n self.clean('nodes_running')\n else:\n self.clean('nodes_running')\n\n for node in response:\n n = 'node_memory_used' + node.get(\"name\")\n if node_memory is not None and node.get(\"mem_used\") > (node_memory * pow(1024, 2)):\n if self.needNotify(n, wait):\n self.notifier.send_notification(\"Node %s - node_memory_used = %d > %d MBs\" % (node.get(\"name\"), node.get(\"mem_used\"), node_memory))\n self.clean(n)\n else:\n self.clean(n)\n\n\n def get_time_to_wait(self, arguments):\n return arguments['server_time_to_wait'] if 'server_time_to_wait' in arguments else 60\n\n def needNotify(self, name, wait):\n\n if wait <= 0:\n return True\n\n if name not in self.checked:\n # it's first time\n self.checked[name] = time.time() + wait\n return False\n\n if self.checked[name] < time.time():\n return True\n\n return False\n\n def clean(self, name):\n if name in self.checked:\n del self.checked[name]","sub_path":"rabbitmqalert/conditionchecker.py","file_name":"conditionchecker.py","file_ext":"py","file_size_in_byte":5899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"293085695","text":"def binary_search(num_list):\n search_num = max(num_list)\n\n low = 0\n high = len(num_list) - 1\n\n while low <= high:\n mid = (low + high) // 2\n guess = num_list[mid]\n\n if guess == search_num:\n return mid\n\n if guess > search_num:\n high = mid - 1\n\n else:\n low = mid + 1\n\n return -1\n\n\nres = binary_search([1, 4, 9, 14, 36, 49, 56, 78, 213, 439, 569, 772, 890, 918])\nprint(res)\n\n\"\"\"\nBig O: log(n)\n\"\"\"\n","sub_path":"Algo/Searching and Sorting/binary_search.py","file_name":"binary_search.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"568840903","text":"from MVC import control\nfrom MVC import model\n\nclass View:\n def __init__(self):\n self.control = None\n #guarda control associada\n def set_control(self,control):\n self.control = control\n def exibir_menu(self):\n resposta=True\n while resposta:\n print('''\n 1.Exibir lista\n 2.Incluir item\n 3.Excluir item\n 4.Sair\n ''')\n resposta = input('Digite um número: ')\n if resposta == '1':\n print('\\n Lista de itens')\n self.exibir_lista_compras(self.control.get_lista_compras())\n elif resposta == '2':\n print('\\n Item incluído')\n elif resposta == '3':\n print('\\n Item excluído')\n elif resposta == '4':\n print('\\n Tchau!')\n resposta=False\n else:\n print('\\n Valor incorreto')\n #exibir lista de compras\n def exibir_lista_compras(self,lista_compras):\n self.lista_compras = lista_compras\n est = open('estoque', 'r')\n lista = est.read()\n est.close()\n print(lista)","sub_path":"MVC/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"265450120","text":"import couchdb\n\n\nclass Database():\n orders = None\n def __init__(self):\n try:\n print('Establishing database connection')\n server = couchdb.Server('http://172.18.0.2:5984/')\n if 'orders' not in server:\n server.create('orders')\n self.orders = server['orders']\n print('Connected to database')\n except Exception as e:\n print('Can\\'t connect to db', e)","sub_path":"src/api/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"575814288","text":"\"\"\"Update Node.path column\n\nRevision ID: 559ce6eb0949\nRevises: 1063d7178fa\nCreate Date: 2014-12-10 13:20:29.374951\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '559ce6eb0949'\ndown_revision = '1063d7178fa'\n\n\ndef upgrade():\n\n from kotti.resources import DBSession\n DBSession.execute(\n \"update nodes set path = path || '/' where path not like '%/'\"\n )\n\n\ndef downgrade():\n from kotti import DBSession\n from kotti.resources import Node\n\n for node in DBSession.query(Node).with_polymorphic([Node]):\n # remove trailing '/' from all nodes but root\n if node.path != u'/':\n node.path = node.path[:-1]\n","sub_path":"kotti/alembic/versions/559ce6eb0949_update_node_path_column.py","file_name":"559ce6eb0949_update_node_path_column.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"382439242","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport argparse\nimport os\nimport shutil\nfrom time import time\nfrom SparseVector import SparseVector\nfrom LogisticRegression import totalLoss, gradTotalLoss, getAllFeatures, basicMetrics, metrics\nfrom operator import add\nfrom pyspark import SparkContext\n\n\ndef readBetaRDD(input, spark_context):\n \"\"\" Read a vector β from file input. Each line contains pairs of the form:\n (feature,value)\n\n The return value is an RDD containing the above pairs.\n \"\"\"\n return spark_context.textFile(input) \\\n .map(eval)\n\n\ndef writeBetaRDD(output, beta):\n \"\"\" Write a vector β to a file output. Each line contains pairs of the form:\n (feature,value)\n \"\"\"\n if os.path.exists(output):\n shutil.rmtree(output)\n beta.saveAsTextFile(output)\n\n\ndef readDataRDD(input_file, spark_context):\n \"\"\" Read data from an input file. Each line of the file contains tuples of the form\n\n (x,y) \n\n x is a dictionary of the form: \n\n { \"feature1\": value, \"feature2\":value, ...}\n\n and y is a binary value +1 or -1.\n\n The result is stored in an RDD containing tuples of the form\n (SparseVector(x),y) \n \"\"\"\n return spark_context.textFile(input_file) \\\n .map(eval) \\\n .map(lambda datapoint: (SparseVector(datapoint[0]), datapoint[1]))\n\n\ndef identityHash(num):\n \"\"\" Hash a number to itself \n \"\"\"\n return num\n\n\ndef groupDataRDD(dataRDD, N):\n \"\"\" Partition the data in dataRDD into N partitions and collect the data in\n each partition into a list. The rdd data should contain inputs of the type:\n (SparseVector(x),y)\n\n The result is an RDD containing tuples of the type\n\n (partitionID,dataList)\n \n where i is the index of the partition and dataList is a list of (SparseVector(x),y) values\n containing the data assigned to this partition\n\n Inputs are: \n - dataRDD: The RDD containing the data\n - N: the number of partitions of the returned RDD\n\n The return value is the grouped RDD, partitioned using identityHash as a partition function.\n \"\"\"\n return dataRDD.repartition(N) \\\n .mapPartitionsWithIndex(\n lambda partitionID, elements: [(partitionID, [x for x in elements])]) \\\n .partitionBy(N, identityHash).cache()\n\n\ndef basicStatistics(groupedDataRDD):\n \"\"\" Return some basic statistics about the data in each partition in groupedDataRDD\n \"\"\"\n num_datapoints = groupedDataRDD.values().map(lambda dataList: len(dataList))\n num_features = groupedDataRDD.values().map(lambda dataList: len(getAllFeatures(dataList)))\n\n datapoint_stats = (num_datapoints.min(), num_datapoints.max(), num_datapoints.mean())\n feature_stats = (num_features.min(), num_features.max(), num_features.mean())\n\n return datapoint_stats, feature_stats\n\n\ndef getAllFeaturesRDD(groupedDataRDD):\n \"\"\" Get all the features present in grouped dataset groupedDataRDD.\n \n The input is:\n - groupedDataRDD: a groupedRDD containing pairs of the form (partitionID,dataList), where \n partitionID is an integer and dataList is a list of (SparseVector(x),y) values\n\n The return value is an RDD containing the above features.\n \"\"\"\n return groupedDataRDD.values() \\\n .flatMap(lambda dataList: getAllFeatures(dataList)) \\\n .distinct()\n\n\ndef mapFeaturesToPartitionsRDD(groupedDataRDD, N):\n \"\"\" Given a groupedDataRDD, construct an RDD connecting the partitionID\n to all the features present in the data list of this partition. That is,\n given a groupedDataRDD containing pairs of the form\n\n (partitionID,dataList)\n \n return an RDD containing *all* pairs of the form\n\n (feat,partitionID)\n\n where feat is a feature label appearing in a datapoint inside dataList associated with partitionID.\n\n The inputs are:\n - groupedDataRDD: RDD containing the grouped data\n - N: Number of partitions of the returned RDD\n \n The returned RDD is partitioned with the default hash function and cached.\n \"\"\"\n return groupedDataRDD.flatMap(lambda pair: [(data, pair[0]) for data in getAllFeatures(pair[1])]) \\\n .partitionBy(N) \\\n .cache()\n\n\ndef sendToPartitions(betaRDD, featuresToPartitionsRDD, N):\n \"\"\" Given a betaRDD and a featuresToPartitionsRDD, create an RDD that contains pairs of the form \n (partitionID, small_beta)\n \n where small_beta is a SparseVector containing only the features present in the partition partitionID. \n \n The inputs are:\n - betaRDD: RDD storing β\n - featuresToPartitionsRDD: RDD mapping features to partitions, generated by mapFeaturesToPartitionsRDD\n - N: Number of partitions of the returned RDD\n\n The returned RDD is partitioned with the identityHash function and cached.\n \"\"\"\n return betaRDD.join(featuresToPartitionsRDD) \\\n .map(lambda pair: (pair[1][1], SparseVector({pair[0]: pair[1][0]}))) \\\n .reduceByKey(lambda x, y: x + y, numPartitions=N, partitionFunc=identityHash) \\\n .cache()\n\n\ndef totalLossRDD(groupedDataRDD, featuresToPartitionsRDD, betaRDD, N, lam=0.0):\n \"\"\" Given a β represented by RDD betaRDD and a grouped dataset data represented by groupedDataRDD compute \n the regularized total logistic loss:\n\n L(β) = Σ_{(x,y) in data} l(β;x,y) + λ ||β ||_2^2 \n \n Inputs are:\n - groupedDataRDD: a groupedRDD containing pairs of the form (partitionID,dataList), where \n partitionID is an integer and dataList is a list of (SparseVector(x),y) values\n - featuresToPartitionsRDD: RDD mapping features to partitions, generated by mapFeaturesToPartitionsRDD\n - betaRDD: a vector β represented as an RDD of (feature,value) pairs\n - N: Number of partitions of RDDs\n - lam (optional): the regularization parameter λ (default: 0.0)\n\n The return value is the scalar L(β).\n \"\"\"\n small_beta = sendToPartitions(betaRDD, featuresToPartitionsRDD, N)\n total_loss = groupedDataRDD.join(small_beta) \\\n .map(lambda beta: totalLoss(beta[1][0], beta[1][1], lam=0)) \\\n .reduce(lambda x, y: x + y)\n\n mybeta = SparseVector(betaRDD.collect())\n\n return total_loss + lam * mybeta.dot(mybeta)\n\ndef gradTotalLossRDD(groupedDataRDD, featuresToPartitionsRDD, betaRDD, N, lam=0.0):\n \"\"\" Given a β represented by RDD betaRDD and a grouped dataset data represented by groupedDataRDD compute \n the regularized total logistic loss :\n\n ∇L(β) = Σ_{(x,y) in data} ∇l(β;x,y) + 2λ β \n \n Inputs are:\n - groupedDataRDD: a groupedRDD containing pairs of the form (partitionID,dataList), where \n partitionID is an integer and dataList is a list of (SparseVector(x),y) values\n - featuresToPartitionsRDD: an RDD mapping features to relevant partitionIDs, created by mapFeaturesToPartitionsRDD\n - betaRDD: a vector β represented as an RDD of (feature,value) pairs\n - lam: the regularization parameter λ\n\n The return value is an RDD storing ∇L(β) in key value pairs of the form:\n (feature,value)\n \"\"\"\n small_beta = sendToPartitions(betaRDD, featuresToPartitionsRDD, N)\n grad_total_loss = groupedDataRDD.join(small_beta) \\\n .map(lambda dataBeta: gradTotalLoss(dataBeta[1][0], dataBeta[1][1], 0))\\\n .flatMap(lambda pairs: [(key,pairs[key]) for key in pairs.keys()])\\\n .reduceByKey(lambda x, y: x+y, numPartitions=N)\n\n # redefining betaRDD\n betaRDD = betaRDD.mapValues(lambda x: lam * x * 2)\n\n return grad_total_loss.join(betaRDD) \\\n .map(lambda x: (x[0], x[1][0]+x[1][1])) \\\n .partitionBy(N)\n\n\ndef lineSearch(fun, xRDD, gradRDD, a=0.2, b=0.6):\n \"\"\" Given function fun, a current argument xRDD, and gradient gradRDD, \n perform backtracking line search to find the next point to move to.\n (see Boyd and Vandenberghe, page 464).\n\n Both x and y are presumed to be RDDs containing key-value pairs of the form:\n (feature,value)\n \n Parameters a,b are the parameters of the line search.\n\n Given function fun, and current argument x, and gradient ∇fun(x), the function finds a t such that\n fun(x - t * grad) <= fun(x) - a t \n\n The return value is the resulting value of t.\n \"\"\"\n t = 1.0\n\n fatx = fun(xRDD)\n gradSq = gradRDD.mapValues(lambda x: x * x).values().reduce(add)\n\n x_min_t_grad = xRDD.join(gradRDD).mapValues(lambda pair: pair[0] - t * pair[1])\n\n while fun(x_min_t_grad) > fatx - a * t * gradSq:\n t = b * t\n x_min_t_grad = xRDD.join(gradRDD).mapValues(lambda pair: pair[0] - t * pair[1])\n return t\n\n\ndef trainRDD(groupedDataRDD, featuresToPartitionsRDD, betaRDD_0, lam, max_iter, eps, N):\n \"\"\" Train a logistic model over a grouped dataset.\n \n Inputs are:\n - groupedDataRDD: a groupedRDD containing pairs of the form (partitionID,dataList), where \n partitionID is an integer and dataList is a list of (SparseVector(x),y) values\n - featuresToPartitionsRDD: an RDD mapping features to relevant partitionIDs, created by mapFeaturesToPartitionsRDD()\n - betaRDD_0: an initial vector β represented as an RDD of (feature,value) pairs\n - lam: the regularization parameter λ\n\n - max_iter: the maximum number of iterations\n - eps: the ε-tolerance\n - N: the number of partitions\n \"\"\"\n k = 0\n gradNorm = 2 * eps\n betaRDD = betaRDD_0\n start = time()\n while k < max_iter and gradNorm > eps:\n gradRDD = gradTotalLossRDD(groupedDataRDD, featuresToPartitionsRDD, betaRDD, N, lam).cache()\n\n fun = lambda xRDD: totalLossRDD(groupedDataRDD, featuresToPartitionsRDD, xRDD, N, lam)\n gamma = lineSearch(fun, betaRDD, gradRDD)\n betaRDD = betaRDD.join(gradRDD).mapValues(lambda pair: pair[0] - gamma * pair[1]).cache()\n\n obj = fun(betaRDD)\n gradSq = gradRDD.mapValues(lambda x: x * x).values().reduce(add)\n gradNorm = np.sqrt(gradSq)\n print('k = ', k, '\\tt = ', time() - start, '\\tL(β_k) = ', obj, '\\t||∇L(β_{k-1})||_2 = ', gradNorm, '\\tγ = ',\n gamma)\n k = k + 1\n\n return betaRDD, gradNorm, k\n\n\ndef basicMetricsRDD(groupedDataRDD, featuresToPartitionsRDD, betaRDD, N):\n \"\"\" Output the quantities necessary to compute the accuracy, precision, and recall of the prediction of labels in a dataset under a given β.\n \n The accuracy (ACC), precision (PRE), and recall (REC) are defined in terms of the following sets:\n\n P = datapoints (x,y) in data for which <β,x> > 0\n N = datapoints (x,y) in data for which <β,x> <= 0\n \n TP = datapoints in (x,y) in P for which y=+1 \n FP = datapoints in (x,y) in P for which y=-1 \n TN = datapoints in (x,y) in N for which y=-1\n FN = datapoints in (x,y) in N for which y=+1\n\n For #XXX the number of elements in set XXX, the accuracy, precision, and recall of parameter vector β over data are defined as:\n \n ACC(β,data) = ( #TP+#TN ) / (#P + #N)\n PRE(β,data) = #TP / (#TP + #FP)\n REC(β,data) = #TP/ (#TP + #FN)\n\n Inputs are:\n - groupedDataRDD: a groupedRDD containing pairs of the form (partitionID,dataList), where \n partitionID is an integer and dataList is a list of (SparseVector(x),y) values\n - featuresToPartitionsRDD: an RDD mapping features to relevant partitionIDs, created by mapFeaturesToPartitionsRDD()\n - betaRDD: a vector β represented as an RDD of (feature,value) pairs\n\n The return values are \n - #P,#N,#TP,#FP,#TN,#FN\n \"\"\"\n small_beta = sendToPartitions(betaRDD, featuresToPartitionsRDD, N)\n basic_metrics = groupedDataRDD.join(small_beta) \\\n .map(lambda data : basicMetrics(data[1][0], data[1][1])) \\\n .reduce(lambda x, y: [x[0] + y[0], x[1] + y[1],\n x[2] + y[2], x[3] + y[3],\n x[4] + y[4], x[5] + y[5]])\n\n # #P, #N, #TP, #FP, #TN, #FN\n return basic_metrics[0], basic_metrics[1], \\\n basic_metrics[2], basic_metrics[3], \\\n basic_metrics[4], basic_metrics[5]\n\ndef testRDD(groupedDataRDD, featuresToPartitionsRDD, betaRDD, N):\n \"\"\" Output the accuracy, precision, and recall of the prediction of labels in a dataset under a given β.\n \n The accuracy (ACC), precision (PRE), and recall (REC) are defined in terms of the following sets:\n\n P = datapoints (x,y) in data for which <β,x> > 0\n N = datapoints (x,y) in data for which <β,x> <= 0\n \n TP = datapoints in (x,y) in P for which y=+1 \n FP = datapoints in (x,y) in P for which y=-1 \n TN = datapoints in (x,y) in N for which y=-1\n FN = datapoints in (x,y) in N for which y=+1\n\n For #XXX the number of elements in set XXX, the accuracy, precision, and recall of parameter vector β over data are defined as:\n\n ACC(β,data) = ( #TP+#TN ) / (#P + #N)\n PRE(β,data) = #TP / (#TP + #FP)\n REC(β,data) = #TP/ (#TP + #FN)\n\n Inputs are:\n - groupedDataRDD: a groupedRDD containing pairs of the form (partitionID,dataList), where \n partitionID is an integer and dataList is a list of (SparseVector(x),y) values\n - featuresToPartitionsRDD: an RDD mapping features to relevant partitionIDs, created by mapFeaturesToPartitionsRDD()\n - betaRDD: a vector β represented as an RDD of (feature,value) pairs\n\n The return values are a tuple containing\n - ACC,PRE,REC \n \"\"\"\n P, N, TP, FP, TN, FN = basicMetricsRDD(groupedDataRDD, featuresToPartitionsRDD, betaRDD, N)\n return metrics(P, N, TP, FP, TN, FN)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Parallel Sparse Logistic Regression.',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--traindata', default=None,\n help='Input file containing (x,y) pairs, used to train a logistic model')\n parser.add_argument('--testdata', default=None,\n help='Input file containing (x,y) pairs, used to test a logistic model')\n parser.add_argument('--beta', default='beta',\n help='File where beta is stored (when training) and read from (when testing)')\n parser.add_argument('--lam', type=float, default=0.0, help='Regularization parameter λ')\n parser.add_argument('--max_iter', type=int, default=40, help='Maximum number of iterations')\n parser.add_argument('--N', type=int, default=20, help='Level of parallelism/number of partitions')\n parser.add_argument('--eps', type=float, default=0.1,\n help='ε-tolerance. If the l2_norm gradient is smaller than ε, gradient descent terminates.')\n\n verbosity_group = parser.add_mutually_exclusive_group(required=False)\n verbosity_group.add_argument('--verbose', dest='verbose', action='store_true',\n help=\"Print Spark warning/info messages.\")\n verbosity_group.add_argument('--silent', dest='verbose', action='store_false',\n help=\"Suppress Spark warning/info messages.\")\n parser.set_defaults(verbose=False)\n\n args = parser.parse_args()\n\n sc = SparkContext(appName='Parallel Sparse Logistic Regression')\n\n if not args.verbose:\n sc.setLogLevel(\"ERROR\")\n\n if args.traindata is not None:\n print('Reading training data from', args.traindata)\n traindataRDD = readDataRDD(args.traindata, sc)\n groupedTrainDataRDD = groupDataRDD(traindataRDD, args.N)\n trainFeaturesToPartitionsRDD = mapFeaturesToPartitionsRDD(groupedTrainDataRDD, args.N).cache()\n\n (dp_stats, f_stats) = basicStatistics(groupedTrainDataRDD)\n\n print('Read', traindataRDD.count(), 'training data points')\n print('Created', args.N, 'partitions with statistics:')\n print('Datapoints per partition: \\tmin = %f \\tmax = %f \\tavg = %f ' % dp_stats)\n print('Features per partition: \\tmin = %f \\tmax = %f \\tavg = %f ' % f_stats)\n\n betaRDD0 = getAllFeaturesRDD(groupedTrainDataRDD).map(lambda x: (x, 0.0)).partitionBy(args.N).cache()\n\n print('Initial beta has', betaRDD0.count(), 'features')\n\n print('Training on data from', args.traindata, 'with λ =', args.lam, ', ε = ', args.eps, ', max iter = ',\n args.max_iter)\n beta, gradNorm, k = trainRDD(groupedTrainDataRDD, trainFeaturesToPartitionsRDD, betaRDD0, args.lam,\n args.max_iter, args.eps, args.N)\n print('Algorithm ran for', k, 'iterations. Converged:', gradNorm < args.eps)\n print('Saving trained β in', args.beta)\n writeBetaRDD(args.beta, beta)\n\n if args.testdata is not None:\n print('Reading test data from', args.testdata)\n testdataRDD = readDataRDD(args.testdata, sc)\n groupedTestDataRDD = groupDataRDD(testdataRDD, args.N).cache()\n testFeaturesToPartitionsRDD = mapFeaturesToPartitionsRDD(groupedTestDataRDD, args.N).cache()\n (dp_stats, f_stats) = basicStatistics(groupedTestDataRDD)\n\n print('Read', testdataRDD.count(), 'test data points')\n print('Created', args.N, 'partitions with statistics:')\n print('Datapoints per partition: \\tmin = %f \\tmax = %f \\tavg = %f ' % dp_stats)\n print('Features per partition: \\tmin = %f \\tmax = %f \\tavg = %f ' % f_stats)\n\n print('Reading β from', args.beta)\n betaRDD = readBetaRDD(args.beta, sc).partitionBy(args.N)\n print('Read beta with', betaRDD.count(), 'features')\n print('Testing on data from', args.testdata)\n acc, pre, rec = testRDD(groupedTestDataRDD, testFeaturesToPartitionsRDD, betaRDD, args.N)\n print('\\tACC = ', acc, '\\tPRE = ', pre, '\\tREC = ', rec)\n","sub_path":"ParallelLogisticRegression.py","file_name":"ParallelLogisticRegression.py","file_ext":"py","file_size_in_byte":18778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"117249354","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 1 14:21:24 2017\r\n\r\n@author: rdk10\r\n\"\"\"\r\nimport numpy as np\r\nimport sitchensis.Functions as f\r\nimport pandas as pd\r\n\r\nimport pdb\r\n\r\ndef colTest(colNames, testColNames, dataType, treeName):\r\n \r\n logFileName = '{0}_ErrorScan.txt'.format(treeName)\r\n colTest = np.array([col in colNames for col in testColNames], dtype = bool)\r\n \r\n if any(colTest == False):\r\n if sum(colTest == False) == 1:\r\n textout = \"The mandatory column '{0}' was not found in the {1} input data\".format(testColNames[colTest==False][0],dataType)\r\n print(textout)\r\n f.print2Log(logFileName,textout)\r\n else:\r\n textout = 'The mandatory columns {0} were not found in the {1} input data'.format(testColNames[colTest==False],dataType)\r\n print(textout)\r\n f.print2Log(logFileName, textout)\r\n else:\r\n textout = 'All the mandatory columns are present to calculate {0} values'.format(dataType)\r\n print(textout)\r\n f.print2Log(logFileName, textout)\r\n\r\ndef trunkScan(treeData, treeName):\r\n \r\n logFileName = '{0}_ErrorScan.txt'.format(treeName)\r\n \r\n lf = open(logFileName,'a') #open a file for writing ('w') to, lf for log file\r\n lf.write('\\n############## Trunks ##############\\n')\r\n lf.close()\r\n \r\n trunkDat = treeData['trunk']\r\n trunkDat.columns = [x.lower() for x in trunkDat.columns]\r\n #trunkDat.dtypes\r\n trunkDat['name'] = trunkDat['name'].str.upper()\r\n \r\n #Make this a function and apply to all datasets\r\n testDiam = 'diam' in trunkDat.columns\r\n testRadius = 'radius' in trunkDat.columns\r\n if any([testDiam,testRadius]):\r\n #There is at least one needed column\r\n if testDiam == True and any(np.isnan(trunkDat['radius'])):\r\n if testDiam:\r\n trunkDat['radius'] = trunkDat['diam']/200 #converts form m to cm\r\n elif testRadius == True and testDiam == False:\r\n if testRadius: \r\n trunkDat['diam'] = trunkDat['radius'] * 200 #converts from cm to m\r\n else:\r\n f.print2Log(logFileName, 'There must be at least a diameter or radius column for trunks')\r\n\r\n trunkCols = trunkDat.columns.str.lower()\r\n testTrunkCols = np.array(['name','height','diam', 'radius', 'dist', 'azi', 'ref', 'ref type'])\r\n \r\n colTest(trunkCols, testTrunkCols, \"trunk\", treeName)\r\n\r\n if any(pd.isnull(trunkDat['ref'])):\r\n print('\\nThere are missing references for the main trunk, these must be filled in prior to running the program.')\r\n f.print2Log(logFileName, '\\nThere are missing references for the main trunk, these must be filled in prior to running the program.')\r\n\r\n treeData['trunk'] = trunkDat \r\n return(treeData) \r\n\r\ndef segScan(treeData, treeName):\r\n \r\n \"\"\"Brings in a dictionary of data for trunks, segments, and brancehs \"\"\"\r\n logFileName = '{0}_ErrorScan.txt'.format(treeName)\r\n \r\n lf = open(logFileName,'a') #open a file for writing ('w') to, lf for log file\r\n lf.write('\\n\\n############## Segments ##############\\n')\r\n lf.close()\r\n \r\n segs = treeData['segments']\r\n \r\n #Test for calculated radius from diameter (must have radius in meters!!!)\r\n testDiam = 'base diam' and 'top diam' in segs.columns\r\n testRadius = 'base radius' and 'top radius' in segs.columns\r\n if any([testDiam,testRadius]):\r\n #There is at least one needed column\r\n if any(np.isnan(segs['base radius'])) or any(np.isnan(segs['top radius'])):\r\n segs['base radius'] = segs['base diam']/200 #converts form cm to m\r\n segs['top radius'] = segs['top diam']/200 #converts form cm to m \r\n else:\r\n f.print2Log(logFileName, 'There must be at least a diameter or radius column for segments')\r\n \r\n segCols = segs.columns.str.lower()\r\n testSegCols = np.array(['name','base ht','base diam', 'base radius', 'base dist', 'base azi', 'base ref', 'base ref type',\r\n 'top ht','top diam','top dist', 'top azi', 'top ref','top ref type', 'midsegment dist','midsegment ref'])\r\n \r\n colTest(segCols, testSegCols, \"segment\", treeName)\r\n treeData['segments'] = segs\r\n \r\n #test that base references to mid-segs are segment of origin not a node. \r\n testSegs = segs[['-' in name for name in segs['base name']]]\r\n if any(testSegs['base name'] != testSegs['base ref']) and len(testSegs > 0):\r\n testSegs = testSegs[testSegs['base name'] != testSegs['base ref']]\r\n print('The mid-segment segment(s) {0} are referenced to something other than {1}, this may cause errors.'.format(testSegs['name'].values, testSegs['base name'].values))\r\n f.print2Log(logFileName, '\\nThe mid-segment segment(s) {0} are referenced to something other than {1}, this may cause errors.'.format(testSegs['name'].values, testSegs['base name'].values))\r\n\r\n #send warning if there are references to Mtop\r\n if any([('M' in ref and 'top' in ref) for ref in segs['top ref']]):\r\n print('Warning: There are references to \"Mtop,\" the highest row on the main trunk page will be used for the x,y locations of these segments')\r\n f.print2Log(logFileName, '\\nWarning: There are references to \"Mtop,\" the highest row on the main trunk page will be used for the x,y locations of these segments')\r\n \r\n return(treeData)\r\n\r\ndef brScan(treeData, treeName):\r\n \r\n logFileName = '{0}_ErrorScan.txt'.format(treeName)\r\n \r\n lf = open(logFileName,'a') #open a file for writing ('w') to, lf for log file\r\n lf.write('\\n\\n############## Branches ##############\\n')\r\n lf.close()\r\n \r\n branches = treeData['branches']\r\n brCols = branches.columns.str.lower()\r\n testBrCols = np.array(['name','origin','base ht','base diam', 'base radius', 'orig azi', 'cent azi', 'top diam', 'hd','slope','vd', 'midsegment dist', 'midsegment ref']) \r\n \r\n if 'base z' not in branches.columns and 'base ht' in branches.columns:\r\n branches['base z'] = branches['base ht']\r\n treeData['branches'] = branches\r\n \r\n if 'top ht' not in branches.columns:\r\n branches['top ht'] = np.NaN\r\n \r\n #Test for calculated radius from diameter (must have radius in meters!!!)\r\n testDiam = 'base diam' and 'top diam' in branches.columns\r\n testRadius = 'base radius' and 'top radius' in branches.columns\r\n if any([testDiam,testRadius]):\r\n #There is at least one needed column\r\n if any(np.isnan(branches['base radius'])) or any(np.isnan(branches['top radius'])):\r\n branches['base radius'] = branches['base diam']/200 #converts form cm to m\r\n branches['top radius'] = branches['top diam']/200 #converts form cm to m \r\n else:\r\n f.print2Log(logFileName, 'There must be at least a diameter or radius column for segments')\r\n \r\n colTest(brCols, testBrCols, \"branch\", treeName)\r\n \r\n return(treeData)\r\n\r\ndef custRefScan(custRefs, treeName):\r\n \r\n logFileName = '{0}_ErrorScan.txt'.format(treeName)\r\n \r\n lf = open(logFileName,'a') #open a file for writing ('w') to, lf for log file\r\n lf.write('\\n\\n############## Custom references ##############\\n')\r\n lf.close()\r\n \r\n refCols = custRefs.columns.str.lower()\r\n testRefCols = np.array(['name','diam','dist','azi','ref','ref diam','ref type', 'ref x', 'ref y']) \r\n \r\n colTest(refCols, testRefCols, \"custom reference\", treeName)\r\n \r\n return(custRefs)\r\n","sub_path":"sitchensis/ScanFunctions.py","file_name":"ScanFunctions.py","file_ext":"py","file_size_in_byte":7536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"177256000","text":"#!/usr/bin/env python3\nfrom pwn import *\n\nexe = context.binary = ELF(\"ropnop\")\nlibc = exe.libc\n\nr = None\ndef connect(fresh=True, local=False):\n global r\n if r is not None:\n if fresh:\n r.close()\n else:\n return\n r = remote(\"hax1.allesctf.net\", 9300) if args.REMOTE and not local else exe.process()\n\nconnect()\n\nexe.address = int(r.recvline_contains(\"defusing\").decode().split()[3], 16)\ninfo(\"exe base: %#x\", exe.address)\n\n# sigreturn to read\nframe = SigreturnFrame(kernel=\"amd64\")\nframe.rdi = 0\nframe.rsi = exe.symbols.read\nframe.rdx = 0x100\nframe.rip = exe.symbols.read\nframe.rsp = exe.symbols.read\n\nr.send(flat({\n 0x10: 0x0 , # rbp\n 0x18: [\n exe.symbols.read, # to set rax\n exe.symbols.gadget_shop + 4, frame # sigreturn\n ]\n}))\n\nsleep(2)\n\nr.send(\"A\"*int(constants.SYS_rt_sigreturn))\n\nsleep(2)\n\nr.send(flat({\n 0x0: exe.symbols.read + 0x20,\n 0x20: asm(shellcraft.sh())\n}))\n\nr.interactive()\n\n# CSCG{s3lf_m0d1fy1ng_c0dez!}\n","sub_path":"ropnop/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"117985937","text":"from flask import Flask\nfrom flask import render_template, request, session, url_for, redirect\nimport shelve\napp = Flask(__name__)\n\napp.debug = True\n#usuarios = {}\ndata = shelve.open('data', writeback=True)\ns = []\n\n@app.route('/')\ndef index():\n if 'username' in session:\n s = session['paginas']\n s.insert(0, '/')\n session['paginas'] = s\n if len(s) == 4:\n s.remove(s[3])\n return render_template('web.html', usuario=session['username'], pags=session['paginas'])\n return render_template('web.html')\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n error = None\n if request.method == 'POST':\n ukey = str(request.form['username'])\n if ukey in data and data[ukey]['pass'] == request.form['password']:\n session['username'] = request.form['username']\n session['paginas'] = s\n return redirect(url_for('index'))\n else:\n error = 'Invalid Credentials. Try again!'\n return render_template('web.html', error=error)\n return render_template('web.html')\n\n@app.route('/signin', methods=['GET','POST'])\ndef signin():\n if request.method == 'POST':\n return render_template('formulario.html')\n\n@app.route('/formulario', methods=['GET', 'POST'])\ndef formulario():\n if request.method == 'POST':\n ukey = str(request.form['username'])\n if ukey in data:\n error = 'Exists. Try again!'\n return render_template('formulario.html', error=error)\n else:\n ukey = str(request.form['username'])\n data[ukey] = {'user': ukey,\n 'pass': request.form['password'],\n 'name': request.form['name'],\n 'lastname': request.form['lastname'],\n 'lastlastname': request.form['lastlastname']}\n session['username'] = request.form['username']\n session['paginas'] = s\n return redirect(url_for('index'))\n return render_template('formulario.html')\n\n@app.route('/Programacion')\ndef prog():\n if 'username' in session:\n s = session['paginas']\n s.insert(0, 'Programacion')\n session['paginas'] = s\n if len(s) == 4:\n s.remove(s[3])\n return render_template('child.html', usuario=session['username'], pags=session['paginas'])\n return render_template('child.html')\n\n@app.route('/Informacion')\ndef info():\n if 'username' in session:\n s = session['paginas']\n s.insert(0, 'Informacion')\n session['paginas'] = s\n if len(s) == 4:\n s.remove(s[3])\n return render_template('info.html', usuario=session['username'], pags=session['paginas'])\n return render_template('info.html')\n\n@app.route('/Entradas')\ndef tickets():\n if 'username' in session:\n s = session['paginas']\n s.insert(0, 'Entradas')\n session['paginas'] = s\n if len(s) == 4:\n s.remove(s[3])\n return render_template('tickets.html', usuario=session['username'], pags=session['paginas'])\n return render_template('tickets.html')\n\n@app.route('/Perfil', methods=['GET', 'POST'])\ndef profile():\n if 'username' in session:\n u = str(session['username'])\n s = session['paginas']\n s.insert(0, 'Perfil')\n session['paginas'] = s\n if len(s) == 4:\n s.remove(s[3])\n if request.method == 'POST':\n data[u]['pass'] = request.form['password']\n data[u]['name'] = request.form['name']\n data[u]['lastname'] = request.form['lastname']\n data[u]['lastlastname'] = request.form['lastlastname']\n return render_template('profile.html', usuario=session['username'], pags=session['paginas'],\n pwd=data[u]['user'], name=data[u]['name'],\n lastname=data[u]['lastname'], lastlastname=data[u]['lastlastname'])\n\n return render_template('profile.html', usuario=session['username'], pags=session['paginas'],\n pwd=data[u]['pass'], name=data[u]['name'],\n lastname=data[u]['lastname'], lastlastname=data[u]['lastlastname'])\n else:\n return render_template('formulario.html')\n\n\n@app.route('/logout')\ndef logout():\n session.pop('username', None)\n return redirect(url_for('index'))\n\napp.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'\n\nif __name__=='__main__':\n app.run(host='0.0.0.0')","sub_path":"P2/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":4504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"276857252","text":"class HTMD2:\n \n\tdef HTMD2():\n\n units=int(input(\"please enter a number of units you consumed in a month\"))\n payAmount=units*4.10\n a=str(input(\"fix/KW of billing demand/month\"))\n b=str(input(\"excess demand\"))\n if(a):\n fixedcharges=225.00\n elif(b):\n fixedcharges=285.00\n print(\"select powerfactor\")\n i=int(input())\n while i in range(1,4):\n if(1):\n powerfactor=units*0.0015\n elif(2):\n powerfactor=units*0.0027\n elif(3):\n toucharges=units*0.60\n nightcharges=units*0.30\n total = payAmount + fixedcharges + powerfactor + toucharges + nightcharges\n","sub_path":"asnmnt/HTMD2.py","file_name":"HTMD2.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"476447783","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 ('cyberark', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='account',\n name='platform',\n field=models.CharField(max_length=50, verbose_name='\\u8df3\\u677f\\u673a\\u7c7b\\u578b', choices=[(b'Linux-System', 'linux\\u8df3\\u677f\\u673a'), (b'Windows-System', 'windows\\u8df3\\u677f\\u673a')]),\n ),\n ]\n","sub_path":"WiseEyeIAMService/cyberark/migrations/0002_auto_20171229_1022.py","file_name":"0002_auto_20171229_1022.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"141924802","text":"import pytest\n\nfrom hypothesis import (\n given,\n strategies as st,\n)\n\nfrom evm.utils.encoding import (\n encode_hex,\n decode_hex,\n)\n\n\n@pytest.mark.parametrize(\n \"value,expected\",\n [\n ('myString', '0x6d79537472696e67'),\n ('myString\\x00', '0x6d79537472696e6700'),\n (\n b'\\xd9e\\x11\\xbe\\xdbj\\x81Q\\xea\\xb5\\x9et\\xd6l\\r\\xa7\\xdfc\\x14c\\xb8b\\x1ap\\x8e@\\x93\\xe6\\xec\\xd7P\\x8a',\n '0xd96511bedb6a8151eab59e74d66c0da7df631463b8621a708e4093e6ecd7508a',\n )\n ]\n)\ndef test_encode_hex(value, expected):\n assert encode_hex(value) == expected\n\n\n@given(value=st.binary(min_size=0, average_size=32, max_size=256))\ndef test_hex_encode_decode_round_trip(value):\n intermediate_value = encode_hex(value)\n result_value = decode_hex(intermediate_value)\n assert result_value == value, \"Expected: {0!r}, Result: {1!r}, Intermediate: {2!r}\".format(value, result_value, intermediate_value)\n","sub_path":"tests/utilities/test_encoding_utils.py","file_name":"test_encoding_utils.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"596579422","text":"#!/usr/bin/env python3\n# SPDX-License-Identifier: Apache-2.0\n\"\"\"Integration test Vendor module.\"\"\"\nimport os\n\nimport pytest\n\nimport requests\n\nfrom onapsdk.sdc import SDC\nfrom onapsdk.vendor import Vendor\nfrom onapsdk.vsp import Vsp\nfrom onapsdk.vf import Vf\nfrom onapsdk.service import Service\nimport onapsdk.constants as const\n\n\n@pytest.mark.integration\ndef test_service_unknown():\n \"\"\"Integration tests for Service.\"\"\"\n response = requests.post(\"{}/reset\".format(SDC.base_front_url))\n response.raise_for_status()\n vendor = Vendor(name=\"test\")\n vendor.onboard()\n vsp = Vsp(name=\"test\", package=open(\"{}/ubuntu16.zip\".format(\n os.path.dirname(os.path.abspath(__file__))), 'rb'))\n vsp.vendor = vendor\n vsp.onboard()\n vf = Vf(name='test', vsp=vsp)\n vf.onboard()\n svc = Service(name='test')\n assert svc.identifier is None\n assert svc.status is None\n svc.create()\n assert svc.identifier is not None\n assert svc.status == const.DRAFT\n svc.add_resource(vf)\n svc.checkin()\n assert svc.status == const.CHECKED_IN\n svc.certify()\n assert svc.status == const.CERTIFIED\n svc.distribute()\n assert svc.status == const.DISTRIBUTED\n assert svc.distributed\n\n@pytest.mark.integration\ndef test_service_onboard_unknown():\n \"\"\"Integration tests for Service.\"\"\"\n response = requests.post(\"{}/reset\".format(SDC.base_front_url))\n response.raise_for_status()\n vendor = Vendor(name=\"test\")\n vendor.onboard()\n vsp = Vsp(name=\"test\", package=open(\"{}/ubuntu16.zip\".format(\n os.path.dirname(os.path.abspath(__file__))), 'rb'))\n vsp.vendor = vendor\n vsp.onboard()\n vf = Vf(name='test', vsp=vsp)\n vf.onboard()\n svc = Service(name='test', resources=[vf])\n svc.onboard()\n assert svc.distributed\n","sub_path":"integration_tests/test_04_service.py","file_name":"test_04_service.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"178114918","text":"\"\"\"A base class for movable map tokens.\"\"\"\n\nfrom random import randint\nfrom random import choice\nfrom Enums.Directions import direction\nfrom Enums.SimulatorEntities import simulatorEntity\nimport copy\nimport time\n\n\nclass moveable(object):\n \"\"\"Positional and Speed information along with move functionality.\"\"\"\n\n xPos = 0\n yPos = 0\n baseMovementSpeed = 25\n movementSpeed = 25\n lastMovementTime = 0\n allDirections = [direction.North,\n direction.East,\n direction.South,\n direction.West]\n lastDirection = choice(allDirections)\n\n def nextMovementAllowed(self):\n \"\"\"When is the next movement allowed in milliseconds.\"\"\"\n return self.lastMovementTime + self.movementSpeed\n\n def position(self):\n \"\"\"Access the position of the movable.\"\"\"\n return (self.xPos, self.yPos)\n\n def move(self, area):\n \"\"\"Pick a direction, look and then move.\"\"\"\n self.lastMovementTime = int(round(time.time() * 1000))\n possible = copy.copy(self.allDirections)\n \"\"\"Give preference to last direction moved\"\"\"\n if self.moveableType == simulatorEntity.Zombie and\\\n self.hungerTimer > 0:\n attemptDirection = self.lastDirection\n elif randint(0, 10) <= 8:\n attemptDirection = self.lastDirection\n else:\n attemptDirection = choice(possible)\n\n possible.remove(attemptDirection)\n while len(possible) > 0:\n resultOfMove = area.canMoveInDirection(attemptDirection, self)\n if resultOfMove:\n self.lastDirection = attemptDirection\n return\n\n if len(possible) is 0:\n return\n\n attemptDirection = choice(possible)\n if len(possible) > 0:\n possible.remove(attemptDirection)\n\n def __init__(self):\n \"\"\"Start-up.\"\"\"\n super(moveable, self).__init__()\n","sub_path":"Moveable.py","file_name":"Moveable.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"443977202","text":"class Mixin: # Визначаємо сам класс-домішку\r\n attr = 0 # Визначаємо атрибут домішки\r\n def mixin_method(self):\r\n # Визначаємо метод домішки\r\n print(\"Meтoд домішки\")\r\n\r\nclass MixClass(Mixin):\r\n def MC_method(self):\r\n print(\"Meтoд класу MixClass\")\r\nclass SubClass (MixClass):\r\n def Sub_method(self):\r\n print(\"Meтoд класу SubClass\")\r\nc1=MixClass()\r\nc1.MC_method()\r\nc1.mixin_method ()# метод домішки\r\nс2=SubClass()\r\nс2.MC_method()\r\nс2.Sub_method()\r\nс2.mixin_method()# метод домішки\r\n","sub_path":"I семестр/Програмування (Python)/Лабораторні/Лисенко 6116/Python/Презентації/ex23/Ex6.py","file_name":"Ex6.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"606027563","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 19 17:58:31 2020\n\n@author: shamu\n\"\"\"\n\n\n\ndef psi_save_grid_data_zip(Data_Name,lat_rgnl,lon_rgnl,lat_co,lon_co,\n lat_F,lon_F,Data,method='np'):\n data = {\n 'lat_rgnl': lat_rgnl,\n 'lon_rgnl': lon_rgnl,\n 'lat_co': lat_co,\n 'lon_co': lon_co,\n 'lat_F': lat_F,\n 'lon_F':lon_F,\n 'Data' : Data\n } \n\n if method == 'np' :\n import numpy as np\n Name_Vari = Data_Name+'.npy'\n np.save(Data_Name,data)\n elif method == 'pickle':\n import pickle\n Name_Vari = Data_Name+'.pickle'\n with open(Name_Vari, 'wb') as f:\n pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)\n elif method == 'mat':\n from scipy import io\n Name_Vari = Data_Name+'.mat'\n io.savemat(Name_Vari, data)\n print('Vari_name : '+Name_Vari)\n \n\n\ndef psi_load_grid_data_zip(Data_Name):\n if Data_Name.split('.')[-1] == 'npy' :\n import numpy as np\n Data_temp = np.load(Data_Name)\n elif Data_Name.split('.')[-1] == 'pickle':\n import pickle\n with open('/home/shamu/HUB2/data.pickle', 'rb') as f:\n Data_temp = pickle.load(f)\n elif Data_Name.split('.')[-1] == 'mat':\n from scipy import io\n Data_temp = io.loadmat(Data_Name)\n lat_rgnl = Data_temp['lat_rgnl']\n lon_rgnl = Data_temp['lon_rgnl']\n lat_co = Data_temp['lat_co']\n lon_co = Data_temp['lon_co']\n lat_F = Data_temp['lat_F']\n lon_F = Data_temp['lon_F']\n Data = Data_temp['Data']\n # Maxlat = lat_rgnl[-1]\n # Minlat = lat_rgnl[0]\n # Maxlon = lon_rgnl[-1]\n # Minlon = lon_rgnl[0]\n return lat_rgnl,lon_rgnl,lat_co,lon_co,lat_F,lon_F,Data\n \n\n","sub_path":"Ori/psi_package/psi_tools.py","file_name":"psi_tools.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"13328488","text":"from django import forms\nfrom django.utils.encoding import force_unicode\nfrom django.utils.html import mark_safe\n\n\nclass CKeditorWidget(forms.Textarea):\n attrs={}\n \n def __init__(self, toolbar,height=250):\n self.toolbar=toolbar\n self.height=height\n\n class Media:\n js=('/media/js/lib/ckeditor/ckeditor.js',\n '/media/js/lib/ckeditor/adapters/jquery.js',)\n def render(self, name, value, attrs=None):\n if value is None:\n value = ''\n value = force_unicode(value) #important when pre-fill content contains unicode\n rendered = super(CKeditorWidget,self).render(name, value, attrs)\n return mark_safe(self.media)+ rendered+mark_safe(\n u\"\"\"\n \"\"\")","sub_path":"dws/blog/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"227041681","text":"from flask import Flask\nimport os\nimport config\nfrom setting import Base, session, ENGINE\n\napp = Flask(__name__)\nif os.getenv('FLASK_APP_ENV', 'develop') == 'develop':\n app.config.from_object(config.DevelopmentConfig)\n app.config['ENV'] = 'development'\nelse:\n app.config.from_object(config.TestConfig)\n app.config['ENV'] = 'test'\n\napp.config['ENGINE'] = ENGINE\napp.config['BASE'] = Base\n\nif __name__ == '__main__':\n app.run(debug=False)","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"212315413","text":"# code for update operation\r\nimport sqlite3\r\nfrom sqlite_fetch import sqlite3_fetch_rec\r\n\r\n# python sqlite.py Update Accounts employee \"SET salary = '50000' where emp_id=2\"\r\n\r\ndef sqlite3_update_rec(dbname, tablename, condi):\r\n \r\n # database name to be passed as parameter\r\n db_name = dbname+\".db\"\r\n conn = sqlite3.connect(db_name)\r\n \r\n # update the student record\r\n sql_command = \"\"\"UPDATE \"\"\" + tablename + \"\"\" \"\"\" + condi\r\n conn.execute(sql_command)\r\n #conn.execute(\"UPDATE emp SET fname = 'Sams' where staff_number='1'\")\r\n conn.commit() \r\n print (\"Total number of rows updated :\", conn.total_changes)\r\n\r\n # fetch and display the db records\r\n sqlite3_fetch_rec(dbname, tablename) \r\n\r\n # close the connection \r\n conn.close()\r\n","sub_path":"Python/Projects/sqlite/sqlite_update.py","file_name":"sqlite_update.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"383836932","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport sys\nimport copy\nimport rospy\nimport moveit_commander\nimport moveit_msgs.msg\nimport geometry_msgs.msg\nimport numpy as np\nfrom math import pi, tau, dist, cos\nfrom std_msgs.msg import String\nfrom moveit_commander.conversions import pose_to_list\n\ndef all_close(goal, actual, tolerance):\n \"\"\"\n Testing if robot actual and goal pose are within tolerance\n \"\"\"\n if type(goal) is list:\n return np.all(np.abs(np.array(actual) - np.array(goal)) <= tolerance)\n elif type(goal) is geometry_msgs.msg.PoseStamped:\n return all_close(goal.pose, actual.pose, tolerance)\n elif type(goal) is geometry_msgs.msg.Pose:\n x0, y0, z0, qx0, qy0, qz0, qw0 = pose_to_list(actual)\n x1, y1, z1, qx1, qy1, qz1, qw1 = pose_to_list(actual)\n # Euclidean distance\n d = dist((x1, y1, z1), (x0, y0, z0))\n # phi = angle between orientations\n cos_phi_half = np.abs(qx0 * qx1 + qy0 * qy1 + qz0 * qz1 + qw0 * qw1)\n return d <= tolerance and cos_phi_half >= cos(tolerance / 2.0)\n \n return True\n\nclass MoveGroupPythonInterfaceTutorialCustom(object):\n \"\"\"\n MoveGroupPythonInterfaceTutorialCustom\n \"\"\"\n\n def __init__(self):\n super(MoveGroupPythonInterfaceTutorialCustom, self).__init__()\n\n moveit_commander.roscpp_initialize(sys.argv)\n rospy.init_node('move_group_python_interface_tutorial_custom', anonymous=True)\n\n robot = moveit_commander.RobotCommander()\n\n scene = moveit_commander.PlanningSceneInterface()\n\n group_name = 'panda_arm'\n move_group = moveit_commander.MoveGroupCommander(group_name)\n\n display_trajectory_pub = rospy.Publisher(\n \"/move_group/display_planned_path\", moveit_msgs.msg.DisplayTrajectory,\n queue_size=20\n )\n\n # Getting Basic Information\n # We can get the name of the reference frame for this robot:\n planning_frame = move_group.get_planning_frame()\n print('========== Planning frame: {}'.format(planning_frame))\n\n # We can also print the name of the end-effector link for this group:\n eef_link = move_group.get_end_effector_link()\n print('========== End effector link: {}'.format(eef_link))\n\n # We can get a list of all the groups in the robot:\n group_names = robot.get_group_names()\n print('========== Available Planning Groups: {}'.format(group_names))\n\n # Sometimes for debugging it is useful to print the entire state of the robot:\n print('========== Printing robot state')\n print(robot.get_current_state())\n print('')\n\n # Misc Variables\n self.box_name = ''\n self.robot = robot\n self.scene = scene\n self.move_group = move_group\n self.display_trajectory_pub = display_trajectory_pub\n self.planning_frame = planning_frame\n self.eef_link = eef_link\n self.group_names = group_names\n\n def go_to_joint_state(self):\n \"\"\"\n Planning to a Joint Goal\n \"\"\"\n # The Pandas zero configuration is at a singularity so the first thing we\n # want to do is move it to a slightly better configuration.\n\n # We can get the joint values from the group and adjust some of the values:\n joint_goal = self.move_group.get_current_joint_values()\n joint_goal[0] = 0\n joint_goal[1] = -pi/4\n joint_goal[2] = 0\n joint_goal[3] = -pi/2\n joint_goal[4] = 0\n joint_goal[5] = pi/3\n joint_goal[6] = 0\n\n # The go command can be called with joint values, poses, or without any\n # parameters if you have already set the pose or joint target for the group\n self.move_group.go(joint_goal, wait=True)\n\n # Calling ``stop()`` ensures that there is no residual movement\n self.move_group.stop()\n\n # Check if pose reached\n current_joints = self.move_group.get_current_joint_values()\n goal_reached = all_close(joint_goal, current_joints, 0.01)\n print('Goal reached: {}'.format(goal_reached))\n return goal_reached\n\n def go_to_pose_goal(self):\n \"\"\"\n Planning to a Pose Goal\n \"\"\"\n # We can plan a motion for this group to a desired pose for the end-effector:\n pose_goal = geometry_msgs.msg.Pose()\n pose_goal.orientation.w = 1.0\n pose_goal.position.x = 0.4\n pose_goal.position.y = 0.1\n pose_goal.position.z = 0.4\n\n self.move_group.set_pose_target(pose_goal)\n\n # Now, we call the planner to compute the plan and execute it.\n self.move_group.go(wait=True)\n # Calling `stop()` ensures that there \n self.move_group.stop()\n # It is always good to clear your targets after planning with poses.\n # Note: there is no equivalent function for clear_joint_value_targets()\n self.move_group.clear_pose_targets()\n\n # Check if pose reached\n current_pose = self.move_group.get_current_pose().pose\n goal_reached = all_close(pose_goal, current_pose, 0.01)\n print('Goal reached: {}'.format(goal_reached))\n return goal_reached\n\n def plan_cartesian_path(self, scale=1):\n \"\"\"\n Cartesian Paths\n \"\"\"\n # You can plan a Cartesian path directly by specifying a list of waypoints\n # for the end-effector to go through. If executing interactively in a Python\n # shell, set scale = 1.0.\n\n waypoints = []\n wpose = self.move_group.get_current_pose().pose\n wpose.position.z -= scale * 0.1 # First move up (z)\n wpose.position.y += scale * 0.2 # and sideways (y)\n waypoints.append(copy.deepcopy(wpose))\n\n # Second move forward/backwards (x)\n wpose.position.x += scale * 0.1\n waypoints.append(copy.deepcopy(wpose))\n\n # Third move sideways (y)\n wpose.position.y -= scale * 0.1\n waypoints.append(copy.deepcopy(wpose))\n\n # We want the Cartesian path to be interpolated at a resolution of 1 cm\n # which is why we will specify 0.01 as the eef_step in Cartesian\n # translation. We will disable the jump threshold by setting it to 0.0,\n # ignoring the check for infeasible jumps in joint space, which is sufficient\n # for this tutorial.\n (plan, fraction) = self.move_group.compute_cartesian_path(waypoints, 0.01, 0.0)\n\n # Note: We are just planning, not asking move_group to actually move the robot\n # yet:\n return plan, fraction\n\n def display_trajectory(self, plan):\n \"\"\"\n Displaying a Trajectory\n \"\"\"\n display_trajectory = moveit_msgs.msg.DisplayTrajectory()\n display_trajectory.trajectory_start = self.robot.get_current_state()\n display_trajectory.trajectory.append(plan)\n # Publish\n self.display_trajectory_pub.publish(display_trajectory)\n\n def execute_plan(self, plan):\n \"\"\"\n Executing a Plan\n \"\"\"\n self.move_group.execute(plan, wait=True)\n\n def add_box(self, timeout=4):\n \"\"\"\n Adding Objects to the Planning Scene\n \"\"\"\n # First, we will create a box in the planning scene at the location of the left\n # finger:\n box_pose = geometry_msgs.msg.PoseStamped()\n box_pose.header.frame_id = 'panda_hand'\n box_pose.pose.orientation.w = 1.0\n # slightly above the end effector\n box_pose.pose.position.z = 0.11\n self.box_name = 'box'\n self.scene.add_box(self.box_name, box_pose, size=(0.075, 0.075, 0.075))\n return self.wait_for_state_update(box_is_known=True, timeout=timeout)\n\n\n def wait_for_state_update(\n self, box_is_known=False, box_is_attached=False, timeout=4):\n \"\"\"\n Ensuring Collision Updates Are Receieved\n \"\"\"\n start = rospy.get_time()\n seconds = rospy.get_time()\n while (seconds - start < timeout) and not rospy.is_shutdown():\n # Test if the box is in attached objects\n attached_objects = self.scene.get_attached_objects([self.box_name])\n is_attached = len(attached_objects.keys()) > 0\n\n # Test if the box is in the scene.\n # Note that attaching the box will remove it from known_objects\n is_known = self.box_name in self.scene.get_known_object_names()\n\n # Test if we are in the expected state\n if (box_is_attached == is_attached) and (box_is_known == is_known):\n return True\n\n # Sleep so that we give other threads time on the processor\n rospy.sleep(0.1)\n seconds = rospy.get_time()\n\n # If we exited the while loop without returning then we timed out\n return False\n\n def attach_box(self, timeout=4):\n \"\"\"\n Attaching Objects to the Robot\n \"\"\"\n # Next, we will attach the box to the Panda wrist. Manipulating objects\n # requires the robot be able to touch them without the planning scene reporting\n # the contact as a collision. By adding link names to the touch_links array, we\n # are telling the planning scene to ignore collisions between those links and\n # the box. For the Panda robot, we set grasping_group = 'hand'. If you are\n # using a different robot, you should change this value to the name of your end\n # effector group name.\n grasping_group = 'hand'\n touch_links = self.robot.get_link_names(group=grasping_group)\n self.scene.attach_box(self.eef_link, self.box_name, touch_links=touch_links)\n\n return self.wait_for_state_update(box_is_attached=True, box_is_known=False,\n timeout=timeout)\n\n def detach_box(self, timeout=4):\n \"\"\"\n Detaching Objects from the Robot\n \"\"\"\n self.scene.remove_attached_object(self.eef_link, self.box_name)\n\n return self.wait_for_state_update(box_is_attached=False, box_is_known=True,\n timeout=timeout)\n\n def remove_box(self, timeout=4):\n \"\"\"\n Removing Objects from the Planning Scene\n \"\"\"\n # Note: The object must be detached before we can remove it from the world\n self.scene.remove_world_object(self.box_name)\n\n return self.wait_for_state_update(\n box_is_attached=False, box_is_known=False, timeout=timeout)\n\ndef main():\n try:\n print(\"Setting up the moveit_commander ...\")\n tutorial = MoveGroupPythonInterfaceTutorialCustom()\n\n input(\"============ Press `Enter` to execute a movement using a joint state goal ...\")\n tutorial.go_to_joint_state()\n\n input(\"============ Press `Enter` to execute a movement using a pose goal ...\")\n tutorial.go_to_pose_goal()\n\n input(\"============ Press `Enter` to plan and display a Cartesian path ...\")\n cartesian_plan, fraction = tutorial.plan_cartesian_path()\n\n input(\"============ Press `Enter` to display a saved trajectory (this will replay the Cartesian path) ...\")\n tutorial.display_trajectory(cartesian_plan)\n\n input(\"============ Press `Enter` to execute a saved path ...\")\n tutorial.execute_plan(cartesian_plan)\n\n input(\"============ Press `Enter` to add a box to the planning scene ...\")\n tutorial.add_box()\n\n input(\"============ Press `Enter` to attach a Box to the Panda robot ...\")\n tutorial.attach_box()\n\n input(\"============ Press `Enter` to plan and execute a path with an attached collision object ...\")\n cartesian_plan, fraction = tutorial.plan_cartesian_path(scale=-1)\n tutorial.execute_plan(cartesian_plan)\n\n input(\"============ Press `Enter` to detach the box from the Panda robot ...\")\n tutorial.detach_box()\n\n input(\"============ Press `Enter` to remove the box from the planning scene ...\")\n tutorial.remove_box()\n\n print(\"============ Python tutorial demo complete!\")\n except rospy.ROSInterruptException:\n print('ROSInterrupt')\n return\n except (KeyboardInterrupt, EOFError):\n print('Keyboard Interrupt')\n return\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"doc/move_group_python_interface/scripts/move_group_python_interface_tutorial_custom.py","file_name":"move_group_python_interface_tutorial_custom.py","file_ext":"py","file_size_in_byte":11204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"82997679","text":"#!/usr/bin/env python\n# -*- coding: utf8\n\nimport sys\nimport urllib\nimport http.client as httplib\nimport hmac\nfrom hashlib import sha1\nfrom urllib.parse import quote\n#import logging\nimport json\nimport re\nimport time\nfrom threading import Timer\nfrom .message_sets import appmsg_sets, appmsg_sets2\nfrom sys_config import cur_config, loger\nfrom .campusApp2 import thirdsvr\nfrom ultilities import json_flat_2_tree\n\n# 适配智慧校园2.0版本\n# PYTHON3 ON Linux:\nif sys.platform == 'linux':\n import ssl\n ssl._create_default_https_context = ssl._create_unverified_context\n #Context = ssl.create_default_context()\n #Context = ssl._create_unverified_context()\nelse:\n Context = None\n\"\"\"\nhttps://www.cnblogs.com/lykbk/p/ASDFQAWQWEQWEQWEQWEQWEQWEQEWEQW.html\n问题的原因是“SSL: CERTIFICATE_VERIFY_FAILED”。\nPython 升级到 2.7.9 之后引入了一个新特性,当使用urllib.urlopen打开一个 https 链接时,会验证一次 SSL 证书。\n而当目标网站使用的是自签名的证书时就会抛出一个 urllib2.URLError: 的错误消息,\n\n解决方案包括下列两种方式:\n\n1. 使用ssl创建未经验证的上下文,在urlopen中传入上下文参数\n\nimport ssl\nimport urllib2\n\ncontext = ssl._create_unverified_context()\nprint urllib2.urlopen(\"https://www.12306.cn/mormhweb/\", context=context).read()\n2. 全局取消证书验证\n\nimport ssl\nimport urllib2\n \nssl._create_default_https_context = ssl._create_unverified_context\n \nprint urllib2.urlopen(\"https://www.12306.cn/mormhweb/\").read()\n注意:在全全局请求文件导入import ssl\n\nimport ssl\nssl._create_default_https_context = ssl._create_unverified_context\n\"\"\"\n#loger = logging.getLogger()\n#loger.basicConfig(level=logging.DEBUG, format='(%(funcName)-10s) %(message)s')\n\n\n# 通知发送类\n# TODO: 增加消息模版功能\nclass pmsgr(object):\n msgtypes = ['text', 'image', 'textcard', 'news']\n\n @classmethod\n def from_request(cls, reqdata, server=None):\n # directly from http request data generate a message\n mtype = reqdata.get('msgtype', 'text')\n if mtype == 'textcard' or mtype == 'news':\n rd = json_flat_2_tree(reqdata)\n else:\n rd = reqdata.to_dict() if hasattr(reqdata, 'to_dict') else reqdata\n msgr = cls(server, mtype)\n wxuid = rd.get('wxuserid')\n if wxuid:\n msgr.users = wxuid\n else:\n msgr.departid = rd['wxdepartid']\n msgr.content = rd['content']\n return msgr\n\n def __init__(self, server, mtype='text', *content):\n if mtype not in self.__class__.msgtypes:\n raise ValueError(\"Message type is not support!\")\n self.server = server\n self.msgtype = mtype\n self.departid = \"\"\n self.content = None\n self.users = \"\"\n if content:\n if self.msgtype == 'text':\n self.text(content[0])\n elif self.msgtype == 'image':\n self.image(content[0])\n elif self.msgtype == 'textcard':\n self.textcard(*content)\n elif self.msgtype == 'news':\n self.news(content)\n\n def _gen_pdata(self):\n pdata = {\n 'msgtype': self.msgtype,\n 'wxuserid': self.users,\n 'wxdepartid': self.departid,\n 'content': self.content\n }\n\n def text(self, content, firewall=None):\n if firewall and not firewall(content):\n raise ValueError(\"Not Allow Message!\")\n self.content = content# if isinstance(content, unicode) else content.decode('gbk')\n self.msgtype = 'text'\n\n def image(self, content, check=False):\n if check:\n if not re.search(r'^http[s]{0,1}\\:\\/\\/.*?\\..*', url):\n raise ValueError(\"Not A URL\")\n self.content= content\n self.msgtype = 'image'\n\n def textcard(self, title, description, url, check=False):\n if check:\n if not re.search(r'^http[s]{0,1}\\:\\/\\/.*?\\..*', url):\n raise ValueError(\"Not A URL\")\n self.content = dict(title=title, description=description, url=url)\n self.msgtype = 'textcard'\n\n def news(self, contents, check=False):\n def chkr(cont):\n if 'title' in cont and 'description' in cont and re.search(r'^http[s]{0,1}\\:\\/\\/.*?\\..*', cont['url'])\\\n and re.search(r'^http[s]{0,1}\\:\\/\\/.*?\\..*', picurl):\n return True\n else:\n return False\n if check:\n for part in contents:\n if not chkr(part):\n raise ValueError(\"Error Content!\")\n self.content = contents\n self.msgtype = 'news'\n\n def send2user(self, users):\n wxusers = None\n if isinstance(users, str):\n if ',' in users:\n wxusers = users.replace(',', '|')\n else:\n wxusers = users\n elif isinstance(users, (list, tuple)):\n if isinstance(users[0], str):\n wxusers = '|'.join(users)\n elif isinstance(users[0], dict):\n wxusers = '|'.join([_['wxuserid'] for _ in users])\n if wxusers is None:\n raise ValueError(\"unknown users!\")\n postdata = {\n 'msgtype': self.msgtype,\n 'wxuserid': wxusers,\n 'content': self.content\n }\n purl = self.server.handle_msger(others=dict(data=postdata))\n with app_smsg('post_msg', postdata=postdata, posturl=purl) as pm:\n wx_rtdata = pm.post()\n return wx_rtdata\n\n def send2dpt(self, departid):\n postdata = {\n 'msgtype': self.msgtype,\n 'wxdepartid': departid,\n 'content': self.content\n }\n purl = self.server.handle_msger(others=dict(data=postdata))\n with app_smsg('post_msg', postdata=postdata, posturl=purl) as pm:\n wx_rtdata = pm.post()\n return wx_rtdata\n\n\n# campus version would liter\nclass app_smsg(object):\n \"\"\"\n with wx_smsg('get_token', ('grant_type', 'appid', 'secret')) as get_token:\n rt = get_token.get()\n with wx_smsg('get_token', grant_type='', appid='', secret='') as get_token:\n work with server\n \"\"\"\n baseurl = 'open.campus.qq.com'\n post_header = {\"Content-type\": \"application/json;charset=utf-8\"}\n #post_header = {\"Content-type\": \"multipart/form-data;charset=utf-8\"}\n get_header = {'Content-Type':'text/html; charset=utf-8'}\n error_rtp = ('errcode', 'errmsg')\n server_schema = 'https'\n SecretKey = ''\n\n def __init__(self, mapname, params, baseurl='', postdata=None, posturl=''):\n # post about: postdata/post_struct_name => for self.post_maker\n if mapname.startswith('get'):\n self.mode = 0\n msgset = appmsg_sets\n else:\n self.mode = 1\n msgset = appmsg_sets2\n if mapname not in msgset:\n raise KeyError('msgset mapping name [%s] is not exists!' % mapname)\n self.SecretKey = self.__class__.SecretKey\n self.action,path,self.keys,self.ext = msgset[mapname]\n self.params = params\n # self.ext: get as return pattern; post as post_data_body_name\n self.baseurl = baseurl or self.__class__.baseurl\n self.path = ''\n self.url = ''\n if path:\n if not path.startswith('/'):\n self.path += '/' + path\n else:\n self.path += path\n if self.mode == 1:\n self.postdata = postdata or {}\n self.posturl = posturl\n\n def _url_maker(self, token, SecretKey=None):\n # token: {}\n SecretKey = SecretKey or self.SecretKey\n sign_source = '%s%s%s?' % ('GET' if self.mode == 0 else 'POST', self.baseurl, self.path)\n cpos = 0\n workd = token.copy()\n workd.update(self.params)\n workd['Timestamp'] = int(time.time())\n workd['Action'] = self.action\n ostr = '&'.join(['%s=%s' % (k, workd[k]) for k in sorted(workd)])\n print(ostr)\n self.url = self.path + '?' + ostr\n print(self.url)\n sign_source += ostr\n if self.mode == 1:\n self.postbody = json.dumps(self.postdata, separators=(',',':'))\n sign_source += '&Date=' + self.postbody\n _signcoded = base64.b16encode(hmac.new(SecretKey.encode(), sign_source.encode(), sha1).digest())\n self.sign = quote(_signcoded.lower(), safe='')\n return self.url\n\n def _rt_solve(self, rtstring):\n # check if error!\n rt = json.loads(rtstring)\n if 'code' in rt and int(rt['code']) == 0:\n return rt\n else:\n loger.warning('A Err return From Server!')\n print(rt)\n # on error\n rt['respon'] = 'failure'\n return rt\n\n def __enter__(self):\n loger.info('enter with con by baseurl: %s' % self.baseurl)\n if self.__class__.server_schema == 'https':\n self.con = httplib.HTTPSConnection(self.baseurl, timeout=5, context=Context)\n else:\n self.con = httplib.HTTPConnection(self.baseurl, timeout=5)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.con.close()\n\n def _url_file_save(self, url, fp, o=True):\n try:\n uo = urllib.URLopener()\n ufo = uo.open(url)\n data = ufo.read()\n ufo.close()\n fo = open(fp, 'w+b')\n fo.write(data)\n fo.close()\n except:\n loger.warning('not able to save data to file.')\n return None\n return fp\n\n def get(self, token, filep='', json=True):\n if self.con:\n self._url_maker(token)\n self.con.request('GET', self.url)\n resp = self.con.getresponse()\n if resp.status == 200:\n if filep:\n fo = None\n try:\n fo = open(filep, 'w+b')\n fo.write(resp.read())\n except:\n self._url_file_save(self.url, filep)\n finally:\n if fo:\n fo.close()\n loger.info('file save done')\n return filep\n else:\n # perhaps get a file some...\n rt = resp.read()\n if json:\n return self._rt_solve(rt)\n else:\n return rt\n else:\n raise RuntimeError('NO connection!')\n\n def post(self, token, json=True, posturl=''):\n self._url_maker(token)\n if self.con:\n self.con.request('POST', self.url, self.postbody.encode(), self.__class__.post_header)\n resp = self.con.getresponse()\n rt = resp.read()\n if json:\n return self._rt_solve(rt)\n return rt\n else:\n raise RuntimeError('NO connection!')\n\n def expost(self, json=True, posturl='', postdata=None):\n if not postdata:\n self.postdata = dict()\n self.postdata[self.ext] = dict()\n elif self.ext not in postdata:\n tmpd = dict()\n tmpd[self.ext] = self.postdata\n self.postdata = tmpd\n else:\n self.postdata = postdata\n td = self.postdata[self.ext]\n for k in self.keys:\n if k not in td:\n loger.warning('may be ignore key: %s' % k)\n self.posturl = posturl\n return self.post(json=json)\n\n\n# A cache version of getter\n# base on get url without timestamp and sign\n# update 20181213, a simple dict could passin an independent cache dict as user's cache\n# if we got a redis as cacher:\n# redis_cacher(object), __getitem__ <=> redis.get; get() <=> redis.get;\n# [MARK: it's good to use double cache for switch mode; it's easy to limit the cache alive and not much resource needed. we can switch cache graceful]\nclass capp_smsg(app_smsg):\n # smsg with cache\n cacheA_Mark = True\n cacherA = dict()\n cacherB = dict()\n cache = cacherA\n #cache_limit = 128 # just for an easy way\n cache_limit = cur_config.system('cache_size')\n cache_kicks = 32 # when full how many to kick\n cache_kickr = 0.5\n cache_array = [None] * cache_limit\n cpos = 0\n cache_dict_limit = 5 # user seperated dict cache\n\n clear_time = 600\n switch_time = 3600\n last_time = time.time()\n stimer = None\n\n C_LOCK = False\n lock_wait = 0.1\n lock_wcount = 10\n\n @classmethod\n def cclear(cls):\n if cls.cacheA_Mark:\n # when cacher_a works... clear cacherB\n _ = cls.cacherB\n else:\n _ = cls.cacherA\n loger.info(\"600s and clear on cache: %s with len: %d\" % ('cacherB' if cls.cacheA_Mark else 'cacherA', len(_)))\n _.clear()\n\n @classmethod\n def via_cache(cls, cpath, force=False):\n # check for switch cache\n dt = time.time() - cls.last_time\n if dt > cls.switch_time:\n loger.info(\"time to switch cacher\")\n cls.cacheA_Mark = not cls.cacheA_Mark\n cls.cache = cls.cacherA if cls.cacheA_Mark else cls.cacherB\n cls.cache_array = []\n cls.last_time = time.time()\n cls.stimer = Timer(cls.clear_time, cls.cclear)\n cls.stimer.start()\n # real job\n cpath = cls._xpath(cpath)\n if cpath in cls.cache:\n loger.info(\"%s in cache!\" % cpath)\n if cls.C_LOCK is True:\n loger.debug(\"CHECK: wait for C_LOCK!\")\n t = cls.lock_wcount\n while t > 0:\n time.sleep(cls.lock_wait)\n if cls.C_LOCK is False:\n break\n t -= 1\n loger.error(\"CHECK: wait for C_CLOCK over time!\")\n return None\n cls.cache_array.remove(cpath)\n cls.cache_array.insert(0, cpath)\n return cls.cache[cpath]\n else:\n return None\n\n @classmethod\n def store_cache(cls, cpath, data):\n cpath = cls._xpath(cpath)\n loger.info(\"%s store into cache!\" % cpath)\n if cls.cpos >= cls.cache_limit and cls.C_LOCK is False:\n loger.info(\"cache ups to limit! do short clear.\")\n _times = min(cls.cache_kicks, round(len(cls.cache) * cls.cache_kickr))\n cls.C_LOCK = True\n for x in xrange(_times):\n xpath = cls.cache_array.pop()\n try:\n cls.cache.pop(xpath)\n except KeyError:\n loger.warn(\"pop cache error with key: %s\" % xpath)\n continue\n cls.cpos = len(cls.cache) - 1\n cls.C_LOCK = False\n cls.cpos += 1\n loger.debug(\"cache size: %s!\" % cls.cpos)\n cls.cache_array.append(cpath)\n cls.cache[cpath] = data\n return True\n\n @classmethod\n def clear_cache(cls, xurl):\n try:\n cls.cache.pop(xurl)\n except KeyError:\n return False\n cls.cpos -= 1\n return True\n\n @classmethod\n def _xpath(cls, opath):\n pstr = re.sub(r'×tamp=.*?&', '&', opath)\n return pstr[:pstr.index('&sign')]\n\n # inject a cacher\n def __init__(self, mapname, params, baseurl='', postdata=None, posturl=''):\n # any thing?\n super(capp_smsg, self).__init__(mapname, params, baseurl='', postdata=None, posturl='')\n\n def get(self, filep='', urlpath='', json=True, force=False, viacache=True):\n self._url_maker(token)\n if not force:\n rt = self.__class__.via_cache(self.url)\n if rt is not None:\n if json:\n return self._rt_solve(rt)\n else:\n return rt\n if self.con:\n #turl = purl.encode('utf8') if isinstance(purl, unicode) else purl.decode('gbk').encode('utf8')\n #turl = purl.encode('utf8')\n self.con.request('GET', self.url)\n resp = self.con.getresponse()\n if resp.status == 200:\n if filep:\n fo = None\n try:\n fo = open(filep, 'w+b')\n fo.write(resp.read())\n except:\n self._url_file_save(purl, filep)\n finally:\n if fo:\n fo.close()\n loger.info('file save done')\n return filep\n else:\n # perhaps get a file some...\n rt = resp.read()\n if not json:\n return rt\n rt_json = self._rt_solve(rt)\n if viacache and rt_json['code'] == 0 and 'data' in rt_json:\n self.__class__.store_cache(purl, rt)\n return rt_json\n else:\n raise RuntimeError('NO connection!')","sub_path":"tschool/app_msger2.py","file_name":"app_msger2.py","file_ext":"py","file_size_in_byte":17131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"534460568","text":"#!/usr/bin/env python\r\n\r\n# This script is for automatically calculating the SSO inclination corresponding to an altitude, given the rate of change of the RAAN of ~ 1 deg/day. Assuming a circular orbit (e=0)\r\n#\r\n# Reference: SMAD III eq. (6-19) p.143, Satellite Orbits (Montenbruck, Gill) p.50 \r\n# Author vjl\r\n# Creation date: 2017-02-16\r\n# Changelog: 2017-02-17: - Added functionality: outputs i from h input\r\n#\t\t\t\t\t\t - Added alt,i plot\r\n#\r\n#\r\n#\r\n#\r\n#\r\n\r\n\r\n# Module imports\r\n\r\nimport math as m\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\n# Define constants\r\n\r\nRe = 6371\t\t \t\t\t\t\t\t\t\t\t\t# Earth Radius (km)\r\nMe = 5.972*10**24\t\t\t\t\t\t\t\t\t\t# Earth mass (kg)\r\nJ2 = 0.00108263 \t\t\t\t\t\t\t\t\t# J2 geopotential coefficient\r\nG = 6.673*10**(-20)\t\t\t\t\t\t\t\t \t \t# Gravitational constant (km3/(kg*s2))\r\n\r\nRAANdot = 0.9856\t\t\t\t\t\t\t \t# RAAN variation for SSO (deg/day)\r\ne = 0\t\t\t\t\t\t\t\t\t\t\t\t\t# eccentricity\r\n\r\nalt = int(input (\"Orbit altitude (km): \"))\t\t\t\t# altitude input (km)\r\n#alt = 500 \r\n\r\na = alt+Re \t\t\t\t\t\t\t\t\t\t\t\t# Semi-major axis (km)\r\nn = m.degrees(m.sqrt(G*Me/(a**3)))*24*3600\t\t\t\t# Mean motion (deg/day)\r\n\r\ni = m.degrees(m.acos(RAANdot/(-1.5*n*J2*(Re**2/a**2))))\t# Inclination given SSO (deg)\r\n\r\ni_anyorbit = m.radians(12)\r\nRAANdot_anyorbit = -(3/2)*n*J2*Re**2/(a**2)*m.cos(i)\r\n\r\n#i = m.degrees(m.acos(RAANdot/(-1.5*m.degrees(m.sqrt(G*Me))*24*3600*J2*(Re**2)*a**(-7/2))))\r\n\r\nprint(i)\r\n\r\nprint(RAANdot_anyorbit)\r\n\r\n\r\n# Plotting altitude versus inclination for SSO\r\n\r\n# alt_array = np.arange(300,1001,1)\r\n# a_array = np.arange(Re+300,Re+1001,1)\r\n# i_array = np.full(len(alt_array),0)\r\n# n_array = np.full(len(alt_array),0)\r\n\r\n#print(alt_array[200])\r\n#print(a_array[200])\r\n\r\n# for j in range(0, len(alt_array)):\r\n\t\r\n# \ti_array[j] = m.degrees(m.acos(RAANdot/(-1.5*m.degrees(m.sqrt(G*Me))*24*3600*J2*(Re**2)*int(a_array[j])**(-7/2))))\r\n# \t#n_array[j] = m.degrees(m.sqrt(G*Me/(int(a_array[j])**3)))*24*3600\t\r\n# \t#print(i_array[j])\r\n\r\n\r\n# #print(i_array[200])\r\n# #print(n_array[200])\r\n\r\n# plt.plot(alt_array,i_array)\r\n\r\n# plt.grid(b=None, which='major', axis='both')\r\n# plt.minorticks_on()\r\n# plt.xticks(np.arange(min(alt_array), max(alt_array)+1, 50))\r\n# plt.yticks(np.arange(min(i_array), max(i_array)+1, 0.25))\r\n# plt.xlabel(\"Altitude (km)\",fontsize=\"large\")\r\n# plt.ylabel(\"Inclination (deg)\",fontsize=\"large\")\r\n# plt.tick_params(labelsize=\"large\") \r\n\r\n# plt.show()\r\n\r\n\r\n","sub_path":"SSO.py","file_name":"SSO.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"413173310","text":"from django.conf.urls import url, include\nfrom core.api.v1 import views\nfrom rest_framework_nested import routers\n\n\nrouter = routers.SimpleRouter(trailing_slash=False)\nrouter.register(r'publisher', views.PublisherViewSet)\nrouter.register(r'content', views.ContentViewSet)\nrouter.register(r'entered_source', views.EnteredSourceViewSet)\nrouter.register(r'workspace', views.WorkspaceViewSet, base_name='workspace')\n\npublisher_router = routers.NestedSimpleRouter(router, r'publisher',\n lookup='publisher',\n trailing_slash=False)\npublisher_router.register(r'url', views.PublisherPublisherURLViewSet,\n base_name='publisher-url')\npublisher_router.register(r'entered_source', views.PublisherEnteredSourceViewSet,\n base_name='publisher-entered-source')\n\nentered_source_router = routers.NestedSimpleRouter(router, r'entered_source',\n lookup='entered_source',\n trailing_slash=False)\nentered_source_router.register(r'content', views.EnteredSourceContentViewSet,\n base_name='entered-source-content')\n\nurlpatterns = [\n url(r'^', include(router.urls)),\n url(r'^', include(publisher_router.urls)),\n url(r'^', include(entered_source_router.urls)),\n url(r'user', views.UserCreateView.as_view(), name='user'),\n url(r'^search$', views.SearchView.as_view(), name='search'),\n url(r'^similar$', views.LDAView.as_view(), name='similar'),\n url(r'^search/stats$', views.SearchStatsView.as_view(), name='search_stats')\n]\n","sub_path":"core/api/v1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"550666336","text":"from redis import StrictRedis,ConnectionPool\n\nurl = 'redis://:wei8899@localhost:6379/0'\npool = ConnectionPool.from_url(url=url)\n\nredis = StrictRedis(connection_pool=pool)\n\n\n# 返回并删除键名为list列表的最后一个元素\n# 如果列表为空则会一直处于阻塞等待\n# timeout:超时等待时间,0为一直等待\n# 返回元组类型\nprint(redis.brpop('list',timeout=0))\n\n# 将键名为list的列表尾元素删除\n# 并将其添加到键名为list1的列表头部\n# 返回该元素\nprint(redis.rpoplpush('list','list1'))\n","sub_path":"Redis/list_02.py","file_name":"list_02.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"30860722","text":"from fetch_training_data import *\nfrom initial_variables import *\nfrom initialize_weights import *\nfrom filter_dataset import *\nfrom fetch_test import *\nimport math\n\n# filter_data()\n\n# pattern = fetch_data()\n# (\n# MAX_CLUSTERS,\n# VEC_LEN,\n# INPUT_PATTERNS,\n# INPUT_TESTS,\n# MIN_ALPHA,\n# MAX_ITERATIONS,\n# SIGMA,\n# INITIAL_LEARNING_RATE,\n# INITIAL_RADIUS\n# ) = initialize_variables(pattern)\n\n\n# w = random_weights(pattern,MAX_CLUSTERS,VEC_LEN)\n# tests = fetch_tests()\n# print(len(tests[3]))\n# print(MAX_CLUSTERS,VEC_LEN,INPUT_PATTERNS)\n# print(training_labels)\n\nclass SOM_Class:\n def __init__(self, vectorLength, maxClusters, numPatterns, numTests, minimumAlpha, weightArray, maxIterations,\n sigma, initialAlpha, initialSigma):\n \"\"\"\n :param vectorLength:\n :param maxClusters:\n :param numPatterns:\n :param numTests:\n :param minimumAlpha:\n :param weightArray:\n :param maxIterations:\n :param sigma:\n :param initialAlpha:\n :param initialSigma:\n \"\"\"\n self.mVectorLen = vectorLength\n self.mMaxClusters = maxClusters\n self.mNumPatterns = numPatterns\n self.mNumTests = numTests\n self.mMinAlpha = minimumAlpha\n self.mAlpha = initialAlpha\n self.d = []\n self.w = weightArray\n self.maxIterations = maxIterations\n self.sigma = SIGMA\n self.mInitialAlpha = initialAlpha\n self.mInitialSigma = sigma\n return\n\n\n\n\n def compute_input(self, vectorArray, vectorNumber):\n \"\"\"\n :param vectorArray:\n :param vectorNumber:\n :return:\n \"\"\"\n # print(len(w),len(vectorArray))\n self.d = [0.0] * self.mMaxClusters\n # print(self.mMaxClusters,self.mVectorLen)\n for i in range(self.mMaxClusters):\n for j in range(self.mVectorLen):\n self.d[i] = self.d[i] + math.pow((self.w[i][j] - vectorArray[vectorNumber][j]), 2)\n self.d[i]=math.sqrt(self.d[i])\n # print(vectorNumber,i,j)\n # print(self.d)\n # print(self.d)\n\n\n # print(self.d)\n return\n\n\n\n def get_minimum(self, nodeArray): # NodeArray holding the distances of selected instance with each node\n minimum = 0\n foundNewMinimum = False\n done = False\n\n while not done:\n foundNewMinimum = False\n for i in range(self.mMaxClusters):\n if i != minimum:\n if nodeArray[i] < nodeArray[minimum]:\n minimum = i\n foundNewMinimum = True\n\n if foundNewMinimum == False:\n done = True\n\n return minimum\n\n def update_weights(self, vectorNumber, dMin, patternArray):\n\n # Adjust weight of winning neuron\n for l in range(self.mVectorLen):\n self.w[dMin][l] = self.w[dMin][l] + (\n self.mAlpha * 1 * (patternArray[vectorNumber][l] - self.w[dMin][l]))\n # Now search for neighbors\n dis = 0.00\n # print('MAX :' + str(self.mMaxClusters))\n for i in range(self.mMaxClusters):\n for j in range(self.mVectorLen):\n if (i != dMin):\n dis = dis + math.pow((self.w[dMin][j] - self.w[i][j]), 2)\n else:\n continue\n dis = math.sqrt(dis)\n # Consider as neighbor if distance is less than sigma\n\n if (dis < self.sigma):\n # Neighborhood function\n h = math.exp(-1 * (pow(dis, 2)) / (2 * (self.sigma ** 2)))\n\n # once accepted as neighbor update its weight\n for x in range(self.mVectorLen):\n self.w[i][x] = self.w[i][x] + (self.mAlpha * h * (patternArray[vectorNumber][x] - self.w[i][x]))\n\n return\n\n def training(self, patternArray):\n print(\"Entered training\")\n iterations = 0\n while (iterations != self.maxIterations):\n iterations = iterations + 1\n for i in range(self.mNumPatterns):\n self.compute_input(patternArray, i)\n dMin = self.get_minimum(self.d)\n self.update_weights(i, dMin, patternArray)\n\n if self.mAlpha > 0.01:\n self.mAlpha = self.mInitialAlpha /((1 + (iterations / self.maxIterations)))\n print(\"Learning Rate:\"+str(self.mAlpha))\n\n if self.sigma > -1*(self.mInitialSigma):\n self.sigma = self.mInitialSigma / ((1 + (iterations / self.maxIterations)))\n print(\"Radius :\" + str(self.sigma))\n print(\"Iterations\" + str(iterations) + '\\n')\n\n\n return\n\n def classify(self, tests, map_dict , train_lab_dict):\n threshold = 0.5\n sum_dict = dict()\n prototypeVector = list()\n numInstances = dict() # Dictionary to hold number of instances mapped to the neuron\n for key in map_dict:\n c = 0\n for x in map_dict[key]:\n c = c + 1\n numInstances[key] = c\n print(numInstances)\n\n # Calculating averages of labels mapped to each neuron\n for key in train_lab_dict:\n sum_list = [sum(x) / numInstances[key] for x in zip(*train_lab_dict[key])]\n if key not in sum_dict:\n sum_dict[key] = []\n sum_dict[key].append(sum_list)\n else:\n sum_dict[key].append(sum_list)\n\n print(sum_dict)\n v = list() # v vector\n for i in range(self.mMaxClusters):\n v.append([0.0] * len(training_labels[0]))\n print(v)\n # for deterministic prediction , set threshold = 0.5: if > 0.5 then 1 else 0\n for key in sum_dict:\n numNeuron = key\n for x in sum_dict[key]:\n v[numNeuron] = x\n print(v)\n\n for i in range(len(v)):\n for j in range(len(training_labels[0])):\n if (v[i][j] >= threshold):\n v[i][j] = 1\n else:\n v[i][j] = 0\n print(v)\n return v\n # In v vector the vector at position say(x) represents the threshold calculated average of labels of instances for that neuron number\n\n # pick up test instances\n # print(\"Classification results :\")\n # for i in tests: # i is test instance\n # matchFlag = 0\n # for x in v:\n # if i == x:\n # matchFlag = 1\n # ind = v.index(x) # ind is the neuron number to which the test should n=be mapped\n # print(i, end=' ')\n # print(\": falls under category\" + str(ind))\n #\n # if (matchFlag == 0):\n # print(\"Test Instance\", end=' ')\n # print(i, end=\" \")\n # print(\"has no match\")\n\n def print_results(self, patternArray, testArray):\n # Printing the clusters created\n\n map_dict = dict() # dictn to hold mapped vwctors along with respective neurons\n train_lab_dict = dict()\n print(\"Clusters for training input: \\n\")\n for i in range(self.mNumPatterns):\n map_list = list() # list to hold mapped instances to a particular neuron\n train_lab_list = list()\n self.compute_input(patternArray, i)\n dMin = self.get_minimum(self.d)\n\n print(\"Vector (\")\n for j in range(self.mVectorLen):\n map_list.append(patternArray[i][j])\n print(str(patternArray[i][j]) + \", \")\n for k in range(len(training_labels[0])):\n train_lab_list.append(training_labels[i][k])\n if dMin not in train_lab_dict:\n train_lab_dict[dMin] = []\n train_lab_dict[dMin].append(train_lab_list)\n else:\n train_lab_dict[dMin].append(train_lab_list)\n\n print(\") fits into category \" + str(dMin) + \"\\n\")\n if dMin not in map_dict:\n map_dict[dMin] = []\n map_dict[dMin].append(map_list)\n else:\n map_dict[dMin].append(map_list)\n\n # Print weight matrix.\n\n print(\"------------------------------------------------------------------------\\n\")\n for i in range(self.mMaxClusters):\n print(\"Weights for Node \" + str(i) + \" connections:\\n\")\n print(\" \")\n for j in range(self.mVectorLen):\n print(\"{:03.3f}\".format(self.w[i][j]) + \", \")\n\n print(\"\\n\")\n\n print(\"Dictionary - Maping of instances to respective neurons :\")\n print(map_dict)\n\n return map_dict, train_lab_dict\n\n def post_train(self,testArray,v):\n # Print post-training tests.\n post_test_labels = [[] for i in range(self.mNumTests)]\n print(\"------------------------------------------------------------------------\\n\")\n print(\"Categorized test input:\\n\")\n for i in range(self.mNumTests):\n self.compute_input(testArray, i)\n\n dMin = self.get_minimum(self.d)\n if dMin is not None:\n post_test_labels[i]=v[dMin]\n else:\n post_test_labels[i]=[]\n print(\"Vector (\")\n for j in range(self.mVectorLen):\n print(str(testArray[i][j]) + \", \")\n\n print(\") fits into category \" + str(dMin) + \"\\n\")\n return post_test_labels\n\n def evaluate(self, predicted_labels, testing_labels):\n p = 0\n #Testing precision\n for x in range(len(predicted_labels)):\n if predicted_labels[x] == testing_labels[x]:\n p+=1\n\n\n return float(float(p)/len(predicted_labels))\n\n\n\n\nif __name__ == '__main__':\n # filter_data()\n pattern = fetch_data()\n (\n MAX_CLUSTERS,\n VEC_LEN,\n INPUT_PATTERNS,\n INPUT_TESTS,\n MIN_ALPHA,\n MAX_ITERATIONS,\n SIGMA,\n INITIAL_LEARNING_RATE,\n INITIAL_RADIUS\n ) = initialize_variables(pattern)\n w = random_weights(pattern, MAX_CLUSTERS, VEC_LEN)\n tests = fetch_tests()\n som = SOM_Class(VEC_LEN, MAX_CLUSTERS, INPUT_PATTERNS, INPUT_TESTS, MIN_ALPHA, w, MAX_ITERATIONS, SIGMA,\n INITIAL_LEARNING_RATE, INITIAL_RADIUS)\n som.training(pattern)\n map_dict, train_lab_dict = som.print_results(pattern, tests)\n v = som.classify(tests, map_dict , train_lab_dict)\n predicted_labels = som.post_train(tests,v)\n print(\"Predicted labels : \" + str(len(predicted_labels)))\n print(predicted_labels)\n\n for x in range(len(predicted_labels)):\n for y in range(LABEL_COUNT):\n predicted_labels[x][y] = float(predicted_labels[x][y])\n print(\"Predicted labels : \" + str(len(predicted_labels)))\n print(predicted_labels)\n print(\"Testing actual labels :\" + str(len(testing_labels)))\n print(testing_labels)\n precision = som.evaluate(predicted_labels,testing_labels)\n print(precision)\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":"som_mll2.py","file_name":"som_mll2.py","file_ext":"py","file_size_in_byte":11136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"615941167","text":"import os, glob, shutil\nimport numpy as np\nfrom PIL import Image\nfrom xlrd import open_workbook\nimport cv2\nimport json\nimport random\nimport pycocotools.mask as maskUtils\n\nclass MyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, bytes):\n return str(obj, encoding='utf-8')\n elif isinstance(obj, np.uint8):\n return int(obj)\n return json.JSONEncoder.default(self, obj)\n\nLABEL_DICT = {\n 1: [\"地板\"],\n 2: [\"墙\"],\n 3: [\"门\"],\n 4: [\"窗户\"],\n 5: [\"窗帘\"],\n 6: [\"壁画\"],\n 7: [\"墙面附属物\"],\n 8: [\"天花板\"],\n 9: [\"吊扇\"],\n 10: [\"床\"],\n 11: [\"桌子\"],\n 12: [\"柜子\"],\n 13: [\"椅子\", \"凳子\"],\n 14: [\"沙发\"],\n 15: [\"灯\", \"吊灯\"],\n 16: [\"其他家具\"],\n 17: [\"家电\"],\n 18: [\"人物\"],\n 19: [\"猫\"],\n 20: [\"狗\"],\n 21: [\"植物\"]\n}\nCATE_DICT = {}\nfor k, v in LABEL_DICT.items():\n for k_, v_ in zip(len(v)*[k, ], v):\n CATE_DICT[v_] = k_\n\n\nif __name__ == '__main__':\n root = '/Users/dyy/Desktop/cvpr13'\n img_dir = os.path.join(root, 'images')\n\n workbook = open_workbook(os.path.join(root, 'colors.xls'))\n sheet = workbook.sheet_by_index(0)\n nrows = sheet.nrows\n COLOR_TO_INS = {}\n for row in range(nrows):\n line = sheet.row_values(row)\n ins_name = line[0].strip()\n color = line[1].strip()[:-1]\n COLOR_TO_INS[color] = ins_name\n\n # imgs = glob.glob(os.path.join(root, 'mask/*.png'))\n # val = random.sample(imgs, 49)\n # train = set(imgs) - set(val)\n # with open(os.path.join(root, 'train.txt'), 'w') as f:\n # for path in train:\n # f.writelines(path)\n # f.write('\\n')\n # with open(os.path.join(root, 'val.txt'), 'w') as f:\n # for path in val:\n # f.writelines(path)\n # f.write('\\n')\n\n dataset_type = 'train'\n with open(os.path.join(root, '{}.txt'.format(dataset_type)), 'r') as f:\n imgs = f.readlines()\n imgs = [img.strip() for img in imgs]\n\n save_dir = os.path.join(root, 'data', dataset_type)\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n\n json_out = {\"images\": [], \"annotations\": []}\n image_id = 1\n segmentation_id = 1\n for idx, img in enumerate(imgs):\n name = img.split('/')[-1].replace('.png', '.jpg')\n print(idx, name)\n img = np.array(Image.open(img))\n h, w, _ = img.shape\n img_info = {\n \"id\": image_id,\n \"file_name\": name,\n \"width\": w,\n \"height\": h,\n }\n json_out['images'].append(img_info)\n shutil.copy(os.path.join(img_dir, name),\n os.path.join(save_dir, name))\n\n colors = []\n for i in range(h):\n for j in range(w):\n c = tuple(img[i, j, :])\n if c not in colors:\n colors.append(c)\n for color in colors:\n key = ''.join(str(color).split(' '))\n ins_name = COLOR_TO_INS[key]\n for k, v in CATE_DICT.items():\n if ins_name.startswith(k):\n cate_id = v\n ins_mask = cv2.inRange(img, lowerb=np.array(color), upperb=np.array(color))\n ins_mask = (ins_mask / 255.).astype(np.uint8)\n if ins_name == '植物' and ins_mask.sum() < 1000:\n continue\n # print(name, ins_mask.sum())\n # save_path = os.path.join(save_dir, name)\n # if not os.path.exists(save_path):\n # os.makedirs(save_path)\n # cv2.imwrite(os.path.join(save_path, '{}.png'.format(ins_name)), ins_mask*255)\n\n binary_mask = maskUtils.encode(np.asfortranarray(ins_mask))\n area = maskUtils.area(binary_mask)\n bbox = maskUtils.toBbox(binary_mask)\n ann_info = {\n \"id\": segmentation_id,\n \"image_id\": image_id,\n \"category_id\": cate_id,\n \"iscrowd\": 0,\n \"area\": area.tolist(),\n \"bbox\": bbox.tolist(),\n \"segmentation\": binary_mask\n }\n json_out[\"annotations\"].append(ann_info)\n segmentation_id += 1\n image_id += 1\n\n with open(os.path.join(root, 'data/{}.json'.format(dataset_type)), 'w') as f:\n json.dump(json_out, f, cls=MyEncoder)","sub_path":"dyy_tools/process_cvpr_ins.py","file_name":"process_cvpr_ins.py","file_ext":"py","file_size_in_byte":4391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"511022738","text":"import tqdm\nimport numpy as np\nfrom shapely.geometry import Polygon\n\nTP = 0\nTOT_PRED = 0\nTOT_GT = 0\n\ndef measure_TP(pred_bbox, gt_bbox, pred_transcript, gt_transcript):\n\n pred_bbox = np.array(pred_bbox)\n gt_bbox = np.array(gt_bbox)\n\n pred_bbox = pred_bbox.reshape([-1, 4, 2])\n gt_bbox = gt_bbox.reshape([-1, 4, 2])\n global TP \n global TOT_GT\n global TOT_PRED\n \n TOT_GT += len(gt_bbox)\n TOT_PRED += len(pred_bbox)\n\n for gt_b, gt_t in zip(gt_bbox, gt_transcript):\n gt_quad = Polygon(gt_b).convex_hull\n gt_area = gt_quad.area\n\n for pred, pred_trans in zip(pred_bbox, pred_transcript):\n pred_quad = Polygon(pred).convex_hull\n\n if gt_quad.intersects(pred_quad):\n inter = gt_quad.intersection(pred_quad).area\n iou = inter / (gt_area + pred_quad.area - inter)\n\n if iou > 0.5:\n if gt_t==pred_trans or gt_t==\"###\" or gt_t==\"\":\n TP += 1\n break\n\nfor i in tqdm.tqdm(range(1,776+1)):\n gt_file_path = '/workspace/str/detset/annotations/test/gt_img_' + str(i) + '.txt'\n pred_file_path = '/workspace/str/myicdar/traingt/' + str(i) + '.txt'\n\n try:\n gt_file = open(gt_file_path)\n pred_file = open(pred_file_path)\n except:\n print(gt_file_path)\n print(pred_file_path)\n \n pred_bbox = []\n gt_bbox = []\n pred_transcript = []\n gt_transcript = []\n\n for line in gt_file.readlines():\n line_lst = line.split(',')\n if line_lst[-1] =='###\\n':\n continue\n gt_bbox.append(line_lst[:8])\n gt_transcript.append(line_lst[-1])\n\n for line in pred_file.readlines():\n line_lst = line.split(',')\n if line_lst[9] =='###\\n':\n continue\n pred_bbox.append(line_lst[:8])\n pred_transcript.append(line_lst[-1])\n \n measure_TP(pred_bbox,gt_bbox,pred_transcript,gt_transcript)\n\nprecision = TP / TOT_PRED\nrecall = TP / TOT_GT\nf1_score = 2 * precision * recall / (precision + recall + 1e-16)\n\nprint('precision',precision)\nprint('recall',recall)\nprint('f1_score',f1_score)","sub_path":"mmocr/demo/measure.py","file_name":"measure.py","file_ext":"py","file_size_in_byte":2148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"283739349","text":"def list_factor(num):\n l = []\n tmp = int(num**0.5)\n \n for i in range(2, tmp + 1):\n if num % i == 0:\n l.append(i)\n if i != num // i:\n l.append(num // i)\n print(l)\n\nx = int(input())\nlist_factor(x)","sub_path":"PythonEx/Ex3/factor.py","file_name":"factor.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"152412142","text":"###\n# Copyright 2011 Diamond Light Source 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###\n\nfrom uk.ac.diamond.scisoft.analysis import SDAPlotter as _plotter,\\\n PlotServiceProvider as _provider, RMIClientProvider as _rmiprovider\n\ntry:\n from uk.ac.diamond.scisoft.analysis.rcp.plotting import RMIPlotWindowManger as _manager\nexcept:\n ## This code has special handling because the RCP classes may not be available\n import sys\n print >> sys.stderr, \"Could not import Plot Window Manager\"\n _manager = None\n\nfrom jycore import _wrapin\n\nplot_clear = _plotter.clearPlot\nplot_export = _plotter.exportPlot\n\n@_wrapin\ndef plot_line(*arg, **kwarg):\n _plotter.plot(*arg, **kwarg)\n\n@_wrapin\ndef plot_addline(*arg, **kwarg):\n _plotter.addPlot(*arg, **kwarg)\n\n@_wrapin\ndef plot_updateline(*arg, **kwarg):\n _plotter.updatePlot(*arg, **kwarg)\n\n@_wrapin\ndef plot_stack(*arg, **kwarg):\n _plotter.stackPlot(*arg, **kwarg)\n\n@_wrapin\ndef plot_updatestack(*arg, **kwarg):\n _plotter.updateStackPlot(*arg, **kwarg)\n\n@_wrapin\ndef plot_image(*arg, **kwarg):\n _plotter.imagePlot(*arg, **kwarg)\n\n@_wrapin\ndef plot_images(*arg, **kwarg):\n _plotter.imagesPlot(*arg, **kwarg)\n\n@_wrapin\ndef plot_surface(*arg, **kwarg):\n _plotter.surfacePlot(*arg, **kwarg)\n\n@_wrapin\ndef plot_points2d(*arg, **kwarg):\n _plotter.scatter2DPlot(*arg, **kwarg)\n\n@_wrapin\ndef plot_updatepoints2d(*arg, **kwarg):\n _plotter.scatter2DPlotOver(*arg, **kwarg)\n\n@_wrapin\ndef plot_points3d(*arg, **kwarg):\n _plotter.scatter3DPlot(*arg, **kwarg)\n@_wrapin\ndef plot_updatepoints3d(*arg, **kwarg):\n _plotter.scatter3DPlotOver(*arg, **kwarg)\n\nplot_createaxis = _plotter.createAxis\nplot_renameactivexaxis = _plotter.renameActiveXAxis\nplot_renameactiveyaxis = _plotter.renameActiveYAxis\n\n@_wrapin\ndef plot_scanforimages(*arg, **kwarg):\n _plotter.scanForImages(*arg, **kwarg)\n\nfrom uk.ac.diamond.scisoft.analysis.plotserver import AxisOperation as _axisop\naxis_top = _axisop.TOP\naxis_bottom = _axisop.BOTTOM\naxis_left = _axisop.LEFT\naxis_right = _axisop.RIGHT\n\nfrom jyio import h5manager as _h5mgr\n\ndef plot_viewnexustree(name, tree):\n if not isinstance(tree, _h5mgr):\n import sys #@Reimport\n print >> sys.stderr, \"Only tree from loadnexus works for now\"\n return\n# import jyhdf5io._tojavatree as _tojtree\n# tree = _tojtree(tree)\n _plotter.viewHDF5Tree(name, tree.gettree())\n\nplot_volume = _plotter.volumePlot\n\nfrom jybeans import parameters as _jyparams\nfrom jybeans import guibean as _jyguibean\n\nfrom jyroi import _roi_wrap, _create_list, _jroi, _roi_list\n\ndef _wrap_gui_bean(jb):\n jb.setWarn(False)\n if _jyparams.roi in jb:\n jb[_jyparams.roi] = _roi_wrap(jb[_jyparams.roi])\n if _jyparams.roilist in jb:\n jl = jb[_jyparams.roilist]\n if jl:\n l = _create_list(jl[0])\n for r in jl:\n l.append(_roi_wrap(r))\n else:\n l = None\n jb[_jyparams.roilist] = l\n jb.setWarn(True)\n\ndef _unwrap_gui_bean(ob, nb):\n for k in ob:\n v = ob[k]\n if k == _jyparams.roi:\n if v is not None and not isinstance(v, _jroi):\n v = v._jroi()\n elif k == _jyparams.roilist:\n ov = v\n if isinstance(ov, _roi_list):\n v = ov._jroilist()\n nb[k] = v\n return nb\n\ndef plot_getbean(name):\n jb = _plotter.getGuiBean(name)\n if jb is not None:\n _wrap_gui_bean(jb)\n return jb\n\ndef plot_setbean(name, bean):\n _plotter.setGuiBean(name, _unwrap_gui_bean(bean, _jyguibean()))\n\ndef plot_getdatabean(name):\n jdb = _plotter.getDataBean(name)\n if jdb is not None:\n jgb = jdb.getGuiParameters()\n if jgb is not None:\n _wrap_gui_bean(jgb)\n return jdb\n\ndef plot_setdatabean(name, bean):\n gb = bean.getGuiParameters()\n _plotter.setDataBean(name, _unwrap_gui_bean(gb, gb))\n\nplot_getguinames = _plotter.getGuiNames\n\nplot_orders = { \"none\": _plotter.IMAGEORDERNONE, \"alpha\": _plotter.IMAGEORDERALPHANUMERICAL, \"chrono\": _plotter.IMAGEORDERCHRONOLOGICAL}\n\ndef setremoteport(rmiport=0, **kwargs):\n '''Sets the RMI Connection Port to the rmiport arg'''\n _rmiprovider.getInstance().setPort(rmiport)\n _provider.setPlotService(None)\n if _manager is not None:\n _manager.clearManager()\n \n\nclass window_manager(object):\n '''Wrapper for IPlotWindowManager in SDA. Allows opening, duplicating and\n obtaining list of existing views'''\n def __init__(self):\n '''\n Create a new wrapper for the window manager, not intended for \n use outside the jyplot module\n '''\n pass\n \n def open_duplicate_view(self, view_name):\n '''\n Open a duplicate view of an existing view name. View name cannot be null.\n The view's Data and Gui Bean are duplicated so each view has it's own\n copy.\n Returns the name of the newly opened view.\n '''\n return _manager.getManager().openDuplicateView(view_name)\n\n def open_view(self, view_name=None):\n '''\n Open a new view with the given view_name, or if None open a new view\n with a new, unique name.\n Returns the name of the newly opened view.\n '''\n return _manager.getManager().openView(view_name)\n\n def get_open_views(self):\n '''\n Return a list of all the open plot views.\n '''\n return _manager.getManager().getOpenViews()\n\nif _manager is None:\n plot_window_manager = None\nelse:\n plot_window_manager = window_manager()\n\n","sub_path":"contributions-actors/uk.ac.diamond.python.service/scripts/scisoftpy/jython/jyplot.py","file_name":"jyplot.py","file_ext":"py","file_size_in_byte":6055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"412239729","text":"#!/usr/local/bin/python\n\n__author__ = 'pdch'\n\n\"\"\"\nread_pdbcomp.py\n\nReturn composition and general information about a pdb in pdbfolder.\nReturns a tuple of four objects (tuple, tuple, list of tuples, list of tuples)\n1. nres: pdbid, nresidues\n2. amins: pdbid, frequency of each of aminoacids\n3. helix: pdbid, helixid, helix type, helix length\n4. sheet: pdbid, sheetid, num strands, num residues in sheet\n\"\"\"\n\n__usage__ = \"nres, amins, helix, sheet = read_pdbcomp.py pdb_id\"\n\n\nimport pickle\nimport re\n\npdbfolder = \"pdbfiles\"\nfext = \"pdb\"\n\ndef getcomp(pdbid):\n \"\"\"\n Reads pdb file from pdbfolder and analyzes data with regex.\n \"\"\"\n\n amin_acids = pickle.load(open(\"amin_acids.p\", 'rb'))\n amin_count = {el: 0 for el in amin_acids}\n helix_class = pickle.load(open(\"helix_class.p\", 'rb'))\n\n\n pdbfile = (\"%s/%s%s\" % (pdbfolder, pdbid, \".pdb\"))\n fid = open(pdbfile, \"r\")\n\n nresidues = 0\n sheet_nres = 0\n am_list = []\n hx_list = []\n sh_list = []\n\n for ln in fid:\n # General info and Amino acid composition\n if ln.startswith(\"SEQRES\"):\n lnl = ln.strip().split()\n if int(lnl[1]) == 1:\n nresidues += int(lnl[3])\n for amin in lnl[4:]:\n if amin in amin_count:\n amin_count[amin] += 1\n\n # Helix composition\n if ln.startswith(\"HELIX\"):\n lnl = ln.strip().split()\n helix_id = int(lnl[1]) # THIS IS S.NO: change to ID later\n helix_len = int(lnl[-1])\n cl = int(re.sub(\"[^0-9]\", \"\", lnl[9]))\n if cl in helix_class:\n helix_cl = helix_class[cl]\n else:\n helix_cl = 'Unknown'\n hx_list.append((pdbid, helix_id, helix_cl, helix_len))\n\n # Sheet composition\n if ln.startswith(\"SHEET\"):\n strand_id = int(ln[7:10].strip())\n strand_num = int(ln[14:16].strip())\n sheet_nres += int(ln[33:37].strip()) - int(ln[22:26].strip()) + 1\n if strand_id == strand_num:\n sheet_id = ln[11:14].strip()\n sh_list.append((pdbid, sheet_id, strand_num, sheet_nres))\n sheet_nres = 0\n\n nr_tuple = (pdbid, nresidues)\n\n for amin in amin_acids:\n am_list.append(amin_count[amin])\n am_tuple = tuple(am_list)\n\n # Test the results\n #print nr_tuple\n #print am_tuple\n #print hx_list\n #print sh_list\n\n return nr_tuple, am_tuple, hx_list, sh_list\n","sub_path":"read_pdbcomp.py","file_name":"read_pdbcomp.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"409241603","text":"# Django non-secret settings for streamux.\n\nfrom settings_private import *\n\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n ('David Anderson', 'dave@natulte.net'),\n)\n\nMANAGERS = ADMINS\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'Europe/Paris'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'fr-fr'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# Absolute path to the directory that holds media.\n# Example: \"/home/media/media.lawrence.com/\"\nMEDIA_ROOT = SITE_ROOT + '/media'\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash if there is a path component (optional in other cases).\n# Examples: \"http://media.lawrence.com\", \"http://example.com/media/\"\nMEDIA_URL = ''\n\n# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a\n# trailing slash.\n# Examples: \"http://foo.com/media/\", \"/media/\".\nADMIN_MEDIA_PREFIX = '/admin_media/'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.load_template_source',\n 'django.template.loaders.app_directories.load_template_source',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n)\n\nROOT_URLCONF = 'streamux.urls'\n\nTEMPLATE_DIRS = (\n SITE_ROOT + '/templates',\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'streamux.radio'\n)\n\nAUTHENTICATION_BACKENDS = (\n 'radio.ae_auth.AeAuthBackend',\n)\n\n# The URL for logging in.\nLOGIN_URL = '/login'\n\n# If no explicit next is provided, redirect to the site root.\nLOGIN_REDIRECT_URL = '/'\n\n# Daemon configuration\nDAEMON_LOGFILE = SITE_ROOT + '/logs/daemon.log'\nDAEMON_PIDFILE = SITE_ROOT + '/daemon.pid'\n\n# Music directories\nMUSIC_DIR = SITE_ROOT + '/music/actual'\nMUSIC_INCOMING = SITE_ROOT + '/music/incoming'\nMUSIC_FAILED = SITE_ROOT + '/music/failed'\n\n# Liquidsoap root\nLIQ_DIR = SITE_ROOT + '/liquidsoap'\n","sub_path":"streamux/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"237162556","text":"#!/usr/bin/env python3\nimport rospy\nfrom std_msgs.msg import Float32\nfrom sensor_msgs.msg import JointState\nfrom simple_pid import PID\nimport numpy as np\nfrom flir_ptu.ptu import PTU\nfrom vision_utils.logger import get_logger\nimport time\nlogger = get_logger()\n\ndef tune_gain(Ku, Tu, mode=\"clasic\"):\n if mode == \"clasic\":\n # clasic PID\n print(\"Clasic\")\n kp = 0.6 * Ku\n ki = 1.2 * Ku / Tu\n kd = 3 * Ku * Tu / 40\n elif mode == \"noovershoot\":\n print(\"No Over Shoot\")\n # No overshoot\n kp = Ku / 5\n ki = (2/5)*Ku / Tu\n kd = Ku * Tu / 15\n else:\n print(\"invaild mdoe\")\n\n print(\"kp: \", kp, \"ki: \", ki, \"kd: \", kd)\n return [kp, ki, kd]\n\nx = PTU(\"192.168.1.110\", 4000, debug=False)\nx.connect()\n\n# x.reset()\n# x.wait()\n\nx.set_speed_mode()\nx.wait()\n\n# set upper speed limit\nx.pan_speed_max(11448)\nx.wait()\n\n# # read accel\n# x.pan_accel()\n# x.wait()\n\n\n\n# x.tilt_speed(2000)\n\n# x.pan_speed(2000)\n# x.wait()\n\n\n# x.set_position_mode()\n# x.wait()\n\n# x.tilt_angle(-25)\n# x.wait()\n\nX = np.linspace(-np.pi*4, np.pi*4, num=4000)\n\n\n# numpy sine values\ny = np.sin(X) * 180/np.pi\nprint(np.max(y))\nprint(np.min(y))\nprint(y[0])\n\nposition = [0.0, 0.0]\n\npan_angle = 200\ntilt_angle = 200\n\n\ndef state_cb(msg):\n global position\n if msg.name == [\"ptu_panner\", \"ptu_tilter\"]:\n position = msg.position\n\n\ndef angle_cb(msg):\n global pan_angle\n pan_angle = msg.data\n # print(\"pan angle: \", angle)\n\n\ndef tilt_angle_cb(msg):\n global tilt_angle\n tilt_angle = msg.data\n # print(\"tilt angle: \", tilt_angle)\n\n\nrospy.init_node(\"PTU_node\")\nrospy.Subscriber(\"/joint_states\", JointState, state_cb)\nrospy.Subscriber(\"/ref_pan_angle\", Float32, angle_cb)\nrospy.Subscriber(\"/ref_tilt_angle\", Float32, tilt_angle_cb)\npub = rospy.Publisher(\"/angle_ref\", Float32, queue_size=1)\n\nku = 1100\ntu = 5.2\n\n[kp,ki,kd] = tune_gain(ku,tu,\"noovershoot\")\n\npid_pan = PID(kp, ki-30, kd-200)\n# pid_tilt = PID(100, 0, 0, setpoint=0)\n\nv_pan = position[0]*180/np.pi\n# v_tilt = position[1]*180/np.pi\n\npid_pan.output_limits = (-11448, 11448)\n# pid_tilt.output_limits = (-30, 90)\n\n# rate = rospy.Rate(50) # 50hz\npid_pan.sample_time = 0.02\n# pid_tilt.sample_time = 0.02\ncounter = 0\nwhile not rospy.is_shutdown():\n if counter < len(y):\n ref = y[counter]\n counter += 1\n error = ref - v_pan\n # print(\"Error: \", error)\n if abs(error) < 3:\n v_pan = ref\n \n pid_pan.setpoint = ref\n control_pan = pid_pan(v_pan)\n \n # print(\"Control: \", control_pan)\n # print(\"Control: \",int(control_pan))\n # control_tilt = pid_tilt(v_tilt)\n if abs(error) >= 3:\n x.pan_speed(int(control_pan))\n pub.publish(ref)\n else:\n x.pan_speed(0)\n pub.publish(ref)\n\n # x.tilt_speed(int(control_tilt))\n \n \n # pid_tilt.setpoint = tilt_angle\n\n v_pan = position[0]*180/np.pi \n # v_tilt = position[1]*180/np.pi\n\n\nx.stream.close()\n","sub_path":"ptu_speed_control_sin.py","file_name":"ptu_speed_control_sin.py","file_ext":"py","file_size_in_byte":2942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"593267086","text":"\"\"\"\nMissionaries and Cannibals Problem\n Uninformed Search Approach\n\n DEPTH-FIRST SEARCH ALGO.\n *--------------------------*\n\nAuthor: Matthew Farrugia-Roberts\n\"\"\"\n\nfrom state import State\n\ndef main():\n # how many on starting side?\n initial_state = State(3, 3, 1)\n # | | |\n # missionaries --* | |\n # cannibals --------* |\n # the boat ------------*\n\n states_prev = {initial_state: None}\n state_stack = [(initial_state, 0)]\n while state_stack and not state_stack[-1][0].is_goal():\n state, depth = state_stack.pop()\n print('.' * depth + \"expanding:\", state)\n for successor_state in state.successors():\n if successor_state in states_prev:\n continue\n state_stack.append((successor_state, depth+1))\n states_prev[successor_state] = state\n\n if state_stack:\n goal, cost = state_stack[-1]\n print(\"goal found:\", goal)\n path = reconstruct_path(states_prev, goal)\n print(\"path:\", path)\n else:\n print(\"no path found...\")\n\n\ndef reconstruct_path(prev_dict, end_state):\n path = []\n state = end_state\n while prev_dict[state] is not None:\n path.append(state)\n state = prev_dict[state]\n path.append(state)\n return path[::-1]\n\nif __name__ == '__main__':\n main()\n","sub_path":"Chexers/webinar_code/mc-3/mc-3.py","file_name":"mc-3.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"340272408","text":"from datetime import datetime\nfrom threading import Thread\nfrom random import randint, random\nfrom time import sleep as wait\nimport logging\n\nfrom helpers.redis_set_up import connection\n\nlogging.basicConfig(filename=\"worker_logs.txt\", level=logging.INFO)\n\n\nclass EventListener(Thread):\n def __init__(self, _connection):\n Thread.__init__(self)\n self.connection = _connection\n\n def run(self):\n pub_sub = self.connection.pubsub()\n pub_sub.subscribe([\"users\", \"spam\"])\n\n for item in pub_sub.listen():\n if item['type'] == 'message':\n logging.info(f\"[{datetime.now()}]: {item['data']}\")\n\n\nclass Worker(Thread):\n def __init__(self, _connection, delay):\n Thread.__init__(self)\n self.connection = _connection\n self.delay = delay\n\n def run(self):\n while True:\n _, message_id = self.connection.brpop(\"queue:\")\n if message_id:\n self.connection.hset(f\"message:{message_id}\", \"status\", \"checking\")\n\n sender_id, consumer_id = self.connection.hmget(f\"message:{message_id}\", [\"sender_id\", \"consumer_id\"])\n self.connection.hincrby(f\"user:{sender_id}\", \"queue\", -1)\n self.connection.hincrby(f\"user:{sender_id}\", \"checking\", 1)\n\n wait(self.delay)\n is_spam = random() > 0.5\n pipeline = self.connection.pipeline(True)\n pipeline.hincrby(f\"user:{sender_id}\", \"checking\", -1)\n\n if is_spam:\n username, *rest = self.connection.hmget(f\"user:{sender_id}\", [\"login\"])\n pipeline.zincrby(\"spam:\", 1, f\"user:{username}\")\n pipeline.hset(f\"message:{message_id}\", \"status\", \"blocked\")\n pipeline.hincrby(f\"user:{sender_id}\", \"blocked\", 1)\n\n message_text, *rest = self.connection.hmget(f\"message:{message_id}\", [\"text\"])\n pipeline.publish(\"spam\", f\"User {username} sent spam message: '{message_text}'\")\n else:\n pipeline.hset(f\"message:{message_id}\", \"status\", \"sent\")\n pipeline.hincrby(f\"user:{sender_id}\", \"sent\", 1)\n pipeline.sadd(f\"sentto:{consumer_id}\", message_id)\n\n pipeline.execute()\n else:\n print(\"[error]: queue is empty\")\n\n\ndef main():\n listener = EventListener(connection)\n listener.start()\n\n handlers_count = 3\n\n for _ in range(handlers_count):\n worker = Worker(connection, randint(1, 5))\n worker.start()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Lab2/main_logic/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"485743497","text":"import matplotlib.mlab as mlab\nimport matplotlib.pyplot as plt \n\n#load data first\n\nplt.hist(np.array(vec_label), facecolor='blue', bins='auto', histtype='bar')\nplt.xlabel('Label')\nplt.ylabel('Number')\nplt.title(r'$\\mathrm{Histogram of Labels}$')\nplt.grid(True)\n\nprint(np.unique(np.array(vec_label)))\naxes = plt.gca()\naxes.set_xlim([33,40])\n#axes.set_ylim([0,150000])\n\nplt.savefig('label_hist.png')\nplt.figure()\n","sub_path":"simple_plot.py","file_name":"simple_plot.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"330999052","text":"import os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn import metrics\nfrom sklearn.metrics import (\n accuracy_score,\n auc,\n classification_report,\n confusion_matrix,\n f1_score,\n plot_confusion_matrix,\n roc_auc_score,\n roc_curve,\n)\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV, train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.tree import DecisionTreeClassifier\n\nimport utils\n\nos.environ[\"PATH\"] += (\n os.pathsep\n + \"C:/Users/saverio/Desktop/Data Mining/DataMiningProject/venvv/Lib/site-packages/graphviz/bin\"\n)\n\n\ndef draw_confusion_matrix(Clf, X, y):\n titles_options = [\n (\"Confusion matrix, without normalization\", None),\n (\"Decision Tree Confusion matrix\", \"true\"),\n ]\n\n for title, normalize in titles_options:\n disp = plot_confusion_matrix(Clf, X, y, cmap=\"OrRd\", normalize=normalize)\n disp.ax_.set_title(title)\n\n plt.show()\n\n\ndef report(results, n_top=3):\n for i in range(1, n_top + 1):\n candidates = np.flatnonzero(results[\"rank_test_score\"] == i)\n for candidate in candidates:\n print(\"Model with rank: {0}\".format(i))\n print(\n \"Mean validation score: {0:.3f} (std: {1:.3f})\".format(\n results[\"mean_test_score\"][candidate],\n results[\"std_test_score\"][candidate],\n )\n )\n print(\"Parameters: {0}\".format(results[\"params\"][candidate]))\n print(\"\")\n\n\ndef load_data(path):\n df = utils.load_tracks(path, outliers=False, buckets=\"discrete\")\n # feature to reshape\n label_encoders = dict()\n column2encode = [\n (\"album\", \"comments\"),\n (\"album\", \"favorites\"),\n (\"album\", \"listens\"),\n (\"album\", \"type\"),\n (\"artist\", \"comments\"),\n (\"artist\", \"favorites\"),\n (\"track\", \"duration\"),\n (\"track\", \"comments\"),\n (\"track\", \"favorites\"),\n (\"track\", \"language_code\"),\n (\"track\", \"license\"),\n (\"track\", \"listens\"),\n ]\n\n for col in column2encode:\n le = LabelEncoder()\n df[col] = le.fit_transform(df[col])\n label_encoders[col] = le\n print(df.info())\n return df\n\n\ndef tuning_param(df, target1, target2):\n\n # split dataset train and set\n attributes = [col for col in df.columns if col != (target1, target2)]\n X = df[attributes].values\n y = df[target1, target2]\n\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, stratify=y, test_size=0.25\n )\n print(X_train.shape, X_test.shape)\n\n # tuning hyperparam with randomize search\n\n # This has two main benefits over an exhaustive search:\n\n # A budget can be chosen independent of the number of parameters and possible values.\n\n # Adding parameters that do not influence the performance does not decrease efficiency.\n # RANDOM\n print(\"Parameter Tuning: \\n\")\n\n # tuning parameters with random search\n print(\"Search best parameters: \\n\")\n param_list = {\n \"max_depth\": [None] + list(np.arange(2, 50)),\n \"min_samples_split\": [2, 5, 10, 15, 20, 30, 50, 100, 150],\n \"min_samples_leaf\": [1, 2, 5, 10, 15, 20, 30, 50, 100, 150],\n \"criterion\": [\"gini\", \"entropy\"],\n }\n\n clf = DecisionTreeClassifier(\n criterion=\"gini\", max_depth=None, min_samples_split=2, min_samples_leaf=1\n )\n\n random_search = RandomizedSearchCV(clf, param_distributions=param_list, n_iter=100)\n random_search.fit(X, y)\n report(random_search.cv_results_, n_top=3)\n\n\ndef tuning_param_gridsearch(df, target1, target2):\n\n # split dataset train and set\n attributes = [col for col in df.columns if col != (target1, target2)]\n X = df[attributes].values\n y = df[target1, target2]\n\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, stratify=y, test_size=0.20\n )\n print(X_train.shape, X_test.shape)\n clf = DecisionTreeClassifier(\n criterion=\"gini\", max_depth=None, min_samples_split=2, min_samples_leaf=1\n )\n\n def report(results, n_top=3):\n for i in range(1, n_top + 1):\n candidates = np.flatnonzero(results[\"rank_test_score\"] == i)\n for candidate in candidates:\n print(\"Model with rank: {0}\".format(i))\n print(\n \"Mean validation score: {0:.3f} (std: {1:.3f})\".format(\n results[\"mean_test_score\"][candidate],\n results[\"std_test_score\"][candidate],\n )\n )\n print(\"Parameters: {0}\".format(results[\"params\"][candidate]))\n print(\"\")\n\n param_list = {\n \"max_depth\": [None] + list(np.arange(2, 50)),\n \"min_samples_split\": list(np.arange(2, 50)),\n \"min_samples_leaf\": list(np.arange(2, 50)),\n \"criterion\": [\"gini\", \"entropy\"],\n }\n\n grid_search = GridSearchCV(clf, param_grid=param_list)\n grid_search.fit(X, y)\n clf = grid_search.best_estimator_\n print(report(grid_search.cv_results_, n_top=3))\n\n\ndef build_model(\n df, target1, target2, min_samples_split, min_samples_leaf, max_depth, criterion\n):\n\n # split dataset train and set\n attributes = [col for col in df.columns if col != (target1, target2)]\n X = df[attributes].values\n y = df[target1, target2]\n\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.20, stratify=y\n )\n\n print(X_train.shape, X_test.shape)\n # build a model\n\n clf = DecisionTreeClassifier(\n criterion=criterion,\n max_depth=max_depth,\n min_samples_split=min_samples_split,\n min_samples_leaf=min_samples_leaf,\n )\n clf.fit(X_train, y_train)\n\n # value importance\n for col, imp in zip(attributes, clf.feature_importances_):\n print(col, imp)\n\n # Apply the decision tree on the training set\n print(\"Apply the decision tree on the training set: \\n\")\n y_pred = clf.predict(X_train)\n print(\"Accuracy %s\" % accuracy_score(y_train, y_pred))\n print(\"F1-score %s\" % f1_score(y_train, y_pred, average=None))\n\n print(classification_report(y_train, y_pred))\n\n confusion_matrix(y_train, y_pred)\n\n # Apply the decision tree on the test set and evaluate the performance\n print(\"Apply the decision tree on the test set and evaluate the performance: \\n\")\n y_pred = clf.predict(X_test)\n\n print(\"Accuracy %s\" % accuracy_score(y_test, y_pred))\n print(\"F1-score %s\" % f1_score(y_test, y_pred, average=None))\n print(classification_report(y_test, y_pred))\n confusion_matrix(y_test, y_pred)\n\n # ROC Curve\n from sklearn.preprocessing import LabelBinarizer\n\n lb = LabelBinarizer()\n lb.fit(y_test)\n lb.classes_.tolist()\n\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n by_test = lb.transform(y_test)\n by_pred = lb.transform(y_pred)\n for i in range(4):\n fpr[i], tpr[i], _ = roc_curve(by_test[:, i], by_pred[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n roc_auc = roc_auc_score(by_test, by_pred, average=None)\n print(roc_auc)\n\n plt.figure(figsize=(8, 5))\n for i in range(4):\n plt.plot(\n fpr[i],\n tpr[i],\n label=\"%s ROC curve (area = %0.2f)\" % (lb.classes_.tolist()[i], roc_auc[i]),\n )\n\n plt.plot([0, 1], [0, 1], \"k--\")\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel(\"False Positive Rate\", fontsize=20)\n plt.ylabel(\"True Positive Rate\", fontsize=20)\n plt.tick_params(axis=\"both\", which=\"major\", labelsize=22)\n plt.legend(loc=\"lower right\", fontsize=14, frameon=False)\n plt.show()\n\n # Model Accuracy, how often is the classifier correct?\n draw_confusion_matrix\n print(\"Accuracy:\", metrics.accuracy_score(y_test, y_pred))\n # confusion matrix\n print(\"\\033[1m\" \"Confusion matrix\" \"\\033[0m\")\n\n draw_confusion_matrix(clf, X_test, y_test)\n\n print()\n\n for col, imp in zip(attributes, clf.feature_importances_):\n print(col, imp)\n\n top_n = 10\n feat_imp = pd.DataFrame(columns=[\"columns\", \"importance\"])\n for col, imp in zip(attributes, clf.feature_importances_):\n feat_imp = feat_imp.append(\n {\"columns\": col, \"importance\": imp}, ignore_index=True\n )\n print(feat_imp)\n\n feat_imp.sort_values(by=\"importance\", ascending=False, inplace=True)\n feat_imp = feat_imp.iloc[:top_n]\n\n feat_imp.plot(\n title=\"Top 10 features contribution\",\n x=\"columns\",\n fontsize=8.5,\n rot=15,\n y=\"importance\",\n kind=\"bar\",\n colormap=\"Pastel1\",\n )\n plt.show()\n\n\ntracks = load_data(\"data/tracks.csv\")\n# tuning_param(tracks, \"album\", \"type\")\n# tuning_param_gridsearch(tracks, \"album\", \"type\")\nbuild_model(tracks, \"album\", \"type\", 100, 100, 8, \"entropy\")\n# build_model(tracks, \"album\", \"type\", 2, 1, 20, \"entropy\")\n","sub_path":"decision_tree_sav_oldsplitting.py","file_name":"decision_tree_sav_oldsplitting.py","file_ext":"py","file_size_in_byte":8872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"472153073","text":"from collections import defaultdict \n \ndef oneAway(str1, str2):\n diff_count = 0\n if abs(len(str1) - len(str2)) > 1:\n return False\n elif len(str1) == len(str2):\n for i in range(min(len(str1), len(str2))):\n if str1[i] != str2[i]:\n diff_count += 1\n if diff_count > 1:\n return False\n else:\n return True\n else:\n for i in range(min(len(str1), len(str2))):\n if str1[i] != str2[i]:\n diff_count += 1\n if diff_count == 0:\n return True\n elif diff_count == 1:\n if len(str1) == len(str2) or str1[-1] == str2[-1]:\n return True\n else:\n return False\n\nprint(oneAway('pale','ple'))\nprint(oneAway('pales','pale'))\nprint(oneAway('pale','bale'))\nprint(oneAway('pale','bake'))\nprint(oneAway('test','test'))\nprint(oneAway('test','testtest'))","sub_path":"strings/one_away.py","file_name":"one_away.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"649014056","text":"DATA = {\n \"organization\": {\n \"name\": \"Renham Industries\",\n \"shared_comments\": False,\n \"url\": \"https://company.zendesk.com/api/v2/organizations/556.json\",\n \"organization_fields\": {\n \"severity\": None\n },\n \"created_at\": \"2011-11-26T00:52:51Z\",\n \"tags\": [\"helloIT\", \"have-you-tried-turning-it-off-and-on-again\"],\n \"updated_at\": \"2011-11-26T00:52:51Z\",\n \"domain_names\": [],\n \"details\": None,\n \"notes\": None,\n \"group_id\": None,\n \"external_id\": None,\n \"id\": 556,\n \"shared_tickets\": False\n }\n}\n","sub_path":"tests/data/org_get.py","file_name":"org_get.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"390277439","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('chatbot', '0002_auto_20161021_0938'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='aiml_config',\n options={'verbose_name': 'Setup', 'verbose_name_plural': 'Setups'},\n ),\n migrations.AlterField(\n model_name='aiml_config',\n name='aiml_files',\n field=models.ManyToManyField(related_name='AIML_File', verbose_name=b'Chatbot Setups', to='chatbot.aiml_file', blank=True),\n ),\n migrations.AlterField(\n model_name='aiml_config',\n name='title',\n field=models.CharField(default=b'', max_length=100),\n ),\n migrations.AlterField(\n model_name='aiml_file',\n name='text_file',\n field=models.TextField(default=b'', verbose_name=b'Plaintext Content', blank=True),\n ),\n ]\n","sub_path":"chatbot/migrations/0003_auto_20161021_1046.py","file_name":"0003_auto_20161021_1046.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"86590510","text":"n, m = map(int, input().split())\ndiv = m//n\nINF = 10**18\nans = -INF\nfor i in reversed(range(1, div+1)):\n if m % i != 0:\n continue\n if ans < i:\n ans = i\n break\nprint(ans)\n","sub_path":"Python_codes/p03241/s393275764.py","file_name":"s393275764.py","file_ext":"py","file_size_in_byte":197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"488219058","text":"\"\"\"\nGitHub API Application: Custom Exception Classes\n\"\"\"\n\nclass GitHubApiException(Exception):\n\n def __init__(self, status_code):\n if status_code == 403:\n message = \"Rate limit reached. Please wait a minute and try again.\"\n else:\n message = f\"HTTP Status Code was: {status_code}.\"\n\n super().__init__(message)","sub_path":"pyworkshop/2_intermediate_python/chapter4/gh_exceptions.py","file_name":"gh_exceptions.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"359914741","text":"class Solution(object):\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n # Time Complexity: O(n)\n # Space Complexity: O(1)\n\n # Strings of length less than 2 can't have repeating characters\n if len(s) < 2:\n return len(s)\n\n # i and j keep track of the indices of\n # the first and last characters of the substring\n i = j = 0\n\n # maxLength keeps track of the longest substring encountered so far\n maxLength = 0\n while j < len(s):\n # Checks if the character has been seen before\n if s[j] not in s[i:j]:\n j += 1\n else:\n # If we find a repeating character, check if\n # the substring formed so far is the longest one\n if j - i > maxLength:\n maxLength = j - i\n # Move the starting pointer 1 past the index of\n # where the previous instance of the repeated character\n # was found\n i = s.index(s[j], i) + 1\n if j - i > maxLength:\n maxLength = j - i\n return maxLength","sub_path":"lengthOfLongestSubstring.py","file_name":"lengthOfLongestSubstring.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"386925840","text":"\"\"\"Models representing Physical items.\"\"\"\nfrom bodega_core.models import Item, Stockroom\nfrom django.db import models\n\n\nclass BrikStockroom(Stockroom):\n \"\"\"For Prod briks, we only need the pxe_server_ip and identifiable name.\"\"\"\n\n name = models.CharField(max_length=255, null=False, blank=False)\n pxe_server_ip = models.CharField(max_length=15, null=False, blank=False)\n\n\nclass PhysicalCdmNode(Item):\n \"\"\"A physical CDM node's static infromation.\n\n Only serial number is required as we will use this to derive the\n information required to manufacture the node and bootstrap the\n cluster. The plan is to use Racktables api that IT manages to\n derive this information.\n \"\"\"\n\n serial_number = models.CharField(max_length=255, null=False, blank=False)\n stockroom = models.ForeignKey('BrikStockroom',\n on_delete=models.CASCADE,\n null=False,\n help_text='Stockroom for this brik')\n","sub_path":"lab/bodega/bodega_physical/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"609194723","text":"import requests\n\nfrom django import forms\nfrom django.conf import settings\n\nfrom django_comments.forms import CommentForm\nfrom django_markdown.widgets import MarkdownWidget\n\nfrom core.utils import get_client_ip\nfrom error_posts.models import ErrorPost\n\n\nclass ErrorPostForm(forms.ModelForm):\n recaptcha = forms.CharField()\n\n class Meta:\n model = ErrorPost\n fields = ['exception_type', 'error_message', 'traceback',\n 'how_to_reproduce', 'django_version']\n\n def __init__(self, *args, **kwargs):\n self.request = kwargs.pop('request', None)\n super().__init__(*args, **kwargs)\n initial = kwargs.get('initial')\n if initial:\n for field in initial:\n if field in self.fields:\n self.fields[field].widget.attrs['readonly'] = True\n if settings.DEBUG:\n self.fields['recaptcha'].required = False\n\n def clean_recaptcha(self):\n code = self.cleaned_data['recaptcha']\n if settings.RECAPTCHA_SECRET_KEY:\n ip_address = get_client_ip(self.request)\n response = requests.post('https://www.google.com/recaptcha/api/siteverify',\n data={'secret': settings.RECAPTCHA_SECRET_KEY,\n 'response': code,\n 'remoteip': ip_address})\n res = response.json()\n if not res['success']:\n raise forms.ValidationError('Invalid Recaptcha')\n return code\n\n def save(self, data_came_from, commit=True):\n instance = super(ErrorPostForm, self).save(commit=False)\n instance.data_came_from = data_came_from\n\n if commit:\n instance.save()\n return instance\n\n\nclass CommentFormWithMarkDown(CommentForm):\n comment = forms.CharField(widget=MarkdownWidget())\n","sub_path":"error_posts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"571434388","text":"#! /usr/bin/env python\n\nimport rospy\nimport sensor_msgs.point_cloud2 as pc2\nfrom sensor_msgs.msg import PointCloud2\nimport tf\n\nclass PointcloudGenerator:\n\n def __init__(self):\n\n rospy.init_node('pointcloud_generator')\n pub_cloud = rospy.Publisher(\"~/cloud\", PointCloud2, queue_size=10)\n\n r = rospy.Rate(10)\n pcloud = PointCloud2()\n cloud = [[1.0,-0.5,0],[2.0,-0.5,0],[3.0,-0.5,0],\n [1.0,0.5, 0],[2.0,0.5, 0],[3.0, 0.5,0]]\n\n while not rospy.is_shutdown():\n\n pcloud = pc2.create_cloud_xyz32(pcloud.header, cloud)\n pcloud.header.frame_id = \"base_footprint\"\n pub_cloud.publish(pcloud)\n r.sleep()\n\nif __name__ == \"__main__\":\n try:\n s = PointcloudGenerator()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"src/capra_filters/scripts/pointcloud_generator.py","file_name":"pointcloud_generator.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"595456194","text":"\n# coding: utf-8\n\n# In[24]:\n\n\nfrom SEResNeXt import SEResNeXt, init_trained_weights\nimport torch\nimport numpy as np\nfrom torch.autograd import Variable\nfrom DataSet import Dataset\nimport my_snip.metrics as metrics\nfrom my_snip.clock import TrainClock, AvgMeter\nfrom my_snip.config import MultiStageLearningRatePolicy\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom TorchDataset import TorchDataset\nfrom torch.utils.data import DataLoader\nimport time\n\nfrom tensorboardX import SummaryWriter\n\n\n# In[25]:\ngpu_id = 3\nnum_workers = 8\nminibatch_size = 16\nnum_epoch = 16\n\nValAccuracy = []\n\nlearning_rate_policy = [[3, 0.01],\n [4, 0.001],\n [4, 0.0001],\n [7, 0.00002]\n ]\nget_learing_rate = MultiStageLearningRatePolicy(learning_rate_policy)\n\n\nmodel_path = './training_models/se_resnext101_32x4d.pt'\nsave_path = './net6.pt'\nbest_path = './training_models/se_resnext101_32x4d_exp6.pt'\nlog_dir = './logs/se_resnext101_32x4d_exp6'\njson_path = log_dir + '/' + 'all_scalars.json'\nwriter = SummaryWriter(log_dir)\n\n\n\n# In[19]:\n\n\ndef adjust_learning_rate(optimzier, epoch):\n #global get_lea\n lr = get_learing_rate(epoch)\n for param_group in optimizer.param_groups:\n\n param_group['lr'] = lr\n\n\n\n# In[20]:\n\n\nds_train = TorchDataset('train')\nds_val = TorchDataset('validation')\n\ndl_train = DataLoader(ds_train, batch_size=minibatch_size, shuffle=True, num_workers=num_workers)\ndl_val = DataLoader(ds_val, batch_size=minibatch_size, shuffle=True, num_workers=num_workers)\n\n\nstep_per_epoch = ds_train.instance_per_epoch // minibatch_size\n\n\n# In[14]:\n\n\nnet = SEResNeXt(101, num_class=80)\ninit_trained_weights(net, model_path)\n\nnet.cuda(gpu_id)\n\n\n# In[22]:\n\n\ncriterion = nn.CrossEntropyLoss().cuda(gpu_id)\n\noptimizer = optim.SGD(net.parameters(), lr = 0.01, momentum = 0.9, weight_decay=1e-4)\n#optimizer = optim.Adam(net.parameters(), lr = 0.01, weight_decay = 1e-4)\nclock = TrainClock()\n\nud_loss_m = AvgMeter('ud_loss')\naccuracy_m = AvgMeter('top-1-accuracy')\ntop3_accuracy_m = AvgMeter('top-3-accuracy')\ndata_time_m = AvgMeter('Reading Batch Data')\nbatch_time_m = AvgMeter('Batch time')\n\nfor epoch_i in range(num_epoch):\n\n net.train()\n print('Epoch {} starts'.format(epoch_i))\n clock.tock()\n epoch_time = time.time()\n\n adjust_learning_rate(optimizer, clock.epoch)\n\n ud_loss_m.reset()\n accuracy_m.reset()\n top3_accuracy_m.reset()\n data_time_m.reset()\n batch_time_m.reset()\n\n start_time = time.time()\n\n for i, mn_batch in enumerate(dl_train):\n\n #if i % 50 == 0:\n # print(i)\n #print(i)\n #if i > 201:\n # break\n data_time_m.update(time.time() - start_time)\n\n clock.tick()\n data = mn_batch['data'].type(torch.FloatTensor)\n label = mn_batch['label'].type(torch.LongTensor).squeeze_()\n\n inp_var = Variable(data).cuda(gpu_id)\n label_var = Variable(label).cuda(gpu_id)\n\n optimizer.zero_grad()\n\n pred = net.forward(inp_var)\n\n #print(label_var.size())\n ud_loss = criterion(pred, label_var)\n\n acc, t3_acc = metrics.torch_accuracy(pred.data, label_var.data, (1, 3))\n\n writer.add_scalar('Train/un_decay_loss', ud_loss.data[0], clock.step)\n writer.add_scalar('Trian/top_acc', acc[0], clock.step)\n writer.add_scalar('Trian/top_3_acc', t3_acc[0], clock.step)\n\n ud_loss_m.update(ud_loss.data[0], inp_var.size(0))\n accuracy_m.update(acc[0], inp_var.size(0))\n\n top3_accuracy_m.update(t3_acc[0], inp_var.size(0))\n\n ud_loss.backward()\n\n optimizer.step()\n\n batch_time_m.update(time.time() - start_time)\n start_time = time.time()\n\n if clock.minibatch % 200 == 0:\n print(\"step {} :\".format(clock.minibatch), ud_loss.data[0], acc[0], t3_acc[0])\n print('data time: {} mins, batch time: {} mins'.format(data_time_m.mean, batch_time_m.mean))\n print('Epoch{} time: {} mins. {} mins to run'.format(clock.epoch, (start_time - epoch_time)/60,\n (batch_time_m.mean * (step_per_epoch - clock.minibatch) / 60)))\n\n print('Epoch {} Finished! Lasting {} mins'.format(clock.epoch, (start_time - epoch_time)/60))\n print('ud_loss: {}, accuracy: {}, top-3-accuracy {}'.format(ud_loss_m.mean, accuracy_m.mean, top3_accuracy_m.mean))\n\n writer.add_scalar('Time/Epoch-time', (start_time - epoch_time)/60)\n writer.add_scalar('Train/Epoch-un_decay_loss', ud_loss_m.mean, clock.epoch)\n writer.add_scalar('Trian/Epoch-top_acc', accuracy_m.mean, clock.epoch)\n writer.add_scalar('Trian/Epoch-top_3_acc', top3_accuracy_m.mean, clock.epoch)\n\n torch.save(net.state_dict(), save_path)\n\n if clock.epoch % 1 == 0:\n\n net.eval()\n print('Begin validation!')\n\n ud_loss_m.reset()\n accuracy_m.reset()\n top3_accuracy_m.reset()\n for i, mn_batch in enumerate(dl_val):\n\n # if i > 401:\n # break\n data = mn_batch['data'].type(torch.FloatTensor)\n label = mn_batch['label'].type(torch.LongTensor).squeeze_()\n inp_var = Variable(data).cuda(gpu_id)\n label_var = Variable(label).cuda(gpu_id)\n\n\n pred = net.forward(inp_var)\n\n ud_loss = criterion(pred, label_var)\n\n acc, t3_acc = metrics.torch_accuracy(pred.data, label_var.data, (1, 3))\n\n ud_loss_m.update(ud_loss.data[0], inp_var.size(0))\n accuracy_m.update(acc[0], inp_var.size(0))\n top3_accuracy_m.update(t3_acc[0], inp_var.size(0))\n\n print('Validation Done!')\n print('ud_loss: {}, accuracy: {}, top-3-accuracy {}'.format(ud_loss_m.mean, accuracy_m.mean, top3_accuracy_m.mean))\n\n writer.add_scalar('Val/Epoch-un_decay_loss', ud_loss_m.mean, clock.epoch)\n writer.add_scalar('Val/Epoch-top_acc', accuracy_m.mean, clock.epoch)\n writer.add_scalar('Val/Epoch-top_3_acc', top3_accuracy_m.mean, clock.epoch)\n\n ValAccuracy.append(accuracy_m.mean)\n if accuracy_m.mean >= max(ValAccuracy):\n torch.save(net.state_dict(), best_path)\n\n\n print('Best top-1-accuracy: {}, saved in {}'.format(max(ValAccuracy), best_path))\n\n# torch.save(net.state_dict(), './net.pt')\nwriter.export_scalars_to_json(json_path)\nwriter.close()\n\nprint('Training Finished')\ntorch.save(net.state_dict(), save_path)\n\nprint('model saved in {}'.format(save_path))\nprint('Best top-1-accuracy: {}, saved in {}'.format(max(ValAccuracy), best_path))\n","sub_path":"torch_code/code_for_train/single_gpu_train_seresnext.py","file_name":"single_gpu_train_seresnext.py","file_ext":"py","file_size_in_byte":6567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"514283379","text":"# how to handle excpetion in python - an exeption is an error in your cade that will stop the execution\n\n\"\"\" errors are 2 types 1) syntax error 2) runtime errors ( example dividing by 0, file not present,index out of range or import error etc)\nsyntax errors cannot be handled instead runtime errors can be handled \"\"\"\n\n# example with no existing file\n\"\"\"\nfo=open(\"File.txt\") >>> File \"C:/Users/u6017127/PycharmProjects/AutomationTraining.py/venv/ExceptionHandling.py\", \nthis command gives an error as file do not exist, to handle this runtime error you need to use \"try,except\" the code is:\"\"\"\n\ntry: # try to run this block of code\n fo=open(\"file.txt\")\n print(fo.read())\n fo.close()\nexcept Exception as e: # if there is an exception print error\n print(e) # >>>>> [Errno 2] No such file or directory: 'file.txt'\n\n\n# exception handling for known errors \"NameError\",\"Type Error\",\"FileNotFoundError\",\"ZeroDivisionError\"\n\ntry:\n print(a)\nexcept NameError: # we can handle exception this way as we know that in case varible a do notexist the error is NameError type\n print(\"variable not defined\")\n\ntry:\n print(\"no error on this line\")\n import fabric # remember whenever getting exception the rest of code in try block will not execute\n print(4/0)\nexcept ZeroDivisionError: # we can handle exception this way as we know that in case varible a do not exist the error is ZeroDivisionError type\n print(\"you cannot divede by 0\")\nexcept ModuleNotFoundError: # we can handle exception this way as we know that in case module a do not exist the error is ModuleNotFoundError type\n print(\"your module do notexist\")\nexcept Exception as e: # you can add extra layer in case of any other not predictable error ( this line always at the end as the execution is sequential\n print(e)\nfinally:\n print(\"this code will always execute\") # you can use finally module to run additional code , the code in finally will always execute after try catch\n\n\n# Try Execpt else and try except and finally error handling differencies\n\ntry:\n print(\"there is no error in try block\")\n # print(a) #if you cause an exeption in try block else will not execute\nexcept Exception as e:\n print(e)\nelse:\n print(\"this block of code will execute only if no error in try block\") # as oppose to finally that is always executed\n\n########################## Raise user defined Exeptions ###############################################\n\n# what is custome exeption - it is errorcreated by user to display an error, it can be created with \"rise\" and \"assert\"\n\n# raise = to raise an existing Excpetion when we want\n\n\"\"\"raise Exception(\"this is an exeption\")\"\"\"\n\n# to use in real time let's write an if condition if flase instead of print I want to raise an exception and stop the code\n\nage=34\nif age<33:\n print(\"the age range is correct\")\nelse:\n raise ValueError(\"the age is not in the defined range\") # raise an exception and stop the code\n\n# Assert = to create an AssertionError - assert will raise exceltion if condition is false\n\nassert(1>5) # condition is false AssertError is created and code will stop\n\ntry:\n assert(1>5)\nexcept Exception as e:\n print(\" the error is: \",e)\n","sub_path":"ExceptionHandling.py","file_name":"ExceptionHandling.py","file_ext":"py","file_size_in_byte":3223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"210868227","text":"import sys, os\r\nfrom PyQt5.QtWidgets import (QMainWindow, QMessageBox,\r\n QPushButton, QGridLayout, QApplication, QDesktopWidget)\r\nfrom PyQt5.QtGui import QFont, QIcon\r\nfrom PyQt5.QtCore import QCoreApplication\r\nfrom PyQt5.QtCore import Qt as qtcore\r\n\r\nLOCALPATH = os.path.dirname(os.path.abspath(__file__))\r\n\r\n\r\nclass Entity(object):\r\n pass\r\n\r\nclass Character(Entity):\r\n\r\n def __init__(self, name):\r\n super().__init__()\r\n self.hunger = 0\r\n self.actionPoints = 0\r\n self.name = name\r\n\r\n\r\n\r\n\r\nclass Game(QMainWindow):\r\n def __init__(self):\r\n super().__init__()\r\n self.turn = 0\r\n\r\n self.initUI()\r\n\r\n def initUI(self):\r\n\r\n # Window config\r\n self.statusBar()\r\n self.resize(1024, 768)\r\n self.setWindowFlag(qtcore.FramelessWindowHint)\r\n self.center()\r\n\r\n # Icon\r\n self.setWindowIcon(QIcon(os.path.join(LOCALPATH, 'images/icon.png')))\r\n\r\n newchar = Character('Albonpin')\r\n charbtn = QPushButton(newchar.name)\r\n charbtn.move(50, 0)\r\n nxtbtn = QPushButton('Next turn', self)\r\n nxtbtn.move(50, 50)\r\n nxtbtn.clicked.connect(lambda: self.nextTurn(newchar))\r\n\r\n eatbtn = QPushButton('Eat something', self)\r\n eatbtn.move(50, 75)\r\n eatbtn.clicked.connect(lambda: self.eatAction(newchar))\r\n\r\n qbtn = QPushButton('Quit', self)\r\n qbtn.clicked.connect(QCoreApplication.instance().quit)\r\n qbtn.move(50, 125)\r\n\r\n\r\n self.show()\r\n\r\n def buttonClicked(self):\r\n sender = self.sender()\r\n self.statusBar().showMessage(sender.text() + ' was pressed')\r\n\r\n def nextTurn(self, char):\r\n\r\n char.hunger += 1\r\n if char.hunger > 10:\r\n self.statusBar().showMessage('You\\'re dead')\r\n else:\r\n char.actionPoints += 1\r\n self.turn += 1\r\n self.statusBar().showMessage('Turn {}:| Hunger:{}'.format(self.turn, char.hunger))\r\n\r\n def eatAction(self, char):\r\n if char.actionPoints > 0:\r\n char.hunger -= 5\r\n self.statusBar().showMessage('Yummy! | Hunger:{}'.format(self.turn, char.hunger))\r\n char.actionPoints = 0\r\n else:\r\n self.statusBar().showMessage('Can\\'t eat, no action points left, click on next turn')\r\n\r\n def closeEvent(self, event):\r\n\r\n reply = QMessageBox.question(self, 'Message',\r\n \"Are you sure to quit?\", QMessageBox.Yes |\r\n QMessageBox.No, QMessageBox.No)\r\n\r\n if reply == QMessageBox.Yes:\r\n event.accept()\r\n else:\r\n event.ignore()\r\n\r\n def center(self):\r\n\r\n qr = self.frameGeometry()\r\n cp = QDesktopWidget().availableGeometry().center()\r\n qr.moveCenter(cp)\r\n self.move(qr.topLeft())\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n game = Game()\r\n sys.exit(app.exec_())","sub_path":"pyqt/first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"550639556","text":"from tensorflow.python.framework import dtypes\nfrom tensorflow.contrib.rnn.python.ops import core_rnn\nfrom tensorflow.python.ops import variable_scope\nimport tensorflow.contrib.legacy_seq2seq as seq2seq\nimport tensorflow as tf\nfrom tensorflow.contrib.rnn import LSTMStateTuple\n\ndim_hidden = 100\n\ndef infer(initial_state,\n cell,\n num_units,\n scope=None):\n\n\n with variable_scope.variable_scope(scope or \"infer\"):\n state = initial_state\n outputs = []\n prev = None\n for i in range(10):\n inp = tf.zeros([num_units, num_units], tf.float32)\n if i > 0:\n inp = prev\n variable_scope.get_variable_scope().reuse_variables()\n output, state = cell(inp, state)\n outputs.append(output)\n prev = output\n return outputs, state\n\ndef custom_rnn_seq2seq(encoder_inputs,\n decoder_inputs,\n enc_cell,\n dec_cell,\n dtype=dtypes.float32,\n initial_state=None,\n use_previous=False,\n scope=None,\n num_units=0):\n\n with variable_scope.variable_scope(scope or \"custom_rnn_seq2seq\"):\n _, enc_state = core_rnn.static_rnn(enc_cell, encoder_inputs, dtype=dtype, scope=scope, initial_state=initial_state)\n print(enc_state.get_shape)\n c = tf.tanh(tf.matmul(tf.get_variable(\"v\", [dim_hidden, dim_hidden]), enc_state))\n h_prime_init = tf.tanh(tf.matmul(tf.get_variable(\"v_prime\", [dim_hidden, dim_hidden]), c))\n if not use_previous:\n return seq2seq.rnn_decoder(decoder_inputs, LSTMStateTuple(c, h_prime_init), dec_cell, scope=scope)\n return infer(LSTMStateTuple(c, h_prime_init), dec_cell, num_units)","sub_path":"rnn/seq2seq_custom.py","file_name":"seq2seq_custom.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"310808586","text":"from selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.keys import Keys\nimport time\nimport sys\nimport threading\nimport requests\nfrom aip import AipOcr\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\n\nclass CourseSelect:\n def __int__(self):\n pass\n\n filepath = \"./cap/img.png\"\n\n\n def get_captcha(self):\n APP_ID = '18275558'\n API_KEY = 'MSLnSpkm3P7HaAmdt9kRtxex'\n SECRET_KEY = 'xBhfzGBxKTn0PorejvggGkrOZNhME18L'\n\n client = AipOcr(APP_ID, API_KEY, SECRET_KEY)\n\n\n options = {\n 'detect_direction' : 'true',\n 'language_type' : 'ENG',\n }\n # 调用通用文字识别接口\n with open(self.filepath, 'rb') as fp:\n content = fp.read()\n result = client.basicAccurate(content, options)\n rst = result['words_result']\n rst = rst[0]['words']\n print(rst)\n rst = rst.replace(' ', '')\n return rst\n\n\n def login(self, id, pwd):\n self.url = 'http://coursesel.umji.sjtu.edu.cn/welcome.action'\n self.browser=webdriver.Chrome(\"/Users/zhehaoyu/Desktop/web crawler/chromedriver-2\")\n browser=self.browser\n time.sleep(2)\n page =browser.get(self.url)\n # input user info\n username=browser.find_element_by_id('user')\n password=browser.find_element_by_id('pass')\n username.send_keys(id)\n password.send_keys(pwd)\n\n # get captcha\n captcha=browser.find_element_by_id('captcha-img')\n captcha.screenshot(self.filepath)\n\n cap = self.get_captcha()\n captcha_input=browser.find_element_by_id('captcha')\n captcha_input.send_keys(cap)\n\n loginBtn = browser.find_element_by_id('submit-button')\n loginBtn.click()\n time.sleep(3)\n\n def getin(self):\n browser = self.browser\n round=browser.find_element_by_class_name('electTurnName')\n round.click()\n time.sleep(3)\n mark=browser.find_element_by_class_name('elect-turn-detail-item-bottom-tip')\n mark.click()\n go=browser.find_element_by_xpath('/html/body/div[2]/div[1]/div/div[2]/div[2]/div/div/div/div[2]/div/div[2]')\n go.click()\n\n def select_by_xpath(self,xpath=\"\"):\n browser=self.browser\n xk=browser.find_element_by_xpath(xpath)\n xk.click()\n browser.switch_to_alert().accept()\n time.sleep(1)\n\n\nif __name__ == '__main__':\n username=''\n pwd=''\n xp=input('input xpath: ')\n\n service = CourseSelect()\n service.login(username, pwd)\n time.sleep(3)\n service.get_in()\n\n time.sleep(10)\n\n service.select_by_xpath(xp)\n service.browser.close()\n","sub_path":"ez_sele.py","file_name":"ez_sele.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"105046880","text":"import unittest\n\nfrom mock import MagicMock\n\nfrom rip.crud.crud_actions import CrudActions\nfrom rip.crud.crud_resource import CrudResource\nfrom rip.crud.pipeline_composer import PipelineComposer\nfrom rip.generic_steps import error_types\nfrom rip.request import Request\nfrom rip.schema_fields.boolean_field import BooleanField\nfrom rip.schema_fields.string_field import StringField\n\n\nclass TestCrudResourceConstruction(unittest.TestCase):\n def setUp(self):\n self.pipeline1 = MagicMock(spec=PipelineComposer)\n self.pipeline2 = MagicMock(spec=PipelineComposer)\n\n class TestResource(CrudResource):\n name = StringField(max_length=32)\n boolean = BooleanField()\n\n self.TestResource = TestResource\n\n def test_read_detail(self):\n request = MagicMock()\n\n test_resource = self.TestResource()\n test_resource.pipelines[CrudActions.READ_DETAIL] = \\\n pipeline = MagicMock()\n test_resource.run_crud_action(CrudActions.READ_DETAIL, request)\n\n pipeline.assert_called_once_with(request)\n\n def test_update_detail(self):\n request = MagicMock()\n\n class DefaultTestResource(CrudResource):\n\n class Meta:\n allowed_actions = [CrudActions.UPDATE_DETAIL]\n\n test_resource = DefaultTestResource()\n test_resource.pipelines[CrudActions.UPDATE_DETAIL] = \\\n pipeline = MagicMock()\n test_resource.run_crud_action(CrudActions.UPDATE_DETAIL, request)\n\n pipeline.assert_called_once_with(request)\n\n def test_create_detail(self):\n request = MagicMock()\n\n class DefaultTestResource(CrudResource):\n class Meta:\n allowed_actions = [CrudActions.CREATE_DETAIL]\n\n test_resource = DefaultTestResource()\n test_resource.pipelines[CrudActions.CREATE_DETAIL] = \\\n pipeline = MagicMock()\n test_resource.run_crud_action(CrudActions.CREATE_DETAIL, request)\n\n pipeline.assert_called_once_with(request)\n\n def test_delete_detail(self):\n request = MagicMock()\n\n class DefaultTestResource(CrudResource):\n class Meta:\n allowed_actions = [CrudActions.DELETE_DETAIL]\n\n test_resource = DefaultTestResource()\n test_resource.pipelines[CrudActions.DELETE_DETAIL] = \\\n pipeline = MagicMock()\n test_resource.run_crud_action(CrudActions.DELETE_DETAIL, request)\n\n pipeline.assert_called_once_with(request)\n\n def test_create_or_update_detail(self):\n expected_response = MagicMock()\n request = MagicMock()\n\n class DefaultTestResource(CrudResource):\n class Meta:\n authentication_cls = MagicMock()\n allowed_actions = [CrudActions.CREATE_OR_UPDATE_DETAIL]\n\n test_resource = DefaultTestResource()\n test_resource.pipelines[CrudActions.CREATE_OR_UPDATE_DETAIL] = \\\n pipeline = MagicMock()\n pipeline.return_value = expected_response\n\n response = test_resource.run_crud_action(\n CrudActions.CREATE_OR_UPDATE_DETAIL, request)\n\n assert response == expected_response\n pipeline.assert_called_once_with(request)\n\n\nclass TestMethodNotAllowed(unittest.TestCase):\n def setUp(self):\n class TestResource(CrudResource):\n class Meta:\n allowed_actions = ()\n\n self.test_resource = TestResource()\n\n def assert_forbidden_response(self, response):\n assert not response.is_success\n assert response.reason == error_types.MethodNotAllowed\n\n def test_forbidden_response_if_methods_not_allowed(self):\n request = Request(user=MagicMock(), request_params={})\n for action in [CrudActions.READ_DETAIL, CrudActions.READ_LIST,\n CrudActions.GET_AGGREGATES, CrudActions.CREATE_DETAIL,\n CrudActions.UPDATE_DETAIL, CrudActions.DELETE_DETAIL,\n CrudActions.CREATE_OR_UPDATE_DETAIL]:\n\n response = self.test_resource.run_crud_action(\n action, request=request)\n self.assert_forbidden_response(response)\n","sub_path":"rip/tests/unit_tests/crud/test_crud_resource.py","file_name":"test_crud_resource.py","file_ext":"py","file_size_in_byte":4143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"122342223","text":"# print(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)\r\n\r\n# i = 0\r\n# while i <= 100:\r\n#\tif i % 2 == 0:\r\n#\t\tprint(i)\r\n#\ti += 1\r\n\r\n#name = \"\"\r\n\r\n#while name != \"Лукман\":\r\n#\tname = input(\"Вы пришли на танцы. Представьтесь: \")\r\n#\tif name == \"Лукман\" or name == \"Ахмед\":\r\n#\t\tprint(\"Здоровеньки булы,\" + name +\". Мы вас заждались. Вот ваша дама в платье.\")\r\n#\t\tbreak\r\n#\telse:\r\n#\t\tprint(\"Пошёл вон. Нам нужен только Лукман! Возращайся в свою селуху.\")\r\n\r\n\r\n\r\nwhile True:\r\n\tname = input(\"Вы пришли на трудоустройство. Представьтесь: \")\r\n\tif name == \"Лукман\":\r\n\t\tprint(\"Здравствуйте, Лукман, Зубная щётка.\")\r\n\t\tbreak\r\n\telif name == \"Ахмед\":\r\n\t\tprint(\"Уходите, вы нам не годитесь! Забудьте дорогу сюда.\")\r\n\t\tbreak\r\n\telif name == \"Саид\":\r\n\t\tprint(\"Я вам не верю. Введите своё имя!\")\r\n\t\tcontinue","sub_path":"Python1/l06/cikl.py","file_name":"cikl.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"573689119","text":"'''\nCreated on Mar 1, 2016\n\n@author: MADHUSUDAN\n'''\nfrom __future__ import print_function\nimport time\ndef sum_to_n(n):\n start = time.time()\n sum=0\n for i in range(1,n+1):\n sum=sum+i\n end = time.time()\n return sum,end-start\n\nprint (\"Sum is %d and time is %10.9f\"% sum_to_n(10000))\n","sub_path":"time_benchmarking.py","file_name":"time_benchmarking.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"53710723","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\nimport wx\nimport armid\nimport ARM\nfrom Borg import Borg\nfrom ConnectorDialog import ConnectorDialog\nfrom ConnectorParameters import ConnectorParameters\n\nclass ConnectorListCtrl(wx.ListCtrl):\n def __init__(self,parent,winId = armid.COMPONENTVIEW_LISTCONNECTORS_ID):\n wx.ListCtrl.__init__(self,parent,winId,size=wx.DefaultSize,style=wx.LC_REPORT)\n b = Borg()\n self.dbProxy = b.dbProxy\n self.theViewName = ''\n self.InsertColumn(0,'Connector')\n self.SetColumnWidth(0,100)\n self.InsertColumn(1,'From')\n self.SetColumnWidth(1,100)\n self.InsertColumn(2,'Role')\n self.SetColumnWidth(2,100)\n self.InsertColumn(3,'Interface')\n self.SetColumnWidth(3,100)\n self.InsertColumn(4,'To')\n self.SetColumnWidth(4,100)\n self.InsertColumn(5,'Interface')\n self.SetColumnWidth(5,100)\n self.InsertColumn(6,'Role')\n self.SetColumnWidth(6,100)\n self.InsertColumn(7,'Asset')\n self.SetColumnWidth(7,100)\n self.InsertColumn(8,'Protocol')\n self.SetColumnWidth(8,100)\n self.InsertColumn(9,'Access Right')\n self.SetColumnWidth(9,100)\n self.theSelectedIdx = -1\n self.theDimMenu = wx.Menu()\n self.theDimMenu.Append(armid.AA_MENUADD_ID,'Add')\n self.theDimMenu.Append(armid.AA_MENUDELETE_ID,'Delete')\n self.Bind(wx.EVT_RIGHT_DOWN,self.OnRightDown)\n wx.EVT_MENU(self.theDimMenu,armid.AA_MENUADD_ID,self.onAddConnector)\n wx.EVT_MENU(self.theDimMenu,armid.AA_MENUDELETE_ID,self.onDeleteConnector)\n\n self.Bind(wx.EVT_LIST_ITEM_SELECTED,self.OnItemSelected)\n self.Bind(wx.EVT_LIST_ITEM_DESELECTED,self.OnItemDeselected)\n self.Bind(wx.EVT_LIST_ITEM_ACTIVATED,self.onConnectorActivated)\n\n def setView(self,cvName): self.theViewName = cvName\n\n def OnRightDown(self,evt):\n self.PopupMenu(self.theDimMenu)\n\n def onAddConnector(self,evt):\n dlg = ConnectorDialog(self)\n if (dlg.ShowModal() == armid.CONNECTOR_BUTTONCOMMIT_ID):\n self.theSelectedIdx = self.GetItemCount()\n self.InsertStringItem(self.theSelectedIdx,dlg.name())\n self.SetStringItem(self.theSelectedIdx,1,dlg.fromComponent())\n self.SetStringItem(self.theSelectedIdx,2,dlg.fromRole())\n self.SetStringItem(self.theSelectedIdx,3,dlg.fromInterface())\n self.SetStringItem(self.theSelectedIdx,4,dlg.toComponent())\n self.SetStringItem(self.theSelectedIdx,5,dlg.toInterface())\n self.SetStringItem(self.theSelectedIdx,6,dlg.toRole())\n self.SetStringItem(self.theSelectedIdx,7,dlg.asset())\n self.SetStringItem(self.theSelectedIdx,8,dlg.protocol())\n self.SetStringItem(self.theSelectedIdx,9,dlg.accessRight())\n\n def onDeleteConnector(self,evt):\n if (self.theSelectedIdx == -1):\n errorText = 'No connector selected'\n errorLabel = 'Delete connector'\n dlg = wx.MessageDialog(self,errorText,errorLabel,wx.OK)\n dlg.ShowModal()\n dlg.Destroy()\n else:\n selectedValue = self.GetItemText(self.theSelectedIdx)\n self.DeleteItem(self.theSelectedIdx)\n\n \n def OnItemSelected(self,evt):\n self.theSelectedIdx = evt.GetIndex()\n\n def OnItemDeselected(self,evt):\n self.theSelectedIdx = -1\n\n def onConnectorActivated(self,evt):\n self.theSelectedIdx = evt.GetIndex()\n conName = self.GetItemText(self.theSelectedIdx)\n fromComponent = self.GetItem(self.theSelectedIdx,1)\n fromRole = self.GetItem(self.theSelectedIdx,2)\n fromInterface = self.GetItem(self.theSelectedIdx,3)\n toComponent = self.GetItem(self.theSelectedIdx,4)\n toInterface = self.GetItem(self.theSelectedIdx,5)\n toRole = self.GetItem(self.theSelectedIdx,6)\n assetName = self.GetItem(self.theSelectedIdx,7)\n pName = self.GetItem(self.theSelectedIdx,8)\n arName = self.GetItem(self.theSelectedIdx,9)\n \n dlg = ConnectorDialog(self,conName,fromComponent.GetText(),fromRole.GetText(),fromInterface.GetText(),toComponent.GetText(),toInterface.GetText(),toRole.GetText(),assetName.GetText(),pName.GetText(),arName.GetText())\n if (dlg.ShowModal() == armid.CONNECTOR_BUTTONCOMMIT_ID):\n self.SetStringItem(self.theSelectedIdx,0,dlg.name())\n self.SetStringItem(self.theSelectedIdx,1,dlg.fromComponent())\n self.SetStringItem(self.theSelectedIdx,2,dlg.fromRole())\n self.SetStringItem(self.theSelectedIdx,3,dlg.fromInterface())\n self.SetStringItem(self.theSelectedIdx,4,dlg.toComponent())\n self.SetStringItem(self.theSelectedIdx,5,dlg.toInterface())\n self.SetStringItem(self.theSelectedIdx,6,dlg.toRole())\n self.SetStringItem(self.theSelectedIdx,7,dlg.asset())\n self.SetStringItem(self.theSelectedIdx,8,dlg.protocol())\n self.SetStringItem(self.theSelectedIdx,9,dlg.accessRight())\n\n def load(self,cons):\n for conName,fromComponent,fromRole,fromInterface,toComponent,toInterface,toRole,assetName,pName,arName in cons:\n idx = self.GetItemCount()\n self.InsertStringItem(idx,conName)\n self.SetStringItem(idx,1,fromComponent)\n self.SetStringItem(idx,2,fromRole)\n self.SetStringItem(idx,3,fromInterface)\n self.SetStringItem(idx,4,toComponent)\n self.SetStringItem(idx,5,toInterface)\n self.SetStringItem(idx,6,toRole)\n self.SetStringItem(idx,7,assetName)\n self.SetStringItem(idx,8,pName)\n self.SetStringItem(idx,9,arName)\n\n def dimensions(self):\n cons = []\n for x in range(self.GetItemCount()):\n conName = self.GetItemText(x)\n fromComponent = self.GetItem(x,1)\n fromRole = self.GetItem(x,2)\n fromInterface = self.GetItem(x,3)\n toComponent = self.GetItem(x,4)\n toInterface = self.GetItem(x,5)\n toRole = self.GetItem(x,6)\n assetName = self.GetItem(x,7)\n pName = self.GetItem(x,8)\n arName = self.GetItem(x,9)\n p = ConnectorParameters(conName,self.theViewName,fromComponent.GetText(),fromRole.GetText(),fromInterface.GetText(),toComponent.GetText(),toInterface.GetText(),toRole.GetText(),assetName.GetText(),pName.GetText(),arName.GetText())\n cons.append(p)\n return cons\n","sub_path":"cairis/cairis/ConnectorListCtrl.py","file_name":"ConnectorListCtrl.py","file_ext":"py","file_size_in_byte":6728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"91651295","text":"\"\"\"\nSupport for the BBC weather service.\n\"\"\"\nimport logging\nfrom datetime import timedelta\n\nimport requests\nimport voluptuous as vol\nfrom requests import RequestException\n\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.components.weather import (\n ATTR_FORECAST_TEMP, ATTR_FORECAST_TIME, PLATFORM_SCHEMA, WeatherEntity)\nfrom homeassistant.const import CONF_NAME, STATE_UNKNOWN, CONF_SCAN_INTERVAL\n\n_LOGGER = logging.getLogger(__name__)\n\nDATA_CONDITION = 'bbc_condition'\n\nATTR_DATA_OBJECT_NOW = 'now'\nATTR_DATA_OBJECT_FORECAST = 'forecast'\n\n\nATTR_FORECAST_CONDITION = 'condition'\nATTR_FORECAST_DESCRIPTION = 'description'\nATTR_PRECIP_PROB = 'precipitation_probability'\nATTR_PRECIP_PROB_DESC = 'precipitation_probability_description'\nATTR_FORECAST_PRESSURE = 'pressure'\nATTR_FORECAST_WIND_BEARING = 'wind_bearing'\nATTR_FORECAST_WIND_SPEED = 'wind_speed'\nATTR_FORECAST_VISIBILITY = 'visibility'\nATTR_FORECAST_HUMIDITY = 'humidity'\n\nATTRIBUTION = \"Weather details provided by BBC\"\n\nATTR_FORECAST_TEMP_LOW = 'templow'\n\nCONF_LOCATION_ID = 'location_id'\n\nDEFAULT_NAME = 'BBC Weather'\n\nURL = 'https://weather-broker-cdn.api.bbci.co.uk/en/forecast/aggregated/{location_id}'\n\nDEFAULT_SCAN_INTERVAL = timedelta(minutes=10)\n\nCONDITION_CLASSES = {\n 'clear-night': [0],\n 'cloudy': [7, 8, 36, 37],\n 'fog': [5],\n 'hail': [],\n 'lightning': [],\n 'lightning-rainy': [28, 29],\n 'partlycloudy': [2, 3],\n 'pouring': [13, 14, 15, 40],\n 'rainy': [9, 10, 11, 12, 39],\n 'snowy': [22, 23, 24],\n 'snowy-rainy': [16, 17, 18],\n 'sunny': [1],\n 'windy': [],\n 'windy-variant': [],\n 'exceptional': [],\n}\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Required(CONF_LOCATION_ID): cv.string,\n vol.Required(CONF_NAME, default=DEFAULT_NAME): cv.string,\n vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): cv.timedelta,\n})\n\n\ndef setup_platform(hass, config, add_devices, discovery_info=None):\n \"\"\"Set up the Yahoo! weather platform.\"\"\"\n\n unit = hass.config.units.temperature_unit\n location_id = config.get(CONF_LOCATION_ID)\n name = config.get(CONF_NAME)\n\n if DATA_CONDITION not in hass.data:\n hass.data[DATA_CONDITION] = [str(x) for x in range(0, 50)]\n for cond, condlst in CONDITION_CLASSES.items():\n for condi in condlst:\n hass.data[DATA_CONDITION][condi] = cond\n\n bbc_weather_data = BbcWeatherData(requests, location_id, hass.data[DATA_CONDITION])\n\n if not bbc_weather_data:\n _LOGGER.critical(\"Can't retrieve weather data from BBC Weather\")\n return False\n\n add_devices([BbcWeather(bbc_weather_data, name, unit)], True)\n\n\nclass BbcWeather(WeatherEntity):\n \"\"\"Representation of BBC weather data.\"\"\"\n\n def __init__(self, weather_data, name, unit):\n \"\"\"Initialize the sensor.\"\"\"\n self._name = name\n self._weather_data = weather_data\n self._unit = unit\n\n @property\n def name(self):\n \"\"\"Return the name of the sensor.\"\"\"\n return self._name\n\n @property\n def condition(self):\n \"\"\"Return the current condition.\"\"\"\n return self._get_weather_data_now(ATTR_FORECAST_CONDITION)\n\n @property\n def temperature(self):\n \"\"\"Return the temperature.\"\"\"\n return self._get_weather_data_now(ATTR_FORECAST_TEMP)\n\n @property\n def temperature_unit(self):\n \"\"\"Return the unit of measurement.\"\"\"\n return self._unit\n\n @property\n def pressure(self):\n \"\"\"Return the pressure.\"\"\"\n \n return self._get_weather_data_now(ATTR_FORECAST_PRESSURE)\n\n @property\n def humidity(self):\n \"\"\"Return the humidity.\"\"\"\n return self._get_weather_data_now(ATTR_FORECAST_HUMIDITY)\n\n @property\n def visibility(self):\n \"\"\"Return the visibility.\"\"\"\n return self._get_weather_data_now(ATTR_FORECAST_VISIBILITY)\n\n @property\n def wind_speed(self):\n \"\"\"Return the wind speed.\"\"\"\n return self._get_weather_data_now(ATTR_FORECAST_WIND_SPEED)\n\n @property\n def wind_bearing(self):\n \"\"\"Return the wind direction.\"\"\"\n return self._get_weather_data_now(ATTR_FORECAST_WIND_BEARING)\n\n @property\n def attribution(self):\n \"\"\"Return the attribution.\"\"\"\n return ATTRIBUTION\n\n @property\n def forecast(self):\n \"\"\"Return the forecast array.\"\"\"\n return self._weather_data.data['forecast']\n\n def update(self):\n \"\"\"Get the latest data from Yahoo! and updates the states.\"\"\"\n self._weather_data.update()\n if not self._weather_data.data:\n _LOGGER.info(\"Don't receive weather data from Yahoo!\")\n return\n \n def _get_weather_data_now(self, weather_property):\n return self._weather_data.data.get(ATTR_DATA_OBJECT_NOW, {}).get(weather_property, STATE_UNKNOWN)\n\n\nclass BbcWeatherData(object):\n \"\"\"Handle the BBC data object\"\"\"\n\n def __init__(self, rest_client, location_id, conditions):\n \"\"\"Initialize the data object.\"\"\"\n self._url = URL.format(location_id=location_id)\n self._rest_client = rest_client\n self._data = None\n self._conditions = conditions\n\n @property\n def data(self):\n \"\"\"Return the data objet.\"\"\"\n return self._data\n\n def update(self):\n \"\"\"Get the latest data from BBC!.\"\"\"\n try:\n response = self._rest_client.get(self._url)\n forecasts = response.json()['forecasts']\n\n now_report = forecasts[0]['detailed']['reports'][0]\n self._data = {\n ATTR_DATA_OBJECT_NOW: {\n ATTR_FORECAST_TEMP: now_report['temperatureC'],\n ATTR_FORECAST_PRESSURE: now_report['pressure'],\n ATTR_FORECAST_HUMIDITY: now_report['humidity'],\n ATTR_FORECAST_VISIBILITY: now_report['visibility'],\n ATTR_FORECAST_WIND_SPEED: now_report['windSpeedKph'],\n ATTR_FORECAST_WIND_BEARING: now_report['windDirectionAbbreviation'],\n ATTR_FORECAST_CONDITION: self._get_condition(now_report['weatherType']),\n ATTR_FORECAST_DESCRIPTION: now_report['enhancedWeatherDescription'],\n ATTR_PRECIP_PROB: now_report['precipitationProbabilityInPercent'],\n ATTR_PRECIP_PROB_DESC: now_report['precipitationProbabilityText'],\n },\n ATTR_DATA_OBJECT_FORECAST: [\n {\n ATTR_FORECAST_TIME: report['localDate'],\n ATTR_FORECAST_TEMP: report['maxTempC'],\n ATTR_FORECAST_TEMP_LOW: report['minTempC'],\n ATTR_FORECAST_CONDITION: self._get_condition(report['weatherType']),\n ATTR_FORECAST_DESCRIPTION: report['enhancedWeatherDescription'],\n ATTR_PRECIP_PROB: report['precipitationProbabilityInPercent'],\n ATTR_PRECIP_PROB_DESC: report['precipitationProbabilityText'],\n\n } for report in map(lambda f : f['summary']['report'], forecasts)]\n }\n\n except RequestException:\n _LOGGER.error(\"Failed to get latest data from BBC Weather\")\n self._data = None\n\n def _get_condition(self, code):\n try:\n return self._conditions[code]\n except (ValueError, IndexError):\n return STATE_UNKNOWN\n","sub_path":"custom_components/weather/bbc_weather.py","file_name":"bbc_weather.py","file_ext":"py","file_size_in_byte":7414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"599820714","text":"# -*- coding: utf-8 -*-\r\nimport argparse\r\n\r\nimport torch\r\n\r\nfrom tqdm import tqdm\r\n\r\nfrom models.embedding import ProtoNetEmbedding\r\nfrom protoNet.prototy_head import ClassificationHead\r\n\r\nfrom utilities import set_gpu, count_accuracy, log, setup_seed\r\nimport numpy as np\r\nimport os\r\nfrom dataloaders.tieredImageNet import tieredImageNet, FewShotDataloader\r\n\r\n\r\ndef get_model():\r\n\r\n network = ProtoNetEmbedding().cuda()\r\n cls_head = ClassificationHead(False).cuda()\r\n\r\n return (network, cls_head)\r\n\r\n\r\nif __name__ == '__main__':\r\n setup_seed(1234)\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--gpu', default='0')\r\n parser.add_argument('--load', default='/data/save_models/best_model.pth.tar',\r\n help='path of the checkpoint file')\r\n parser.add_argument('--episode', type=int, default=2000,\r\n help='number of episodes to test')\r\n parser.add_argument('--way', type=int, default=5,\r\n help='number of classes in one test episode')\r\n parser.add_argument('--shot', type=int, default=5,\r\n help='number of support examples per training class')\r\n parser.add_argument('--query', type=int, default=10,\r\n help='number of query examples per training class')\r\n\r\n opt = parser.parse_args()\r\n set_gpu(opt.gpu)\r\n\r\n log_file_path = os.path.join(os.path.dirname(opt.load), \"test_log.txt\")\r\n log(log_file_path, str(vars(opt)))\r\n\r\n # Define the models\r\n (embedding_net, cls_head) = get_model()\r\n\r\n # Load saved model checkpoints\r\n saved_models = torch.load(opt.load)\r\n embedding_net.load_state_dict(saved_models['embedding'])\r\n embedding_net.eval()\r\n cls_head.load_state_dict(saved_models['head'])\r\n cls_head.eval()\r\n #-----------------------------\r\n dataset_test = tieredImageNet(phase='test')\r\n data_loader = FewShotDataloader\r\n dloader_test = data_loader(\r\n dataset=dataset_test,\r\n nKnovel=opt.way,\r\n nKbase=0,\r\n nExemplars=opt.shot, # num training examples per novel category\r\n nTestNovel=opt.query * opt.way, # num test examples for all the novel categories\r\n nTestBase=0, # num test examples for all the base categories\r\n batch_size=1,\r\n num_workers=1,\r\n epoch_size=opt.episode, # num of batches per epoch\r\n )\r\n #-----------------------------------\r\n\r\n # Evaluate on test set\r\n test_accuracies = []\r\n\r\n for i, batch in enumerate(tqdm(dloader_test()), 1):\r\n\r\n data_support, labels_support, data_query, labels_query, _, _ = [x.cuda() for x in batch]\r\n\r\n data_support = data_support.float()\r\n data_query = data_query.float()\r\n\r\n labels_support = labels_support.long()\r\n labels_query = labels_query.long()\r\n\r\n\r\n n_support = opt.way * opt.shot\r\n n_query = opt.way * opt.query\r\n\r\n\r\n\r\n emb_support = embedding_net(data_support.reshape([-1] + list(data_support.shape[-3:])))\r\n emb_support = emb_support.reshape(1, n_support, -1)\r\n\r\n emb_query = embedding_net(data_query.reshape([-1] + list(data_query.shape[-3:])))\r\n emb_query = emb_query.reshape(1, n_query, -1)\r\n\r\n logits = cls_head(emb_query, emb_support, labels_support, opt.way, opt.shot)\r\n\r\n acc = count_accuracy(logits.reshape(-1, opt.way), labels_query.reshape(-1))\r\n test_accuracies.append(acc.item())\r\n\r\n avg = np.mean(np.array(test_accuracies))\r\n std = np.std(np.array(test_accuracies))\r\n ci95 = 1.96 * std / np.sqrt(i + 1)\r\n\r\n if i % 50 == 0:\r\n print('Episode [{}/{}]:\\t\\t\\tAccuracy: {:.2f} ± {:.2f} % ({:.2f} %)' \\\r\n .format(i, opt.episode, avg, ci95, acc))\r\n","sub_path":"protoNet/test_imagenet.py","file_name":"test_imagenet.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"257017646","text":"\r\n#1.1 Given a number count the total number of digits in a number.\r\n\r\n\r\n\r\ndef count(l):\r\n c=0\r\n while l!=0:\r\n l=l//10\r\n c=c+1\r\n print(\"Count of total number of digits:\",c)\r\nl=int(input(\"Enter a number:\"))\r\ncount(l)\r\n\r\n\r\n\r\n\r\n#1.2 Reverse the following list using for loop.\r\n\r\n\r\n\r\nlist1=[]\r\nn = int(input(\"Enter number of elements for list 1 : \"))\r\nfor i in range(0, n): \r\n l = int(input())\r\n list1.append(l)\r\n\r\nfor i in range(len(list1)-1,-1,-1):\r\n print(list1[i])\r\n \r\n\r\n\r\n\r\n#2 Given 2 strings, s1 and s2, create a new string by appending s2 in the middle of s1.\r\n \r\n \r\n\r\ns1=input(\"Enter 1st String:\")\r\ns2=input(\"Enter 2nd String:\")\r\na=int(len(s1)/2)\r\nstring=s1[0:a]+s2+s1[a:]\r\nprint(string)\r\n\r\n\r\n\r\n#3. Arrange String characters such that lowercase letters should come first.\r\n\r\n\r\n\r\ni=input(\"Enter a String:\")\r\n#i='BHAaveSHmakWana'\r\nl=list(i)\r\nlow=[]\r\nup=[]\r\nfor n in l:\r\n if n.islower():\r\n low.append(n)\r\n else:\r\n up.append(n)\r\nlow=''.join(map(str,low))\r\nup=''.join(map(str,up))\r\nprint(low+up)\r\n\r\n\r\n\r\n\r\n#4. Given a string, return the sum and average of the digits that appear in the string, ignoring all othercharacters.\r\n\r\n#inputStr = \"English = 78 Science = 83 Math = 68 History = 65\"\r\n\r\n\r\ninputStr=input(\"enter string with marks:\")\r\nl=[]\r\nfor marks in re.findall(r'\\d\\d', inputStr):\r\n\tl.append(int(marks))\r\nprint(inputStr)\r\nprint(\"sum\",sum(l),\"Average\",sum(l)/len(l))\r\n\r\n\r\n\r\n#5 Given a two list. Create a third list by picking an odd-index element from the first list and even indexelements from second.\r\n\r\n\r\nlistOne=[]\r\nlistTwo=[]\r\n\r\nnum1 = int(input(\"Enter number of elements for list 1 : \"))\r\nfor i in range(0, n): \r\n list1 = int(input())\r\n listOne.append(list1)\r\nnum2 = int(input(\"Enter number of elements for list 2 : \"))\r\nfor i in range(0, m): \r\n list2 = int(input())\r\n listTwo.append(list2)\r\nl=listOne[0::2]\r\nm=listTwo[1::2]\r\nprint(l+m)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"python test.py","file_name":"python test.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"250733053","text":"# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def maxAncestorDiff(self, root: TreeNode) -> int:\n def traverse(node):\n cmin, cmax, cmaxdiff = node.val, node.val, 0\n if node.left:\n lmin, lmax, lmaxdiff = traverse(node.left)\n cmin = min(lmin, cmin)\n cmax = max(lmax, cmax)\n cmaxdiff = max(lmaxdiff, cmaxdiff, abs(\n node.val - lmin), abs(node.val-lmax))\n if node.right:\n rmin, rmax, rmaxdiff = traverse(node.right)\n cmin = min(rmin, cmin)\n cmax = max(rmax, cmax)\n cmaxdiff = max(rmaxdiff, cmaxdiff, abs(\n node.val - rmin), abs(node.val - rmax))\n return cmin, cmax, cmaxdiff\n return traverse(root)[2]\n\n\nsol = Solution()\nroot = TreeNode(2)\nroot.left = TreeNode(5)\nroot.right = TreeNode(0)\nroot.right.left = TreeNode(4)\nroot.right.left.right = TreeNode(6)\nroot.right.left.right.left = TreeNode(1)\nroot.right.left.right.left.left = TreeNode(3)\nret = sol.maxAncestorDiff(root)\nprint(ret)\n","sub_path":"src/maximum-difference-between-node-and-ancestor.py","file_name":"maximum-difference-between-node-and-ancestor.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"596390065","text":"\"\"\"SpiNNaker Routing Table Compression (SpRouT)\n\nOrdered Covering Reduction Algorithm\n\"\"\"\nfrom __future__ import print_function\nimport collections\nimport operator\nfrom six import iteritems, itervalues\nimport sys\nimport time\nfrom .model import MatchExpression, RoutingTableEntry\nfrom . import utils\n\n\ndef ordered_covering(routing_table, masks, target_length=None,\n allow_core_fuzziness=False):\n \"\"\"Reduce the size of a routing table by merging together compatible\n entries and exploiting the ordering of the table.\n\n The Ordered Covering Reduction algorithm exploits the fact that it is the\n first matching routing entry in the table that is selected for routing. It\n maintains the list of routing entries in ascending order of generality\n (where generality refers to the number of Xs in the match expression). New\n entries are made by speculatively masking off areas of the matching\n expressions and picking the largest group of rows which may be merged into\n a new \"covering row\". The algorithm stops when either there are no\n possible merges, or the desired number of entries has been hit.\n\n Parameters\n ----------\n routing_table : list\n A list of :py:class:`~.model.RoutingTableEntries`.\n\n It is assumed that these entries are not in any particular order and\n may be reordered into ascending order of functionality without\n affecting routing correctness. It is also assumed that if this table\n is unordered there are no two entries which would match each other --\n this assumption is not checked!\n\n masks : list\n A list of tuples of bits that can be masked out to try to combine\n entries.\n\n target_length : int or None\n Terminate the algorithm when this number of entries has been reached.\n If this is None then the algorithm will continue regardless until no\n more reductions can be made.\n\n allow_core_fuzziness : bool\n If False [default] then the final routing table will be functionally\n equivalent to the starting one. Otherwise some routes which transmit\n to different cores on the same chip may be merged and it will be up to\n the core to reject packets which it does not expect.\n\n Returns\n -------\n list :\n A list of routing table entries ordered by ascending generality. The\n ordering (asc. by generality) must be preserved if correct behaviour is\n later desired.\n \"\"\"\n # Make a copy of the routing table\n routing_table = list(routing_table[:])\n\n # Sort the routing table in order of generality\n routing_table.sort(key=lambda rte: rte.match_expression.generality)\n\n # Keep a mapping of which routing entries map to original match expressions\n made_merges = dict()\n\n # For masks and while we haven't met out target\n for mask in masks:\n # While it has been possible to make progress, and we have no target or\n # have not met the target continue to perform reductions.\n while target_length is None or len(routing_table) > target_length:\n # Get a list of possible merges.\n possible_merges = _get_possible_merges(routing_table, mask,\n allow_core_fuzziness)\n logger.debug(\"Refining {} merges.\".format(len(possible_merges)))\n best_merge = _refine_possible_merges(routing_table,\n possible_merges, made_merges)\n\n if best_merge is None:\n # If there are no possible merges then continue to the next\n # mask.\n break\n\n # Apply the best merge to the routing table\n routing_table = _apply_merging_operation(best_merge, routing_table,\n allow_core_fuzziness)\n\n # Get the new entry to allow retaining the map of merges\n new_entry = _get_routing_table_entry_from_merger(\n best_merge, allow_core_fuzziness)\n made_merges = _update_merges_map(made_merges, new_entry,\n best_merge)\n logger.debug(\"Made merge, length of table = {}\".format(\n len(routing_table)))\n\n # If we have met our target then stop\n if target_length is not None and len(routing_table) <= target_length:\n break\n\n # Return the newly reduced routing table\n return routing_table\n\n\ndef _get_possible_merges(routing_table, mask, merge_cores=False):\n \"\"\"Get lists of entries which may be merged together.\n\n Parameters\n ----------\n routing_table : list\n A list of RoutingTableEntries.\n mask : list\n A list of bits to try to merge on.\n merge_cores : bool\n Whether routing entries with differing target cores may be combined.\n\n Returns\n -------\n list\n A list of lists of possible merges that may be made.\n \"\"\"\n # Create a dictionary of the possible merges\n possible_merges = collections.defaultdict(list)\n\n # Go through all the entries and add them to the dictionary of merges by\n # masking out appropriate bits of the match expression and recording the\n # links (and optionally, cores).\n for entry in routing_table:\n reduced_match_expression =\\\n entry.match_expression.get_generalised_expression(mask)\n\n if not merge_cores:\n # If cores can't be merged we hash together the match expression,\n # set of links and set of cores.\n reduced_entry = (reduced_match_expression, entry.links,\n entry.cores)\n else:\n # If we can merge cores then we ignore cores when we come to build\n # the dictionary.\n reduced_entry = (reduced_match_expression, entry.links)\n\n # Finally we record this entry so that it might be merged with other\n # entries.\n possible_merges[reduced_entry].append(entry)\n\n # Now return a list of the possible merges\n return list(merges for merges in itervalues(possible_merges) if\n len(merges) > 1)\n\n\ndef _get_insertion_index(routing_table, new_match_expression):\n \"\"\"Get the correct insertion position for a new match expression when\n ordering in ascending order by generality.\n\n Parameters\n ----------\n routing_table : list\n new_match_expression : model.MatchExpression\n\n Returns\n -------\n int\n The position in the routing table where the new match expression should\n be inserted.\n \"\"\"\n # Binary search until we get an equivalent match expression then increment\n # until we reach the end of that block.\n bottom = 0\n top = len(routing_table) - 1\n position = bottom + (top - bottom)/2\n\n # Cache new and position generality\n ng = new_match_expression.generality\n pg = routing_table[position].match_expression.generality\n\n while pg != ng and bottom < position < top:\n if pg < ng:\n bottom = position # Move up\n elif pg > ng:\n top = position # Move down\n\n position = bottom + (top - bottom)/2\n pg = routing_table[position].match_expression.generality\n\n # Progress through the list from current position until either top is\n # reached or the next generality is discovered.\n while (position < len(routing_table) and\n routing_table[position].match_expression.generality <= ng):\n position += 1\n\n return position\n\n\ndef _refine_possible_merges(routing_table, possible_merges, made_merges):\n \"\"\"Refine lists of possible merges to remove entries that would otherwise\n be matched by entries with higher priority.\n\n For each set entry in a set of possible merges we check that it would not\n otherwise be matched by entries between its current position and the\n position of the merged entry. We ignore matches that would be made by\n other entries in the same merge set.\n\n Parameters\n ----------\n routing_table : list\n List of routing table entries ordered by generality.\n possible_merges : list\n List of sets/lists of entries that might be merged together.\n made_merges : dict\n A mapping of entries in the routing table to the set of merged entries\n they represent.\n\n Returns\n -------\n list or None\n A list containing the entries that should be merged for the greatest\n reduction in routing table size, or None if no merges are possible.\n \"\"\"\n refined_merges = list()\n\n # Sort possible merges in decreasing order of size\n possible_merges.sort(key=len, reverse=True)\n merge_lens = map(len, possible_merges)\n\n # For each possible merge we remove match entries that are matched\n # somewhere between their current position and the position of the merged\n # entry.\n for i, merge in enumerate(possible_merges):\n # Create a list of entries to remove from this possible merge\n remove_entries = list()\n merge.sort(key=lambda e: e.match_expression.generality, reverse=True)\n\n # For each entry that could be merged check to see if it matches any\n # entries that aren't in this merge between its current location and\n # the location that will be occupied by the new merged entry.\n # We've sorted merge entries so that they are in descending order of\n # generality.\n for j, entry in enumerate(merge):\n print(\"Upchecking for {}/{}\".format(j + 1, len(merge)), end='\\r')\n sys.stdout.flush()\n # For entries that we're retaining determine the insertion point of\n # the new entry.\n merged_match_expression = MatchExpression.get_covering_expression(\n [e.match_expression for e in merge if e not in remove_entries]\n )\n n = _get_insertion_index(routing_table, merged_match_expression)\n\n # Get the position of the entry we're looking at\n m = routing_table.index(entry)\n\n # Add this entry to the list to remove if there are any matches\n # between index m and n for rows that are not in this merge.\n me = entry.match_expression\n remove = any(MatchExpression.matches(me, e.match_expression) and\n (e not in merge or e in remove_entries) for e in\n routing_table[m:n])\n\n if remove:\n remove_entries.append(entry)\n\n # Remove the marked entries from the list, if the merge is now empty\n # move onto the next possible merge.\n new_merge = list(set(merge) - set(remove_entries))\n if len(new_merge) <= 1:\n continue\n\n # For each entry below the merged match expression check that we don't\n # alias any of the entries that it represents.\n merged_match_expression = MatchExpression.get_covering_expression(\n [e.match_expression for e in new_merge]\n )\n n = _get_insertion_index(routing_table, merged_match_expression)\n\n for j, entry in enumerate(routing_table[n:]):\n print(\"Downchecking for {}/{}\\r\".format(\n j + 1, len(routing_table) - n), end='\\r')\n sys.stdout.flush()\n # If this entry is present in the dictionary then we should check\n # that none of the match expressions present in the set of aliased\n # match expressions match against the match expression we are\n # intending to insert. If they do then we give up (though later we\n # can try to remove entries from the merge).\n if entry in made_merges:\n if any(MatchExpression.matches(merged_match_expression, e) for\n e in made_merges[entry]):\n logger.debug(\"Downcheck failed, aborting.\")\n break\n elif MatchExpression.matches(merged_match_expression,\n entry.match_expression):\n break\n else:\n # This merge is feasible, if it's still better than the next\n # possible merge could be then stop!\n refined_merges.append(new_merge)\n\n if i < len(possible_merges) - 1:\n if len(new_merge) >= merge_lens[i+1]:\n break\n\n # Return the best merge or None if no merges exist.\n if len(refined_merges) < 1:\n return None\n else:\n return sorted(refined_merges, key=len)[0]\n\n\ndef _apply_merging_operation(merge, routing_table, allow_core_merging):\n \"\"\"Modify the routing table by adding a new entry for the merged entries\n and then removing the merged entries.\n \"\"\"\n # Copy the routing table\n routing_table = routing_table[:]\n\n # Create the new entry, get its insertion point and insert\n new_entry = _get_routing_table_entry_from_merger(merge, allow_core_merging)\n insert_at = _get_insertion_index(routing_table, new_entry.match_expression)\n routing_table.insert(insert_at, new_entry)\n\n # Remove the old entries\n for entry in merge:\n routing_table.remove(entry)\n\n # Return the new table\n return routing_table\n\n\ndef _get_routing_table_entry_from_merger(merge_entries,\n allow_merge_cores=False):\n \"\"\"Combine routing table entries into a new entry.\n \"\"\"\n # Get the new match expression\n me = MatchExpression.get_covering_expression([e.match_expression for e in\n merge_entries])\n\n # Get new sets of links and cores\n new_links = reduce(operator.or_, [e.links for e in merge_entries])\n new_cores = reduce(operator.or_, [e.cores for e in merge_entries])\n\n # Links should be the same\n assert all(new_links == e.links for e in merge_entries)\n\n # Cores aren't always\n if not allow_merge_cores:\n assert all(new_cores == e.cores for e in merge_entries)\n\n # Create and return the new entry\n return RoutingTableEntry(me, new_cores, new_links, False)\n\n\ndef _update_merges_map(merges_map, new_entry, merges):\n \"\"\"Create a new merges map.\n \"\"\"\n new_map = {k: v for (k, v) in iteritems(merges_map) if k not in merges}\n\n new_mexps = set()\n for m in merges:\n if m in merges_map:\n new_mexps |= merges_map[m]\n else:\n new_mexps.add(m.match_expression)\n\n new_map[new_entry] = new_mexps\n return new_map\n\n\n# Apply this minimisation algorithm to a routing table taken from a file.\nif __name__ == \"__main__\": # pragma : no cover\n import argparse\n import logging\n import re\n\n logging.basicConfig(level=logging.DEBUG)\n logger = logging.getLogger()\n\n # Construct the argument parser to construct call arguments for this\n # routing minimiser.\n parser = argparse.ArgumentParser()\n parser.add_argument('file', help='a routing table to minimise')\n parser.add_argument('masks', help='space separated mask descriptions')\n parser.add_argument('--target', type=int,\n help='number of routing entries to target')\n parser.add_argument('--refine',\n help='remove aliased entries before minimising',\n action='store_true')\n parser.add_argument('--display',\n help='print routing tables before and after',\n action='store_true')\n parser.add_argument('--core-merging',\n help='allow merging of cores in routes',\n action='store_true')\n parser.add_argument('--no-check',\n help=\"don't check for correctness when complete\",\n action='store_true')\n args = parser.parse_args()\n\n # Open the file and construct the routing table\n routing_table = list()\n\n with open(args.file, 'r') as f:\n logging.info(\"Reading routing table.\")\n for line in f:\n data = line.split('#')[0].strip()\n if data != '':\n routing_table.append(RoutingTableEntry.from_str(data))\n\n if args.display:\n print(\"Read routing table:\\n\")\n print(utils.pretty_print_routing_table(routing_table))\n\n if args.refine:\n logging.info(\"Refining routing table prior to minimisation.\")\n routing_table = utils.remove_aliased_entries(routing_table)\n\n if args.display:\n print(\"\\nRefined routing table:\\n\")\n print(utils.pretty_print_routing_table(routing_table))\n\n # Get the masks from the arguments\n range_masks = re.findall(r'\\d+..\\d+', args.masks)\n list_masks = re.findall(r'[\\d,]+\\d', args.masks)\n\n masks = list()\n \"\"\"\n for mask in list_masks:\n masks.append(tuple(map(int, mask.split(','))))\n \"\"\"\n\n for mask in range_masks:\n (a, b) = map(int, mask.split('..'))\n\n if a > b:\n masks.append(tuple(range(b, a+1)[:]))\n else:\n masks.append(tuple(range(a, b+1)[:]))\n\n # Apply minimisation\n logger.info(\"Minimising table using the 'ordered covering' algorithm.\")\n\n start_time = time.time()\n minimised_routing_table = ordered_covering(\n routing_table, masks, target_length=args.target,\n allow_core_fuzziness=args.core_merging)\n run_time = time.time() - start_time\n\n if args.display:\n print(\"\\nMinimised routing table:\\n\")\n print(utils.pretty_print_routing_table(minimised_routing_table))\n\n # Check for correctness\n correct = True\n if not args.no_check:\n logger.info(\"Checking correctness of routing table.\")\n correct = utils.check_routing_table(routing_table,\n minimised_routing_table)\n\n if correct:\n if len(routing_table) > len(minimised_routing_table):\n print(\"\\x1b[32m\")\n else:\n print(\"\\n\")\n print(\"New routing table is correct.\")\n print(\"Original table required {} rows, minimised table requires {} \"\n \"rows.\".format(len(routing_table), len(minimised_routing_table)))\n print(\"\\x1b[39m\")\n else:\n print(\"\\x1b[31;1m!!!New routing table is incorrect!!!\\x1b[39;0m\")\n\n print(\"Minimisation took {:.3f} seconds.\".format(run_time))\n","sub_path":"sprout/ordered_covering.py","file_name":"ordered_covering.py","file_ext":"py","file_size_in_byte":18264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"645730832","text":"import tensorflow as tf\n\nfrom nets.mobilenet_v1 import mobilenet_v1, mobilenet_v1_arg_scope\nfrom tensorflow.contrib import slim\n\n\ndef endpoints(image, is_training):\n if image.get_shape().ndims != 4:\n raise ValueError('Input must be of size [batch, height, width, 3]')\n\n with tf.contrib.slim.arg_scope(mobilenet_v1_arg_scope(batch_norm_decay=0.9, weight_decay=0.0)):\n _, endpoints = mobilenet_v1(image, num_classes=1001, is_training=is_training)\n\n endpoints['reduce_dims'] = tf.squeeze(endpoints['AvgPool_1a'], [1,2], name='reduce_dims')\n\n return endpoints, 'MobilenetV1'\n\n\n\n\n","sub_path":"nets/mobilenet_v1_1_224.py","file_name":"mobilenet_v1_1_224.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"368431099","text":"import errno\nfrom random import randint\n\nimport matplotlib\nimport numpy as np\nimport os\nimport glob\nimport cv2\n\ndef targetPixelList(image):\n x = len(image[0])\n y = len(image)\n pointlist = []\n for i in range(y):\n for j in range(x):\n if(image[i][j] > 100):\n pointlist.append([i,j])\n return pointlist\n\n\ndef createPointLabel(TPL, image):\n y = len(image)\n x = len(image[0])\n patch = np.zeros((y,x))\n # pointpatch = pointPatch\n temp = np.full(( 65 , 65 ), 255 )\n if(len(TPL)>0):\n index = randint(0,len(TPL)-1)\n kernel1d = cv2.getGaussianKernel(65, 7)\n kernel2d = np.outer(kernel1d, kernel1d.transpose())\n\n gaussianPath = temp * kernel2d\n k = 255 / gaussianPath[32][32]\n gaussianPath = k*gaussianPath\n patchY = TPL[index][0]\n patchX = TPL[index][1]\n for j in range(patchY-32, patchY+33):\n for k in range(patchX-32, patchX+33):\n if(j<0 or k<0 or j > y-1 or k>x-1):\n continue\n patch[j][k] = gaussianPath[j-(patchY-32)][k-(patchX-32)]\n return patch\n\nif __name__ == \"__main__\":\n os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_ 0\"] = \"4\"\n maskdirNames = '/home/su_j615/out_focusing/trainmasks'\n # maskdirNames = '/home/su_j615/out_focusing/valmasks'\n dirName = glob.glob(maskdirNames + \"/*\")\n for k in range(4):\n for j in range(len(dirName)):\n fileNames = glob.glob(dirName[j] + \"/*\")\n print(len(fileNames))\n for i in range(len(fileNames)):\n # print(str(i))\n image = cv2.imread(fileNames[i], cv2.IMREAD_GRAYSCALE)\n print(fileNames[i])\n TPL = targetPixelList(image)\n patch = createPointLabel(TPL, image)\n dirpath = dirName[j].replace('trainmasks', 'trainpoints')+'/point'+str(k)\n print(dirpath)\n if not (os.path.isdir(dirpath)):\n os.makedirs(os.path.join(dirpath))\n path = fileNames[i][fileNames[i].rfind('/') + 1:]\n path = dirpath +'/' + path\n print(path)\n cv2.imwrite(path, patch)\n\n","sub_path":"COCO_dataset_preprocessing/foregroundcreatePoint.py","file_name":"foregroundcreatePoint.py","file_ext":"py","file_size_in_byte":2244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"464267312","text":"import numpy as np\nimport os\nimport math\nimport sys\nimport matplotlib.pyplot as plt\n\n#fix seed for consistent datasets\nseed=20210602\nnp.random.seed(seed)\n\nlevel = 'lv2'\ndata_dir = \"resources_data/{}/\".format(level)\nnum_tasks = 2000\nanalysis_dir = \"resources_analysis/{}/\".format(level)\n\ndef generate_data_dir(name, mem):\n\tcores = [4]*num_tasks\n\tvirtual_memory = [0]*num_tasks\n\tdisk = [4000]*num_tasks\n\ttime = [500]*num_tasks\n\taverage_cores = [0]*num_tasks\n\tif not os.path.isdir(data_dir+name):\n\t\tmem_tag = [[math.floor(val), math.floor(tag)] for val, tag in mem]\n\t\tos.mkdir(\"{}{}\".format(data_dir, name))\n\t\tos.mkdir(\"{}{}/data/\".format(data_dir, name))\n\t\twith open(\"{}{}/data/resources_all.txt\".format(data_dir, name), 'w') as f:\n\t\t\tf.write(\"taskid -- core -- memory -- virtual_memory -- disk -- time -- average_cores -- tag\\n\")\n\t\t\tfor i in range(num_tasks):\n\t\t\t\tline = \"{} -- {} -- {} -- {} -- {} -- {} -- {} -- {}\\n\".format(i+1, cores[i], mem_tag[i][0], virtual_memory[i], disk[i], time[i], average_cores[i], mem_tag[i][1])\n\t\t\t\tf.write(line)\n\tif not os.path.isdir(analysis_dir+name):\n\t\tos.mkdir(\"{}{}\".format(analysis_dir, name))\n\t\tos.mkdir(\"{}{}/plots/\".format(analysis_dir, name))\n\t\tos.mkdir(\"{}{}/results/\".format(analysis_dir, name))\n\ndef normal(mean, std, num_tasks):\n\tmem = np.random.normal(mean, std, num_tasks)\n\tmem_tag = [[i, 1] for i in mem]\n\treturn mem_tag\n\ndef uniform(low, high, num_tasks):\n\tmem = np.random.uniform(low, high, num_tasks)\n\tmem_tag = [[i, 1] for i in mem]\n\treturn mem_tag\n\ndef exponential(scale, size):\n\tmem = np.random.exponential(scale, size)\n\tfor i in range(len(mem)):\n\t\tif mem[i] > 64000:\n\t\t\tmem[i] = 64000\n\tmem_tag = [[i, 1] for i in mem]\n\treturn mem_tag\n\ndef beta(a, b, maximum, size):\n\tmem = maximum*np.random.beta(a, b, size)\n\tmem_tag = [[i, 1] for i in mem]\n\treturn mem_tag\n\ndef bimodal(mean1, mean2, std1, std2, num_tasks):\n\tmem1 = np.random.normal(mean1, std1, num_tasks//2)\n\tmem2 = np.random.normal(mean2, std2, num_tasks//2)\n\tmem1_tag = [[i, 1] for i in mem1]\n\tmem2_tag = [[i, 2] for i in mem2]\n\tmem_tag = np.concatenate((mem1_tag, mem2_tag))\n\tnp.random.shuffle(mem_tag)\n\treturn mem_tag\n\ndef trimodal(mean1, mean2, std1, std2, mean3, std3, num_tasks):\n\tmem1 = np.random.normal(mean1, std1, num_tasks//3)\n\tmem2 = np.random.normal(mean2, std2, num_tasks//3)\n\tmem3 = np.random.normal(mean3, std3, num_tasks - 2*(num_tasks//3))\n\tmem1_tag = [[i, 1] for i in mem1]\n\tmem2_tag = [[i, 2] for i in mem2]\n\tmem3_tag = [[i, 3] for i in mem3]\n\tmem_tag = np.concatenate((mem1_tag, mem2_tag, mem3_tag))\n\tnp.random.shuffle(mem_tag)\n\treturn mem_tag\n\ndef uniform_same(low, high, num_classes, num_tasks):\n\tall_mem = []\n\tfor num in range(num_classes):\n\t\tif num == num_classes - 1:\n\t\t\tmem = np.random.uniform(low, high, num_tasks - (num_classes-1)*num_tasks//num_classes)\n\t\telse:\n\t\t\tmem = np.random.uniform(low, high, num_tasks//num_classes)\n\t\tmem_tag = [[i, num+1] for i in mem]\n\t\tall_mem.append(mem_tag)\n\tall_mem_tag = []\n\tfor arr in all_mem:\n\t\tfor pair in arr:\n\t\t\tall_mem_tag.append(pair)\n\tnp.random.shuffle(all_mem_tag)\n\treturn all_mem_tag\n\ngenerate_data_dir(\"normal_large\", normal(32000, 11000, num_tasks))\ngenerate_data_dir(\"normal_small\", normal(8000, 2000, num_tasks))\ngenerate_data_dir(\"uniform_large\", uniform(10000, 40000, num_tasks))\ngenerate_data_dir(\"uniform_small\", uniform(1000, 4000, num_tasks))\ngenerate_data_dir(\"exponential\", exponential(20000, (num_tasks)))\ngenerate_data_dir(\"beta\", beta(8, 2, 40000, num_tasks))\ngenerate_data_dir(\"bimodal\", bimodal(32000, 11000, 8000, 2000, num_tasks))\ngenerate_data_dir(\"trimodal\", trimodal(32000, 11000, 4000, 1000, 16000, 4000, num_tasks))\ngenerate_data_dir(\"bimodal_small_std\", bimodal(32000, 8000, 500, 200, num_tasks))\ngenerate_data_dir(\"trimodal_small_std\", trimodal(32000, 11000, 500, 500, 16000, 500, num_tasks))\ngenerate_data_dir(\"bimodal_same\", bimodal(8000, 8000, 2000, 2000, num_tasks))\ngenerate_data_dir(\"uniform_same\", uniform_same(8000, 9000, 4, num_tasks))\ngenerate_data_dir(\"exponential_small\", exponential(10000, (num_tasks)))\n","sub_path":"data_generation/lv2/generate_synthetic_data.py","file_name":"generate_synthetic_data.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"320222330","text":"\"\"\"\nDjango settings for open_humans project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/dev/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/dev/ref/settings/\n\"\"\"\n\nimport logging\nimport os\nimport sys\n\nfrom distutils import util # pylint: disable=no-name-in-module\n\nimport dj_database_url\n\nfrom env_tools import apply_env\n\n\ndef to_bool(env, default='false'):\n \"\"\"\n Convert a string to a bool.\n \"\"\"\n return bool(util.strtobool(os.getenv(env, default)))\n\n\nclass FakeSite(object):\n \"\"\"\n A duck-typing class to fool things that use django.contrib.sites.\n \"\"\"\n\n name = 'Open Humans'\n\n def __init__(self, domain):\n self.domain = domain\n\n def __unicode__(self):\n return self.name\n\n# Apply the env in the .env file\napply_env()\n\n# Detect when the tests are being run so we can diable certain features\nTESTING = 'test' in sys.argv\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\nPORT = os.getenv('PORT', 8000)\n\nENV = os.getenv('ENV', 'development')\nDOMAIN = os.getenv('DOMAIN', 'localhost:{}'.format(PORT))\n\nDEFAULT_HTTP_PROTOCOL = 'http'\n\nif ENV in ['production', 'staging']:\n # For email template URLs\n DEFAULT_HTTP_PROTOCOL = 'https'\n\nSECRET_KEY = os.getenv('SECRET_KEY')\n\nDEBUG = to_bool('DEBUG')\nOAUTH2_DEBUG = to_bool('OAUTH2_DEBUG')\n\n# This is the default but we need it here to make migrations work\nOAUTH2_PROVIDER_APPLICATION_MODEL = 'oauth2_provider.Application'\n\n# Disable SSL during development\nSSLIFY_DISABLE = ENV not in ['production', 'staging']\n\nLOG_EVERYTHING = to_bool('LOG_EVERYTHING')\n\nDISABLE_CACHING = to_bool('DISABLE_CACHING')\n\nALLOW_TOKEN_REFRESH = to_bool('ALLOW_TOKEN_REFRESH')\n\n# The number of hours after which a direct upload is assumed to be incomplete\n# if the uploader hasn't hit the completion endpoint\nINCOMPLETE_FILE_EXPIRATION_HOURS = 6\n\nif os.getenv('CI_NAME') == 'codeship':\n DISABLE_CACHING = True\n\nconsole_at_info = {\n 'handlers': ['console'],\n 'level': 'INFO',\n}\n\nnull = {\n 'handlers': ['null'],\n}\n\nIGNORE_SPURIOUS_WARNINGS = to_bool('IGNORE_SPURIOUS_WARNINGS')\n\nif LOG_EVERYTHING:\n LOGGING = {\n 'disable_existing_loggers': False,\n 'version': 1,\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n 'level': 'DEBUG',\n },\n },\n 'loggers': {\n '': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': False,\n },\n 'django.db': {\n # django also has database level logging\n },\n },\n }\nelif not TESTING:\n LOGGING = {\n 'disable_existing_loggers': False,\n 'version': 1,\n 'formatters': {\n 'open-humans': {\n '()': 'open_humans.formatters.LocalFormat',\n 'format': '%(levelname)s %(asctime)s %(context)s %(message)s',\n }\n },\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n 'level': 'INFO',\n 'formatter': 'open-humans'\n },\n },\n 'loggers': {\n 'django.request': console_at_info,\n # Log our modules at INFO\n 'common': console_at_info,\n 'data_import': console_at_info,\n 'open_humans': console_at_info,\n 'public_data': console_at_info,\n },\n }\nelse:\n LOGGING = {\n 'disable_existing_loggers': True,\n 'version': 1,\n 'formatters': {},\n 'handlers': {\n 'null': {\n 'class': 'logging.NullHandler'\n },\n },\n 'loggers': {\n 'django.request': null,\n 'common': null,\n 'data_import': null,\n 'open_humans': null,\n 'public_data': null,\n }\n }\n\nif IGNORE_SPURIOUS_WARNINGS:\n LOGGING['handlers']['null'] = {\n 'class': 'logging.NullHandler'\n }\n\n LOGGING['loggers']['py.warnings'] = {\n 'handlers': ['null']\n }\n\nif OAUTH2_DEBUG:\n oauth_log = logging.getLogger('oauthlib')\n\n oauth_log.addHandler(logging.StreamHandler(sys.stdout))\n oauth_log.setLevel(logging.DEBUG)\n\nALLOWED_HOSTS = ['*']\n\nMANAGERS = ()\nADMINS = ()\n\nINSTALLED_APPS = (\n 'open_humans',\n\n # Studies\n #'studies',\n #'studies.american_gut',\n #'studies.go_viral',\n #'studies.pgp',\n #'studies.wildlife',\n\n # Activities\n #'activities',\n #'activities.data_selfie',\n #'activities.fitbit',\n #'activities.jawbone',\n #'activities.moves',\n #'activities.mpower',\n #'activities.runkeeper',\n #'activities.withings',\n #'activities.twenty_three_and_me',\n #'activities.ancestry_dna',\n #'activities.ubiome',\n #'activities.vcf_data',\n\n # Other local apps\n 'data_import',\n 'private_sharing',\n 'public_data',\n\n # gulp integration\n 'django_gulp',\n\n # Django built-ins\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.humanize',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n # Third-party modules\n 'account',\n 'bootstrap_pagination',\n 'captcha',\n 'corsheaders',\n # 'debug_toolbar.apps.DebugToolbarConfig',\n 'django_extensions',\n 'django_forms_bootstrap',\n 'django_hash_filter',\n 'oauth2_provider',\n 'rest_framework',\n 's3upload',\n 'social.apps.django_app.default',\n 'sorl.thumbnail',\n)\n\nif not TESTING:\n INSTALLED_APPS = INSTALLED_APPS + ('raven.contrib.django.raven_compat',)\n\n RAVEN_CONFIG = {\n 'dsn': os.getenv('SENTRY_DSN'),\n 'processors': (\n 'common.processors.SanitizeEnvProcessor',\n 'raven.processors.SanitizePasswordsProcessor',\n )\n }\n\nMIDDLEWARE_CLASSES = (\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n\n # 'debug_toolbar.middleware.DebugToolbarMiddleware',\n 'sslify.middleware.SSLifyMiddleware',\n\n 'open_humans.middleware.RedirectStealthToProductionMiddleware',\n 'open_humans.middleware.RedirectStagingToProductionMiddleware',\n\n 'django.middleware.cache.UpdateCacheMiddleware',\n\n 'corsheaders.middleware.CorsMiddleware',\n\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n\n # Must come before AuthenticationMiddleware\n 'open_humans.middleware.QueryStringAccessTokenToBearerMiddleware',\n\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n\n 'account.middleware.LocaleMiddleware',\n 'account.middleware.TimezoneMiddleware',\n\n 'open_humans.middleware.AddMemberMiddleware',\n 'open_humans.middleware.PGPInterstitialRedirectMiddleware',\n\n 'django.middleware.cache.FetchFromCacheMiddleware',\n)\n\ntemplate_context_processors = [\n 'account.context_processors.account',\n\n 'social.apps.django_app.context_processors.backends',\n 'social.apps.django_app.context_processors.login_redirect',\n\n 'django.template.context_processors.request',\n\n 'django.contrib.auth.context_processors.auth',\n\n 'django.template.context_processors.debug',\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.media',\n 'django.template.context_processors.static',\n 'django.template.context_processors.tz',\n\n 'django.contrib.messages.context_processors.messages',\n]\n\ntemplate_loaders = [\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n]\n\n# Don't cache templates during development\nif not DEBUG and not DISABLE_CACHING:\n template_loaders = [\n ('django.template.loaders.cached.Loader', template_loaders)\n ]\n\ntemplate_options = {\n 'context_processors': template_context_processors,\n 'debug': DEBUG,\n 'loaders': template_loaders,\n}\n\nNOBROWSER = to_bool('NOBROWSER', 'false')\n\nif TESTING:\n from .testing import InvalidString # pylint: disable=wrong-import-position\n\n template_options['string_if_invalid'] = InvalidString('%s')\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'OPTIONS': template_options,\n },\n # {\n # 'BACKEND': 'django.template.backends.jinja2.Jinja2',\n # 'OPTIONS': {\n # 'loader': template_loaders\n # },\n # },\n]\n\nROOT_URLCONF = 'open_humans.urls'\n\nWSGI_APPLICATION = 'open_humans.wsgi.application'\n\n# Use DATABASE_URL to do database setup, for a local Postgres database it would\n# look like: postgres://localhost/database_name\nDATABASES = {}\n\n# Only override the default if there's a database URL specified\nif os.getenv('CI_NAME') == 'codeship':\n DATABASES['default'] = {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'test',\n 'USER': os.getenv('PG_USER'),\n 'PASSWORD': os.getenv('PG_PASSWORD'),\n 'HOST': '127.0.0.1',\n 'PORT': 5434\n }\nelif dj_database_url.config():\n DATABASES['default'] = dj_database_url.config()\n\n# Internationalization\n# https://docs.djangoproject.com/en/dev/topics/i18n/\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static-files')\n\nSTATICFILES_DIRS = (\n # Do this one manually since bootstrap wants it in ../fonts/\n ('fonts', os.path.join(BASE_DIR, 'node_modules', 'bootstrap', 'dist',\n 'fonts')),\n ('images', os.path.join(BASE_DIR, 'static', 'images')),\n\n # Local apps\n ('public-data', os.path.join(BASE_DIR, 'public_data', 'static')),\n ('direct-sharing', os.path.join(BASE_DIR, 'private_sharing', 'static')),\n\n os.path.join(BASE_DIR, 'build'),\n)\n\nSTATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\n\nSTATIC_URL = '/static/'\n\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\nLOGIN_URL = 'account_login'\nLOGIN_REDIRECT_URL = 'home'\n\nAUTH_USER_MODEL = 'open_humans.User'\n\nACCOUNT_LOGIN_REDIRECT_URL = LOGIN_REDIRECT_URL\nACCOUNT_OPEN_SIGNUP = to_bool('ACCOUNT_OPEN_SIGNUP', 'true')\nACCOUNT_PASSWORD_MIN_LEN = 8\nACCOUNT_SIGNUP_REDIRECT_URL = 'home'\nACCOUNT_HOOKSET = 'open_humans.hooksets.OpenHumansHookSet'\nACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = 'home'\nACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = 'home'\nACCOUNT_USE_AUTH_AUTHENTICATE = True\n\n# We want CREATE_ON_SAVE to be True (the default) unless we're using the\n# `loaddata` command--because there's a documented issue in loading fixtures\n# that include accounts:\n# http://django-user-accounts.readthedocs.org/en/latest/usage.html#including-accounts-in-fixtures\nACCOUNT_CREATE_ON_SAVE = sys.argv[1:2] != ['loaddata']\n\nDEFAULT_FROM_EMAIL = 'Open Humans '\n\nEMAIL_USE_TLS = True\n\nEMAIL_HOST = 'smtp.mailgun.org'\nEMAIL_HOST_USER = 'no-reply@openhumans.org'\nEMAIL_HOST_PASSWORD = os.getenv('MAILGUN_PASSWORD')\nEMAIL_PORT = 587\n\n# Fall back to console emails for development without mailgun set.\nif DEBUG and not EMAIL_HOST_PASSWORD:\n EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n# TODO: Collect these programatically\nOAUTH2_PROVIDER = {\n 'SCOPES': {\n 'read': 'Read Access',\n 'write': 'Write Access',\n 'american-gut': 'American Gut',\n 'go-viral': 'GoViral',\n 'pgp': 'Harvard Personal Genome Project',\n 'wildlife': 'Wildlife of Our Homes',\n 'open-humans': 'Open Humans',\n },\n 'AUTHORIZATION_CODE_EXPIRE_SECONDS': 60 * 30,\n 'REQUEST_APPROVAL_PROMPT': 'auto',\n 'ALLOWED_REDIRECT_URI_SCHEMES': [\n 'http', 'https',\n # Redirect URIs that are using iOS or Android app-registered schema\n 'openhumanshk', 'resilienceproject',\n ],\n}\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'oauth2_provider.ext.rest_framework.OAuth2Authentication',\n ),\n 'DEFAULT_PAGINATION_CLASS':\n 'rest_framework.pagination.LimitOffsetPagination',\n 'PAGE_SIZE': 100,\n 'TEST_REQUEST_DEFAULT_FORMAT': 'json',\n}\n\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n 'social.backends.jawbone.JawboneOAuth2',\n 'social.backends.moves.MovesOAuth2',\n 'social.backends.runkeeper.RunKeeperOAuth2',\n 'common.oauth_backends.WithingsOAuth1',\n 'common.oauth_backends.FitbitOAuth2',\n)\n\nGO_VIRAL_MANAGEMENT_TOKEN = os.getenv('GO_VIRAL_MANAGEMENT_TOKEN')\n\nDATA_PROCESSING_URL = os.getenv('DATA_PROCESSING_URL')\n\nDEFAULT_FILE_STORAGE = 'open_humans.storage.PrivateStorage'\n\n# COLORSPACE and PRESERVE_FORMAT to avoid transparent PNG turning black, see\n# https://stackoverflow.com/questions/26762180/sorl-thumbnail-generates-black-square-instead-of-image\nTHUMBNAIL_STORAGE = 'open_humans.storage.PublicStorage'\nTHUMBNAIL_FORCE_OVERWRITE = True\nTHUMBNAIL_COLORSPACE = None\nTHUMBNAIL_PRESERVE_FORMAT = True\n\nAWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID')\nAWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY')\nAWS_STORAGE_BUCKET_NAME = os.getenv('AWS_S3_STORAGE_BUCKET_NAME')\n\n# \"On projects behind a reverse proxy that uses HTTPS, the redirect URIs can\n# became with the wrong schema (http:// instead of https://) when the request\n# lacks some headers, and might cause errors with the auth process, to force\n# HTTPS in the final URIs set this setting to True\"\nif ENV in ['production', 'staging']:\n SOCIAL_AUTH_REDIRECT_IS_HTTPS = True\n\nSOCIAL_AUTH_ADMIN_USER_SEARCH_FIELDS = ['username', 'first_name', 'email']\n\nSOCIAL_AUTH_PIPELINE = (\n 'social.pipeline.social_auth.social_details',\n 'social.pipeline.social_auth.social_uid',\n 'social.pipeline.social_auth.auth_allowed',\n 'social.pipeline.social_auth.social_user',\n\n # Not needed unless we're auto-creating users\n # 'social.pipeline.user.get_username',\n\n # NOTE: this might be useful for UYG\n # Associates the current social details with another user account with\n # a similar email address.\n # 'social.pipeline.social_auth.associate_by_email',\n\n # If `create_user` is included in the pipeline then social will create new\n # accounts if the user isn't logged into Open Humans--meaning that if a\n # user logs in with RunKeeper they get an auto-generated Open Humans\n # account, which isn't the behavior we want.\n # 'social.pipeline.user.create_user',\n\n 'social.pipeline.social_auth.associate_user',\n 'social.pipeline.social_auth.load_extra_data',\n 'social.pipeline.user.user_details',\n)\n\nSOCIAL_AUTH_FITBIT_KEY = os.getenv('FITBIT_ID')\nSOCIAL_AUTH_FITBIT_SECRET = os.getenv('FITBIT_SECRET')\n\nSOCIAL_AUTH_FITBIT_SCOPE = [\n # The activity scope includes activity data and exercise log related\n # features, such as steps, distance, calories burned, and active minutes\n 'activity',\n # The heartrate scope includes the continuous heart rate data and related\n # analysis\n 'heartrate',\n # The location scope includes the GPS and other location data\n 'location',\n # The nutrition scope includes calorie consumption and nutrition related\n # features, such as food/water logging, goals, and plans\n 'nutrition',\n # The profile scope is the basic user information\n # 'profile',\n # The settings scope includes user account and device settings, such as\n # alarms\n # 'settings',\n # The sleep scope includes sleep logs and related sleep analysis\n 'sleep',\n # The social scope includes friend-related features, such as friend list,\n # invitations, and leaderboard\n # 'social',\n # The weight scope includes weight and related information, such as body\n # mass index, body fat percentage, and goals\n 'weight',\n]\n\nSOCIAL_AUTH_JAWBONE_KEY = os.getenv('JAWBONE_ID')\nSOCIAL_AUTH_JAWBONE_SECRET = os.getenv('JAWBONE_SECRET')\n\nSOCIAL_AUTH_JAWBONE_SCOPE = [\n 'basic_read',\n 'extended_read',\n 'generic_event_read',\n 'heartrate_read',\n 'location_read',\n 'meal_read',\n 'mood_read',\n 'move_read',\n 'sleep_read',\n 'weight_read',\n]\n\nSOCIAL_AUTH_MOVES_SCOPE = [\n 'activity',\n 'location',\n]\n\nSOCIAL_AUTH_MOVES_KEY = os.getenv('MOVES_ID')\nSOCIAL_AUTH_MOVES_SECRET = os.getenv('MOVES_SECRET')\n\nSOCIAL_AUTH_RUNKEEPER_KEY = os.getenv('RUNKEEPER_ID')\nSOCIAL_AUTH_RUNKEEPER_SECRET = os.getenv('RUNKEEPER_SECRET')\n\nSOCIAL_AUTH_WITHINGS_KEY = os.getenv('WITHINGS_ID')\nSOCIAL_AUTH_WITHINGS_SECRET = os.getenv('WITHINGS_SECRET')\n\n# Allow Cross-Origin requests (for our API integrations)\nCORS_ORIGIN_ALLOW_ALL = True\n\n# Custom CSRF Failure page\nCSRF_FAILURE_VIEW = 'open_humans.views.csrf_error'\n\n# ...but only for the API URLs\nCORS_URLS_REGEX = r'^/api/.*$'\n\nSITE = FakeSite(DOMAIN)\nSITE_ID = 1\n\n# This way of setting the memcache options is advised by MemCachier here:\n# https://devcenter.heroku.com/articles/memcachier#django\nif ENV in ['production', 'staging']:\n memcache_servers = os.getenv('MEMCACHIER_SERVERS', '').replace(',', ';')\n\n memcache_username = os.getenv('MEMCACHIER_USERNAME')\n memcache_password = os.getenv('MEMCACHIER_PASSWORD')\n\n if memcache_servers:\n os.environ['MEMCACHE_SERVERS'] = memcache_servers\n\n if memcache_username and memcache_password:\n os.environ['MEMCACHE_USERNAME'] = memcache_username\n os.environ['MEMCACHE_PASSWORD'] = memcache_password\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django_pylibmc.memcached.PyLibMCCache',\n 'BINARY': True,\n 'OPTIONS': {\n 'ketama': True,\n 'tcp_nodelay': True,\n }\n }\n}\n\nif DISABLE_CACHING:\n CACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',\n }\n }\n\nCACHE_MIDDLEWARE_SECONDS = 30 * 60\n\nSESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'\n\nTEST_RUNNER = 'open_humans.OpenHumansDiscoverRunner'\n\n# For redirecting staging URLs with production client IDs to production; this\n# helps us transition new integrations from staging to production\nPRODUCTION_CLIENT_IDS = os.getenv('PRODUCTION_CLIENT_IDS', '').split(' ')\nPRODUCTION_URL = os.getenv('PRODUCTION_URL')\n\nMAILCHIMP_API_KEY = os.getenv('MAILCHIMP_API_KEY')\nMAILCHIMP_NEWSLETTER_LIST = os.getenv('MAILCHIMP_NEWSLETTER_LIST')\n\nNOCAPTCHA = True\n\nRECAPTCHA_PUBLIC_KEY = os.getenv('RECAPTCHA_PUBLIC_KEY')\nRECAPTCHA_PRIVATE_KEY = os.getenv('RECAPTCHA_PRIVATE_KEY')\n\nZAPIER_WEBHOOK_URL = os.getenv('ZAPIER_WEBHOOK_URL')\n\nMAX_UNAPPROVED_MEMBERS = int(os.getenv('MAX_UNAPPROVED_MEMBERS', '20'))\n\n# Highlighted projects\nPROJ_FEATURED = os.getenv('PROJ_FEATURED', None)\n\n# The key used to communicate between this site and data-processing\nPRE_SHARED_KEY = os.getenv('PRE_SHARED_KEY')\n\n# Import settings from local_settings.py; these override the above\ntry:\n # pylint: disable=wildcard-import,wrong-import-position\n from local_settings import * # NOQA\nexcept ImportError:\n pass\n","sub_path":"open_humans/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":19274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"594015222","text":"\"\"\"An entry point for the qa module\"\"\"\n\nimport argparse\nfrom espa_validation.validate_data.qa import qa_data\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n required_named = parser.add_argument_group(\"Required named arguments\")\n\n required_named.add_argument(\"-m\", dest=\"dir_mast\", type=str, required=True, action=\"store\",\n help=\"The full path to the Master directory\")\n\n required_named.add_argument(\"-t\", dest=\"dir_test\", type=str, required=True, action=\"store\",\n help=\"The full path to the Test directory\")\n\n required_named.add_argument(\"-o\", dest=\"dir_out\", type=str, required=True, action=\"store\",\n help=\"The full path to the Results directory\")\n\n parser.add_argument(\"-x\", dest=\"xml_schema\", type=str, required=False, action=\"store\",\n help=\"Full path to XML schema\")\n\n parser.add_argument(\"--no-archive\", dest=\"archive\", required=False, action=\"store_false\",\n help=\"Look for individual files insead of g-zipped archives\")\n\n parser.add_argument(\"--verbose\", dest=\"verbose\", required=False, action=\"store_true\",\n help=\"Enable verbose logging\")\n\n parser.add_argument(\"--include-nodata\", dest=\"incl_nd\", required=False, action=\"store_true\",\n help=\"Do not mask NoData values\")\n\n args = parser.parse_args()\n\n qa_data(**vars(args))\n\n return None\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"espa_validation/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"601308832","text":"# Python\nimport logging\n\n# Logger\nlog = logging.getLogger(__name__)\n# unicon\nfrom unicon.core.errors import SubCommandFailure\n\ndef extract_tar_gz(device, path, files, option='-zxvf'):\n \"\"\" extract tar.gz file\n Args:\n files (`list`): list of tar.gz files\n option (`str`): option to tar command for extraction\n Default to `-zxvf`\n Raises:\n N/A\n Returns:\n extracted_files (`list`): extracted file list\n \"\"\"\n extracted_files = []\n\n log.debug('files : {f}'.format(f=files))\n\n for file in files:\n # check if the file has extention `.tar.gz`\n if '.tar.gz' not in file:\n raise Exception('file {f} is not tar.gz file'.format(f=file))\n # create folder_name from filename\n folder_name = file.split('.tar.gz')[0]\n # extract tar.gz file\n output = device.api.execute(\"cd {p} && mkdir {d} && cd {d} && tar {op} ../{f}\".\\\n format(p=path, d=folder_name, op=option, f=file))\n # based on output, `extracted_files` list will be created as return\n if output:\n for file in output.split():\n extracted_files.append('{p}/{d}/{f}'.format(p=path,\n d=folder_name,\n f=file))\n if 'cannot create directory' in output:\n raise Exception(\n \"Directory {d} already exists and couldn't create\".format(\n d=folder_name))\n\n return extracted_files\n\ndef execute_by_jinja2(device, templates_dir, template_name, post_commands=None, failure_commands=None, **kwargs):\n \"\"\" Configure using Jinja template\n Args:\n device ('obj'): Device object\n templates_dir ('str'): Template directory\n template_name ('str'): Template name\n post_commands ('list'): List of post commands\n failure_commands ('list'): List of commands required after failure\n kwargs ('obj'): Keyword arguments\n Returns:\n Boolean\n Raises:\n None\n \"\"\"\n\n log.info(\"Configuring {filename} on {device}\".format(\n filename=template_name,\n device=device.alias))\n template = device.api.get_jinja_template(\n templates_dir=templates_dir,\n template_name=template_name)\n \n if not template:\n raise Exception('Could not get template')\n\n timeout = kwargs.pop('timeout', None)\n out = [x.lstrip() for x in template.render(**kwargs).splitlines()]\n\n if post_commands:\n out = out + post_commands\n \n try:\n for cmd in out:\n if timeout:\n log.info('{} timeout value used for device: {}'.format(\n timeout, device.name))\n device.execute(cmd, timeout=timeout)\n else:\n device.execute(cmd)\n except SubCommandFailure as e:\n if failure_commands:\n device.execute(failure_commands) \n raise SubCommandFailure(\n \"Failed in applying the following \"\n \"configuration:\\n{config}, error:\\n{e}\".format(config=out, e=e)\n )\n\n log.info(\"Successfully changed configuration using the jinja template\")\n\ndef get_md5_hash_of_file(device, file, timeout=60):\n \"\"\" Return the MD5 hash of a given file.\n\n Args:\n device (obj): Device to execute on\n file (str): File to calculate the MD5 on\n timeout (int, optional): Max time in seconds allowed for calculation.\n Defaults to 60.\n\n Returns:\n MD5 hash (str), or None if something went wrong\n \"\"\"\n # md5sum test_file.bin\n # 5a06abf1ce541d311de335ce6bd9997a /test_file.bin\n try:\n return device.execute('md5sum {}'.format(file),\n timeout=timeout).split()[0]\n except Exception as e:\n log.warning(e)\n return None\n","sub_path":"pkgs/sdk-pkg/src/genie/libs/sdk/apis/linux/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"316509352","text":"# code-checked\n# server-checked\n\nfrom model import ToyNet\n\nimport torch\nimport torch.utils.data\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nimport numpy as np\nimport pickle\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport cv2\n\nimport numpy as np\n\nx_min = -6.0\nx_max = 6.0\nnum_points = 60\n\nM_values = [1, 4, 16, 64, 256]\nfor M in M_values:\n for iter in range(6):\n network_inds = list(np.random.randint(low=0, high=1024, size=(M, )))\n print (network_inds)\n\n networks = []\n for i in network_inds:\n network = ToyNet(\"eval_Ensemble-MAP-SGDMOM_1_M1024\", project_dir=\"/root/evaluating_bdl/toyClassification\").cuda()\n network.load_state_dict(torch.load(\"/root/evaluating_bdl/toyClassification/training_logs/model_Ensemble-MAP-SGDMOM_1_M1024_%d/checkpoints/model_Ensemble-MAP-SGDMOM_1_M1024_epoch_150.pth\" % i))\n networks.append(network)\n\n M_float = float(len(networks))\n print (M_float)\n\n for network in networks:\n network.eval()\n\n false_prob_values = np.zeros((num_points, num_points))\n x_values = np.linspace(x_min, x_max, num_points, dtype=np.float32)\n for x_1_i, x_1_value in enumerate(x_values):\n for x_2_i, x_2_value in enumerate(x_values):\n x = torch.from_numpy(np.array([x_1_value, x_2_value])).unsqueeze(0).cuda() # (shape: (1, 2))\n\n mean_prob_vector = np.zeros((2, ))\n for network in networks:\n logits = network(x) # (shape: (1, num_classes)) (num_classes==2)\n prob_vector = F.softmax(logits, dim=1) # (shape: (1, num_classes))\n\n prob_vector = prob_vector.data.cpu().numpy()[0] # (shape: (2, ))\n\n mean_prob_vector += prob_vector/M_float\n\n false_prob_values[x_2_i, x_1_i] = mean_prob_vector[0]\n\n plt.figure(1)\n x_1, x_2 = np.meshgrid(x_values, x_values)\n plt.pcolormesh(x_1, x_2, false_prob_values, cmap=\"RdBu\", vmin=0, vmax=1)\n plt.colorbar()\n plt.tight_layout(pad=0.1, w_pad=0.1, h_pad=0.1)\n plt.savefig(\"%s/predictive_density_M=%d_%d.png\" % (network.model_dir, M, iter+1))\n plt.close(1)\n\n print (\"##################################################################\")\n","sub_path":"toyClassification/Ensemble-MAP-SGDMOM/eval_plots.py","file_name":"eval_plots.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"601946144","text":"import streamlit as st\nimport pandas as pd\nimport europresse\nfrom io import StringIO\n\n# Fonction convertissat en format csv et mis en chache\n@st.cache_data\ndef convert_df(df):\n return df.to_csv(index=False).encode('utf-8')\n\nst.title('Transformation des fichiers europresse HTML > CSV')\nst.write(\"Les fichiers doivent être en HTML dans le format de sortie d'Europresse/version classique\")\nst.write(\"Le traitement utilise BeautifulSoup / Pandas / Streamlit\")\n\n# Chargement de données multiples\nuploaded_files = st.file_uploader(\"Choisir un/des fichiers HTML Europesse\", accept_multiple_files=True)\n\ncorpus = []\n\nif len(uploaded_files)>0:\n for uploaded_file in uploaded_files:\n st.write(\"filename:\", uploaded_file.name)\n corpus += europresse.extract(uploaded_file)\n\n st.write(\"Taille du corpus %d\"%len(corpus))\n df = europresse.get_table(corpus)\n csv = convert_df(df)\n st.download_button(\n \"Télécharger le tableau en csv\",\n csv,\n \"tableau.csv\",\n \"text/csv\",\n key='download-csv'\n )","sub_path":"scripts/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"239941054","text":"#!/usr/bin/env python3\n\n# Multiples of 3 and 5\n# Problem 1 \n# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. \n# The sum of these multiples is 23.\n# Find the sum of all the multiples of 3 or 5 below 1000\n\nmax = 1000\nsum = 0\n\nfor x in range(1,max):\n if x % 3 == 0:\n sum = sum + x\n elif x % 5 == 0:\n sum = sum + x\n\nprint(sum)","sub_path":"001.py","file_name":"001.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"122427328","text":"\"\"\"\nFile to fill with fun clickbait analysis!\nLove, Lucino\n\"\"\"\n\nfrom newsapi import NewsApiClient\nimport nltk\nfrom nltk.tag import pos_tag\nfrom nltk.tokenize import word_tokenize\nimport random\nimport pickle\nfrom collections import Counter\nfrom nltk.corpus import stopwords\n\ncommon_bigrams = []\n\n\"\"\"\nOpens the pickled file and shuffles it up, returning a list of labeled headlines\n\"\"\"\n\n\ndef create_labeled_data():\n all_headlines = pickle.load(open('headlines.p', 'rb'))\n random.shuffle(all_headlines)\n return all_headlines\n\n\ndef build_source(source):\n source_headlines = []\n news_api = NewsApiClient(api_key='063f02817dbb49528058d7372964f645')\n x = 1\n while x <= 4:\n s_headlines = \\\n news_api.get_everything(sources=source, from_param='2018-11-19', to='2018-12-19',\n language='en',\n sort_by='relevancy', page_size=100, page=x)['articles']\n s_titles = [article['title'] for article in s_headlines]\n s_titles = list(filter(None.__ne__, s_titles))\n source_headlines.extend(s_titles)\n x += 1\n return source_headlines\n\n\"\"\"\nGenerate bigrams based on the training data, then \n\"\"\"\n\n\ndef create_feature_sets(labeled_data):\n common = get_bigrams(labeled_data)\n common_bigrams.extend(common)\n feature_sets = [(bait_features(headline), label) for (headline, label) in labeled_data]\n train_set, test_set = feature_sets[:2700], feature_sets[2700:]\n return train_set, test_set\n\n\n#pulls out most frequent bigrams from the training set each time (they are almost always the same!)\ndef get_bigrams(lst):\n training = lst[:2700]\n training = [w for w in training if w[1] == 'bait']\n training = [w[0] for w in training]\n raw = \" \".join(training)\n tokens = raw.split(\" \")\n bigrams = list(nltk.bigrams(tokens))\n fdist = nltk.FreqDist(bigrams)\n most_common = fdist.most_common(25)\n common_bigrams = [x[0] for x in most_common]\n return common_bigrams\n\n\ndef bait_features(headline):\n featureset = {}\n featureset['procount'] = procount(headline)\n featureset['punct'] = punct(headline)\n featureset['averagewordlength'] = averagewordlength(headline)\n featureset['mostcommontag'] = mostcommontag(headline)\n featureset['wh'] = wh(headline)\n featureset['startswithnum'] = startswithnum(headline)\n featureset['imperative'] = imperative(headline)\n featureset['bigrams'] = bigrams(headline)\n featureset['function_words'] = function_words(headline)\n featureset['flag_words'] = flag_words(headline)\n return featureset\n\n# Checks for the use of first and second-person pronouns in article headline; returns true if any found.\ndef procount(headline):\n pronouns = [\"we\", \"you\", \"i\", \"everyone\", \"us\", \"your\", \"our\"]\n for w in word_tokenize(headline):\n if w.lower() in pronouns:\n return True\n return False\n\n\n# Checks end-of-sentence punctuation count in headline; returns true if count is greater than 0.\ndef punct(headline):\n count = 0\n punct = [\".\", \"!\", \"?\"]\n for w in word_tokenize(headline):\n if w in punct:\n count += 1\n return count > 0\n\n\n# Checks whether the headline starts with a digit; returns true if so.\ndef startswithnum(headline):\n tags = [w[1] for w in pos_tag(word_tokenize(headline))]\n if tags[0] == 'CD':\n return True\n return False\n\n\n# Calculates average word length within headline; returns true if the average is greater than 4.\ndef averagewordlength(headline):\n charactercount = 0\n wordcount = 0\n commonshortwords = [\"the\", \"a\", \"for\", \"an\", \"of\", \"and\", \"so\", \"but\", \"with\", \",\", \".\", \":\", \";\"]\n for w in word_tokenize(headline):\n if w.lower() not in commonshortwords:\n charactercount += len(w)\n wordcount += 1\n avg = charactercount / wordcount\n return avg < 4\n\n\n# Checks for the most common POS tag in the headline; returns true if the most common tag is NN.\ndef mostcommontag(headline):\n tags = [w[1] for w in pos_tag(word_tokenize(headline))]\n counts = Counter(tags)\n return counts.most_common()[0][0] == \"NN\"\n\n\n# Checks for the use of superlative adjectives in the headline; returns true if any found.\ndef superlative(headline):\n tags = [w[1] for w in pos_tag(word_tokenize(headline))]\n for tag in tags:\n if tag == 'JJS' or tag == 'RBS':\n return True\n return False\n\n\n# Checks for the use of wh-words in the headline; returns true if any found.\ndef wh(headline):\n tags = [w[1] for w in pos_tag(word_tokenize(headline))]\n for tag in tags:\n if tag == 'WP':\n return True\n return False\n\n\n# Checks whether the first word in a headline is tagged as a bare-form verb, indicating an imperative;\n# returns true if it is.\ndef imperative(headline):\n tags = [w[1] for w in pos_tag(word_tokenize(headline))]\n if tags[0] == 'VB':\n return True\n return False\n\n\n# Checks all bigrams in the headline, and compares them against a list of most common clickbait bigrams. Returns\n# true if any match.\ndef bigrams(headline):\n bigrams = nltk.bigrams(headline.split(\" \"))\n\n for x in bigrams:\n if x in common_bigrams:\n return True\n return False\n\n\n# Calculates proportion of word in headline that are stopwords or function words\ndef function_words(headline):\n fun_words = [w for w in [word.lower() for word in word_tokenize(headline)] if w in stopwords.words('english')]\n #return len(fun_words)/len(word_tokenize(headline))\n return True if (len(fun_words)/len(word_tokenize(headline)) == .5) else False\n\n\ndef flag_words(headline):\n flags = ['this', 'will', 'believe', 'surprise']\n found = False\n for word in word_tokenize(headline):\n word = word.lower()\n if word in flags:\n found = True\n return found\n\n\ndef train_classifier(training_set):\n classifier = nltk.NaiveBayesClassifier.train(training_set)\n return classifier\n\n\ndef evaluate_classifier(classifier, test_set):\n print(nltk.classify.accuracy(classifier, test_set))\n\n\ndef classify_headlines(lines, classifier):\n features = [bait_features(line) for line in lines]\n label_list = []\n for feat in features:\n label_list.append(classifier.classify(feat))\n bait_count = label_list.count('bait')\n return bait_count/len(label_list)\n\n\nif __name__ == '__main__':\n labeled_data = create_labeled_data()\n training_set, test_set = create_feature_sets(labeled_data)\n # classifier = train_classifier(training_set)\n # evaluate_classifier(classifier, test_set)\n # classifier.show_most_informative_features(20)\n\n # opens a ready-trained classifier to save time on training and evaluating.\n # uncomment the above lines and run the program to see a 'new' classifier's\n # accuracy!\n classifier = pickle.load( open('trained_classifier.p', 'rb'))\n source = input('Welcome to the Clickbait Classifier! '\n 'Choose a news source to classify from sources.txt.\\n')\n\n print('The headlines found from this source are about ' +\n str(classify_headlines(build_source(source), classifier)*100) + '% clickbait!')\n\n\n\n","sub_path":"nlp-final-slam/clickbait.py","file_name":"clickbait.py","file_ext":"py","file_size_in_byte":7171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"575693330","text":"# Programa para carga de datos en BBDD SQLite\n\nimport sqlite3\n\n# - - - - - - - - - - Prog. Principal - - - - - - - \n\nconectado=sqlite3.connect(\"SistemaExpo\")\npuntero=conectado.cursor()\npuntero.execute(''' \nCREATE TABLE Item_Pedido(\nid\t integer primary key autoincrement,\nid_pedido integer NOT NULL,\ncod_producto\tVARCHAR(10) NOT NULL,\ncantidad\tinteger NOT NULL,\nprecio\tREAL NOT NULL)''')\n\nconectado.commit()\nconectado.close()\n\n\n\n","sub_path":"Inicios/ini_items pedido.py","file_name":"ini_items pedido.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"277124523","text":"# --------------------------------\n# Name: PPA2_masterTest.py\n# Purpose: get values for the \"trip shed\" for freeway projects based on trip table\n# estimated by \"big data\" model such as Google Replica, Streetlight, etc.\n#\n# Author: Darren Conly\n# Last Updated: \n# Updated by: \n# Copyright: (c) SACOG\n# Python Version: 3.x\n# --------------------------------\nimport datetime as dt\nimport os\n\nimport arcpy\nimport pandas as pd\n\nimport ppa_input_params as params\nimport accessibility_calcs as acc\nimport get_lutype_acres as luac\nimport landuse_buff_calcs as lu_pt_buff\nimport mix_index_for_project as mixidx\nimport urbanization_metrics as urbn\nimport ppa_utils as utils\n \n\ndef get_singleyr_data(fc_tripshedpoly, projtyp, analysis_year, out_dict_base={}):\n fc_pcl_pt = params.parcel_pt_fc_yr(analysis_year)\n fc_pcl_poly = params.parcel_poly_fc_yr(analysis_year)\n \n print(\"getting accessibility data for base...\")\n accdata = acc.get_acc_data(fc_tripshedpoly, params.accdata_fc, projtyp, get_ej=False)\n \n print(\"getting ag acreage data for base...\")\n ag_acres = luac.get_lutype_acreage(fc_tripshedpoly, projtyp, fc_pcl_poly, params.lutype_ag)\n \n # total job + du density (base year only, for state-of-good-repair proj eval only)\n print(\"getting ILUT data for base...\")\n job_du_dens = lu_pt_buff.point_sum_density(fc_pcl_pt, fc_tripshedpoly, projtyp, \n [params.col_emptot, params.col_du], params.ilut_sum_buffdist)\n comb_du_dens = sum(list(job_du_dens.values()))\n job_du_dens['job_du_perNetAcre'] = comb_du_dens\n\n # get EJ data\n print(\"getting EJ data for base...\")\n ej_data = lu_pt_buff.point_sum(fc_pcl_pt, fc_tripshedpoly, projtyp, [params.col_pop_ilut],\n params.ilut_sum_buffdist, params.col_ej_ind, case_excs_list=[])\n \n ej_flag_dict = {0: \"Pop_NonEJArea\", 1: \"Pop_EJArea\"} # rename keys from 0/1 to more human-readable names\n ej_data = utils.rename_dict_keys(ej_data, ej_flag_dict)\n ej_data[\"Pct_PopEJArea\"] = ej_data[\"Pop_EJArea\"] / sum(list(ej_data.values()))\n \n accdata_ej = acc.get_acc_data(fc_tripshedpoly, params.accdata_fc, projtyp, get_ej=True) # EJ accessibility data\n ej_data.update(accdata_ej)\n\n # for base dict, add items that only have a base year value (no future year values)\n for d in [accdata, ag_acres, job_du_dens, ej_data]:\n out_dict_base.update(d)\n\n outdf = pd.DataFrame.from_dict(out_dict_base, orient='index')\n \n return outdf\n\ndef get_multiyear_data(fc_tripshedpoly, projtyp, base_df, analysis_year):\n print(\"getting multi-year data for {}...\".format(analysis_year))\n ilut_val_fields = [params.col_pop_ilut, params.col_du, params.col_emptot, params.col_k12_enr, params.col_empind, params.col_persntrip_res] \\\n + params.ilut_ptrip_mode_fields \n\n fc_pcl_pt = params.parcel_pt_fc_yr(analysis_year)\n fc_pcl_poly = params.parcel_poly_fc_yr(analysis_year)\n\n year_dict = {}\n # get data on pop, job, k12 totals\n # point_sum(fc_pclpt, fc_tripshedpoly, projtyp, val_fields, buffdist, case_field=None, case_excs_list=[])\n ilut_buff_vals = lu_pt_buff.point_sum(fc_pcl_pt, fc_tripshedpoly, projtyp, ilut_val_fields,\n params.ilut_sum_buffdist, case_field=None, case_excs_list=[])\n\n ilut_indjob_share = {\"{}_jobshare\".format(params.col_empind): ilut_buff_vals[params.col_empind] / ilut_buff_vals[params.col_emptot]}\n ilut_buff_vals.update(ilut_indjob_share)\n\n ilut_mode_split = {\"{}_share\".format(modetrp): ilut_buff_vals[modetrp] / ilut_buff_vals[params.col_persntrip_res]\n for modetrp in params.ilut_ptrip_mode_fields}\n ilut_buff_vals.update(ilut_mode_split)\n\n # cleanup to remove non-percentage mode split values, if we want to keep output CSV from getting too long.\n # for trip_numcol in params.ilut_ptrip_mode_fields: del ilut_buff_vals[trip_numcol]\n\n # job + du total\n job_du_tot = {\"SUM_JOB_DU\": ilut_buff_vals[params.col_du] + ilut_buff_vals[params.col_emptot]}\n\n\n # land use diversity index\n mix_index_data = mixidx.get_mix_idx(fc_pcl_pt, fc_tripshedpoly, projtyp)\n\n # housing type mix\n housing_mix_data = lu_pt_buff.point_sum(fc_pcl_pt, fc_tripshedpoly, projtyp, [params.col_du], params.du_mix_buffdist,\n params.col_housing_type, case_excs_list=['Other'])\n\n # acres of \"natural resources\" (land use type = forest or agriculture)\n nat_resources_data = urbn.nat_resources(fc_tripshedpoly, projtyp, fc_pcl_poly, analysis_year)\n # combine into dict\n for d in [ilut_buff_vals, job_du_tot, mix_index_data, housing_mix_data, nat_resources_data]:\n year_dict.update(d)\n\n # make dict into dataframe\n df_year_out = pd.DataFrame.from_dict(year_dict, orient='index')\n \n return df_year_out\n\ndef get_tripshed_data(fc_tripshed, project_type, analysis_years, csv_aggvals, base_dict={}):\n\n # metrics that only have base year value\n outdf_base = get_singleyr_data(fc_tripshed, project_type, analysis_years[0], base_dict)\n \n # outputs that use both base year and future year values\n for year in analysis_years:\n df_year = get_multiyear_data(fc_tripshed, project_type, outdf_base, year)\n # if it's base year, then append values to bottom of outdf_base,\n # if it's future year, then left-join the values to the outdf.\n # table has metrics as rows; years as columns (and will also append \n if year == min(analysis_years):\n out_df = outdf_base.rename(columns={0: 'tripshed_{}'.format(year)})\n df_year = df_year.rename(columns={0: 'tripshed_{}'.format(year)})\n out_df = out_df.append(df_year)\n else:\n df_year = df_year.rename(columns={0: 'tripshed_{}'.format(year)})\n out_df = out_df.join(df_year)\n \n # get community type and regional level data\n df_aggvals = pd.read_csv(csv_aggvals, index_col='Unnamed: 0')\n col_aggvals_year = 'year'\n cols_ctype_reg = ['REGION']\n \n for year in analysis_years:\n df_agg_yr = df_aggvals[df_aggvals[col_aggvals_year] == year] # filter to specific year\n df_agg_yr = df_agg_yr[cols_ctype_reg] # only include community types for community types that project is in\n df_agg_yr = df_agg_yr.rename(columns={col:'{}_{}'.format(col, year) for col in list(df_agg_yr.columns)})\n \n out_df = out_df.join(df_agg_yr)\n \n return out_df\n \nif __name__ == '__main__':\n # =====================================USER/TOOLBOX INPUTS===============================================\n arcpy.env.workspace = r'I:\\Projects\\Darren\\PPA_V2_GIS\\PPA_V2.gdb'\n arcpy.OverwriteOutput = True\n\n # project data\n tripshed_fc = r'I:\\Projects\\Darren\\PPA_V2_GIS\\PPA_V2.gdb\\TripShed_test_project01032020_1109' # TripShed_test_project01032020_1109\n proj_name = os.path.basename(tripshed_fc) # os.path.basename(tripshed_fc)\n project_type = params.ptype_area_agg # params.ptype_fwy, params.ptype_arterial, or params.ptype_sgr\n adt = 17000\n \n # CSV of aggregate values by community type and for whole region\n xlsx_template = r\"Q:\\ProjectLevelPerformanceAssessment\\PPAv2\\PPA2_0_code\\PPA2\\Input_Template\\XLSX\\Replica_Summary_Template.xlsx\"\n \n\n # =======================BEGIN SCRIPT==============================================================\n analysis_years = [2016, 2040] # which years will be used.\n time_sufx = str(dt.datetime.now().strftime('%m%d%Y_%H%M'))\n output_csv = r'C:\\TEMP_OUTPUT\\ReplicaTripShed\\PPA_TripShed_{}_{}.csv'.format(\n os.path.basename(tripshed_fc), time_sufx)\n\n out_dict_base = {\"project_name\": proj_name, \"project_type\": project_type, 'project_aadt': adt}\n\n out_df = get_tripshed_data(tripshed_fc, project_type, analysis_years, params.aggvals_csv, base_dict={})\n\n out_df.to_csv(output_csv)\n print(\"success!\")\n\n\n","sub_path":"PPA2/archived scripts/backups08062020/bigdata_tripshed.py","file_name":"bigdata_tripshed.py","file_ext":"py","file_size_in_byte":7992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"225169263","text":"from flask import Flask,render_template\nimport requests\nfrom bs4 import BeautifulSoup\n\npage= requests.get(\"https://www.mygov.in/covid-19\")\napp = Flask(__name__)\nsoup=BeautifulSoup(page.content,\"html.parser\")\nli1=[]\nli2=[]\ndic={}\ninfo=soup.find_all(class_=\"iblock_text\")\nfor ele in info:\n li1.append(ele.find(class_=\"icount\").get_text())\n li2.append(ele.find(class_=\"info_label\").get_text())\n\ndate=soup.find(class_=\"info_title\")\ndata=date.span.get_text()\nfor i in range(len(li1)):\n dic[li2[i]]=li1[i]\nprint(dic)\n\n@app.route(\"/\")\ndef corona():\n return render_template(\"Corona.html\",data=data,dic=dic)\n\nif __name__==\"__main__\":\n\tapp.run(debug=True)","sub_path":"corona.py","file_name":"corona.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"59617867","text":"#!/usr/bin/env python3\n\n# Problem 1 - Multiples of 3 and 5\n# \n# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. \n# The sum of these multiples is 23.\n#\n# Find the sum of all the multiples of 3 or 5 below 1000.\n\ndef solve():\n sum = 0\n for x in list(range(1,1000)):\n if ((x % 3 == 0) or (x % 5 == 0) and (not (x is None))):\n sum += x\n return sum\n\nprint(solve())","sub_path":"python/problem-1.py","file_name":"problem-1.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"234260804","text":"\"\"\"\nAPI for retrieving and setting dates.\n\"\"\"\nfrom __future__ import absolute_import, unicode_literals\n\nimport logging\n\nimport six\nfrom django.core.exceptions import ValidationError\nfrom django.utils.dateparse import parse_datetime\nfrom edx_django_utils.cache.utils import DEFAULT_REQUEST_CACHE\nfrom opaque_keys import InvalidKeyError\nfrom opaque_keys.edx.keys import CourseKey, UsageKey\n\nfrom edx_when import models\n\nlog = logging.getLogger('edx-when')\n\nFIELDS_TO_EXTRACT = ('due', 'start', 'end')\n\n\ndef _ensure_key(key_class, key_obj):\n if not isinstance(key_obj, key_class):\n key_obj = key_class.from_string(key_obj)\n return key_obj\n\n\ndef is_enabled_for_course(course_key):\n \"\"\"\n Return whether edx-when is enabled for this course.\n \"\"\"\n return models.ContentDate.objects.filter(course_id=course_key, active=True).exists()\n\n\ndef override_enabled():\n \"\"\"\n Return decorator that enables edx-when.\n \"\"\"\n from waffle.testutils import override_flag\n return override_flag('edx-when-enabled', active=True)\n\n\ndef set_dates_for_course(course_key, items):\n \"\"\"\n Extract dates from blocks.\n\n items is an iterator of (location, field metadata dictionary)\n \"\"\"\n course_key = _ensure_key(CourseKey, course_key)\n models.ContentDate.objects.filter(course_id=course_key, active=True).update(active=False)\n for location, fields in items:\n for field in FIELDS_TO_EXTRACT:\n if field in fields:\n val = fields[field]\n if val:\n log.info('Setting date for %r, %s, %r', location, field, val)\n set_date_for_block(course_key, location, field, val)\n\n\ndef clear_dates_for_course(course_key):\n \"\"\"\n Set all dates to inactive.\n \"\"\"\n course_key = _ensure_key(CourseKey, course_key)\n models.ContentDate.objects.filter(course_id=course_key, active=True).update(active=False)\n\n\ndef get_dates_for_course(course_id, user=None, use_cached=True):\n \"\"\"\n Return dictionary of dates for the given course_id and optional user.\n\n key: block location, field name\n value: datetime object\n \"\"\"\n log.debug(\"Getting dates for %s as %s\", course_id, user)\n\n cache_key = 'course_dates.%s'\n if user:\n if isinstance(user, int):\n user_id = user\n else:\n user_id = user.id if not user.is_anonymous else ''\n cache_key += '.%s' % user_id\n else:\n user_id = None\n dates = DEFAULT_REQUEST_CACHE.data.get(cache_key, None)\n if use_cached and dates is not None:\n return dates\n course_id = _ensure_key(CourseKey, course_id)\n qset = models.ContentDate.objects.filter(course_id=course_id, active=True).select_related('policy')\n dates = {}\n policies = {}\n for cdate in qset:\n key = (cdate.location, cdate.field)\n dates[key] = cdate.policy.abs_date\n policies[cdate.id] = key\n if user_id:\n for userdate in models.UserDate.objects.filter(\n user_id=user_id,\n content_date__course_id=course_id,\n content_date__active=True).select_related(\n 'content_date', 'content_date__policy'\n ).order_by('modified'):\n dates[policies[userdate.content_date_id]] = userdate.actual_date\n DEFAULT_REQUEST_CACHE.data[cache_key] = dates\n return dates\n\n\ndef get_date_for_block(course_id, block_id, name='due', user=None):\n \"\"\"\n Return the date for block in the course for the (optional) user.\n \"\"\"\n try:\n return get_dates_for_course(course_id, user).get((_ensure_key(UsageKey, block_id), name), None)\n except InvalidKeyError:\n return None\n\n\ndef get_overrides_for_block(course_id, block_id):\n \"\"\"\n Return list of date overrides for a block.\n\n list of (username, full_name, date)\n \"\"\"\n course_id = _ensure_key(CourseKey, course_id)\n block_id = _ensure_key(UsageKey, block_id)\n\n query = models.UserDate.objects.filter(\n content_date__course_id=course_id,\n content_date__location=block_id,\n content_date__active=True).order_by('-modified')\n dates = []\n users = set()\n for udate in query:\n if udate.user_id in users:\n continue\n else:\n users.add(udate.user_id)\n username = udate.user.username\n try:\n full_name = udate.user.profile.name\n except AttributeError:\n full_name = 'unknown'\n override = udate.actual_date\n dates.append((username, full_name, override))\n return dates\n\n\ndef get_overrides_for_user(course_id, user):\n \"\"\"\n Return all user date overrides for a particular course.\n\n iterator of {'location': location, 'actual_date': date}\n \"\"\"\n course_id = _ensure_key(CourseKey, course_id)\n\n query = models.UserDate.objects.filter(\n content_date__course_id=course_id,\n user=user,\n content_date__active=True).order_by('-modified')\n blocks = set()\n for udate in query:\n if udate.content_date.location in blocks:\n continue\n else:\n blocks.add(udate.content_date.location)\n yield {'location': udate.content_date.location, 'actual_date': udate.actual_date}\n\n\ndef set_date_for_block(course_id, block_id, field, abs_date, rel_date=None, user=None, reason='', actor=None):\n \"\"\"\n Save the date for a particular field in a block.\n\n abs_date: datetime object\n rel_date: a relative date integer (in days?)\n user: user object to override date\n reason: explanation for override\n actor: user object of person making the override\n \"\"\"\n course_id = _ensure_key(CourseKey, course_id)\n block_id = _ensure_key(UsageKey, block_id)\n if abs_date and isinstance(abs_date, six.string_types):\n abs_date = parse_datetime(abs_date)\n try:\n existing_date = models.ContentDate.objects.get(course_id=course_id, location=block_id, field=field)\n existing_date.active = True\n except models.ContentDate.DoesNotExist:\n if user:\n raise MissingDateError(block_id)\n existing_date = models.ContentDate(course_id=course_id, location=block_id, field=field)\n existing_date.policy, __ = models.DatePolicy.objects.get_or_create(abs_date=abs_date)\n\n if user and not user.is_anonymous:\n userd = models.UserDate(user=user, abs_date=abs_date, rel_date=rel_date)\n userd.actor = actor\n userd.reason = reason or ''\n userd.content_date = existing_date\n try:\n userd.full_clean()\n except ValidationError:\n raise InvalidDateError(userd.actual_date)\n userd.save()\n log.info('Saved override for user=%d loc=%s date=%s', userd.user_id, userd.location, userd.actual_date)\n else:\n if existing_date.policy.abs_date != abs_date:\n log.info('updating policy %r %r -> %r', existing_date, existing_date.policy.abs_date, abs_date)\n existing_date.policy = models.DatePolicy.objects.get_or_create(abs_date=abs_date)[0]\n existing_date.save()\n\n\nclass BaseWhenException(Exception):\n pass\n\n\nclass MissingDateError(BaseWhenException):\n pass\n\n\nclass InvalidDateError(BaseWhenException):\n pass\n","sub_path":"lib/python2.7/site-packages/edx_when/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":7251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"204103021","text":"import asyncio\nimport websockets\nimport enum\n\n\ndef websocket_upgrade(http):\n request_headers = dict(http.headers)\n response_headers = []\n\n def get_header(key):\n key = key.lower().encode(\"utf-8\")\n return request_headers.get(key, b\"\").decode(\"utf-8\")\n\n def set_header(key, val):\n response_headers.append((key.encode(\"utf-8\"), val.encode(\"utf-8\")))\n\n try:\n key = websockets.handshake.check_request(get_header)\n websockets.handshake.build_response(set_header, key)\n except websockets.InvalidHandshake:\n rv = b\"HTTP/1.1 403 Forbidden\\r\\n\\r\\n\"\n http.transport.write(rv)\n http.transport.close()\n return\n\n # Retrieve any subprotocols to be negotiated with the consumer later\n subprotocols = request_headers.get(b\"sec-websocket-protocol\", None)\n if subprotocols:\n subprotocols = subprotocols.split(b\",\")\n http.scope.update({\"type\": \"websocket\", \"subprotocols\": subprotocols})\n asgi_instance = http.app(http.scope)\n request = WebSocketRequest(http, response_headers)\n http.loop.create_task(asgi_instance(request.receive, request.send))\n request.put_message({\"type\": \"websocket.connect\", \"order\": 0})\n\n\nasync def websocket_session(protocol):\n close_code = None\n order = 1\n request = protocol.active_request\n path = request.scope[\"path\"]\n\n while True:\n try:\n data = await protocol.recv()\n except websockets.exceptions.ConnectionClosed as exc:\n close_code = exc.code\n break\n\n message = {\n \"type\": \"websocket.receive\",\n \"path\": path,\n \"text\": None,\n \"bytes\": None,\n \"order\": order,\n }\n if isinstance(data, str):\n message[\"text\"] = data\n elif isinstance(data, bytes):\n message[\"bytes\"] = data\n request.put_message(message)\n order += 1\n\n message = {\n \"type\": \"websocket.disconnect\",\n \"code\": close_code,\n \"path\": path,\n \"order\": order,\n }\n request.put_message(message)\n protocol.active_request = None\n\n\nclass WebSocketRequestState(enum.Enum):\n CONNECTING = 0\n CONNECTED = 1\n CLOSED = 2\n\n\nclass WebSocketRequest:\n def __init__(self, http, response_headers):\n self.state = WebSocketRequestState.CONNECTING\n self.http = http\n self.scope = http.scope\n self.response_headers = response_headers\n self.loop = asyncio.get_event_loop()\n self.receive_queue = asyncio.Queue()\n self.protocol = None\n\n def put_message(self, message):\n self.receive_queue.put_nowait(message)\n\n async def receive(self):\n return await self.receive_queue.get()\n\n async def send(self, message):\n message_type = message[\"type\"]\n text_data = message.get(\"text\")\n bytes_data = message.get(\"bytes\")\n\n if self.state == WebSocketRequestState.CLOSED:\n raise Exception(\"Unexpected message, WebSocketRequest is CLOSED.\")\n\n if self.state == WebSocketRequestState.CONNECTING:\n # Complete the handshake after negotiating a subprotocol with the consumer\n subprotocol = message.get(\"subprotocol\", None)\n if subprotocol:\n self.response_headers.append(\n (b\"Sec-WebSocket-Protocol\", subprotocol.encode(\"utf-8\"))\n )\n protocol = WebSocketProtocol(self.http, self.response_headers)\n protocol.connection_made(self.http.transport, subprotocol)\n protocol.connection_open()\n self.http.transport.set_protocol(protocol)\n self.protocol = protocol\n self.protocol.active_request = self\n\n if not self.protocol.accepted:\n accept = message_type == \"websocket.accept\"\n close = message_type == \"websocket.close\"\n\n if accept or close:\n self.protocol.accept()\n self.state = WebSocketRequestState.CONNECTED\n if accept:\n self.protocol.listen()\n else:\n self.protocol.reject()\n self.state = WebSocketRequestState.CLOSED\n\n if self.state == WebSocketRequestState.CONNECTED:\n if text_data:\n await self.protocol.send(text_data)\n elif bytes_data:\n await self.protocol.send(bytes_data)\n\n if message_type == \"websocket.close\":\n code = message.get(\"code\", 1000)\n await self.protocol.close(code=code)\n self.state = WebSocketRequestState.CLOSED\n else:\n raise Exception(\"Unexpected message, WebSocketRequest is %s\" % self.state)\n\n\nclass WebSocketProtocol(websockets.WebSocketCommonProtocol):\n def __init__(self, http, handshake_headers):\n super().__init__(max_size=10000000, max_queue=10000000)\n self.handshake_headers = handshake_headers\n self.accepted = False\n self.loop = http.loop\n self.app = http.app\n self.active_request = None\n\n def connection_made(self, transport, subprotocol):\n super().connection_made(transport)\n self.subprotocol = subprotocol\n self.transport = transport\n\n def accept(self):\n self.accepted = True\n rv = b\"HTTP/1.1 101 Switching Protocols\\r\\n\"\n for k, v in self.handshake_headers:\n rv += k + b\": \" + v + b\"\\r\\n\"\n rv += b\"\\r\\n\"\n self.transport.write(rv)\n\n def listen(self):\n self.loop.create_task(websocket_session(self))\n\n def reject(self):\n rv = b\"HTTP/1.1 403 Forbidden\\r\\n\\r\\n\"\n self.active_request = None\n self.transport.write(rv)\n self.transport.close()\n","sub_path":"uvicorn/protocols/websockets/websockets.py","file_name":"websockets.py","file_ext":"py","file_size_in_byte":5776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"590532712","text":"\"\"\"\nGiven a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).\n\nFor example, this binary tree [1,2,2,3,4,4,3] is symmetric:\n\n 1\n / \\\n 2 2\n / \\ / \\\n3 4 4 3\nBut the following [1,2,2,null,3,null,3] is not:\n 1\n / \\\n 2 2\n \\ \\\n 3 3\n\"\"\"\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def isSymmetric(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: bool\n \"\"\"\n \n \"\"\"\n #recursive\n if root==None: return True\n return self.recursion(root.left, root.right)\n \"\"\"\n \n \"\"\"\n #iterative pre-order dfs\n return self.pre_dfs(root)\n \"\"\"\n \n #iterative bfs\n return self.bfs(root)\n \n def bfs(self, root):\n if root == None: return True\n \n q = []\n q.append( (root.left, root.right) )\n while q:\n (l, r) = q.pop(0)\n if l == None and r == None:\n continue\n elif l and r and (l.val == r.val):\n q.append( (l.left, r.right) )\n q.append( (l.right, r.left) )\n else:\n return False\n return True\n \n def pre_dfs(self, root):\n if root == None: return True\n \n stack = []\n stack.append( (root.left, root.right) )\n while stack:\n (l, r) = stack.pop()\n if l and r and (l.val ==r.val):\n stack.append( (l.right, r.left) )\n stack.append( (l.left, r.right) )\n elif l==None and r==None:\n continue\n else:\n return False\n return True\n \n def recursion(self, l, r):\n if l==None and r == None:\n return True\n elif l and r:\n return l.val == r.val and (self.recursion(l.left, r.right) ) and (self.recursion(l.right, r.left))\n \n return False\n","sub_path":"101_Symmetric Tree.py","file_name":"101_Symmetric Tree.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"395251378","text":"class arvore_preta_vermelha:\n def __init__(self):\n self.ext = no(-1,cor.preto)\n self.raiz = self.ext\n\n def inserir(self,val):\n temp = no()\n ptr = self.raiz\n par = self.ext\n\n while(ptr!=self.ext):\n par = ptr\n if ptr.info > val:\n ptr = ptr.lchild\n elif ptr.info < val:\n ptr = ptr.rchild\n else:\n print('Elemento Duplicado')\n return\n\n temp.info = val\n temp.lchild = self.ext\n temp.rchild = self.ext\n temp.cor = cor.vermelho\n temp.parent = par\n\n if par == self.ext:\n self.raiz = temp\n elif temp.info < par.info:\n par.lchild = temp\n else:\n par.rchild = temp\n self.balance_inserir(temp)\n\n def balance_inserir(self,ptr):\n while ptr.parent.cor == cor.vermelho:\n par = ptr.parent\n grandPar = par.parent\n if par == grandPar.lchild:\n uncle = grandPar.rchild\n if uncle.cor == cor.vermelho:\n par.cor = cor.preto\n uncle.cor = cor.preto\n grandPar.cor = cor.vermelho\n ptr = grandPar\n\n else:\n if ptr == par.rchild:\n self.rotate_left(par)\n ptr = par\n par = ptr.parent\n par.cor = cor.preto\n grandPar.cor = cor.vermelho\n self.rotate_right(grandPar)\n\n elif par == grandPar.rchild:\n uncle = grandPar.lchild\n if uncle.cor == cor.vermelho:\n par.cor = cor.preto\n uncle.cor = cor.preto\n grandPar.cor = cor.vermelho\n ptr = grandPar\n else:\n if ptr == par.lchild:\n self.rotate_right(par)\n ptr = par\n par = ptr.parent\n par.cor = cor.preto\n grandPar.cor = cor.vermelho\n self.rotate_left(grandPar)\n\n else:\n continue\n\n self.raiz.cor = cor.preto\n\n def procurar(self,key,return_loc=False):\n ptr = self.raiz\n while ptr!=self.ext:\n if ptr.info == key:\n return ptr if return_loc else 'Verdadeiro'\n elif ptr.info < key:\n ptr = ptr.rchild\n else:\n ptr = ptr.lchild\n return ptr if return_loc else 'Falso'\n\n def deletar(self,val):\n ptr = self.procurar(val,True)\n if ptr == self.ext:\n print('Elemento não existe')\n return\n if ptr.lchild != self.ext or ptr.rchild != self.ext:\n succ = self.inorder_succ(ptr)\n ptr.info = succ.info\n ptr = succ\n if ptr.lchild != self.ext:\n child = ptr.lchild\n else:\n child = ptr.rchild\n child.parent = ptr.parent\n if ptr == self.raiz:\n self.raiz = child\n elif ptr.parent.lchild == ptr:\n ptr.parent.lchild = child\n else:\n ptr.parent.rchild = child\n if child == self.raiz:\n child.cor = cor.preto\n elif ptr.cor == cor.preto:\n if child != self.ext:\n child.cor = cor.preto\n else:\n self.balance_deletar(child)\n else:\n pass\n\n def balance_deletar(self,ptr):\n while ptr != self.raiz:\n if ptr.parent.lchild == ptr:\n sib = ptr.parent.rchild\n\n if sib.cor == cor.vermelho:\n sib.cor = cor.preto\n ptr.parent.cor = cor.vermelho\n self.rotate_left(ptr.parent)\n sib = ptr.parent.rchild\n\n if sib.lchild.cor == cor.preto and sib.rchild.cor == cor.preto:\n sib.cor = cor.vermelho\n if ptr.parent.cor == cor.vermelho:\n ptr.parent.cor = cor.preto\n return\n ptr = ptr.parent\n\n\n else:\n\n if sib.rchild.cor == cor.preto:\n sib.lchild.cor = cor.preto\n sib.cor = cor.vermelho\n self.rotate_right(sib)\n sib = ptr.parent.rchild\n sib.cor = ptr.parent.cor\n ptr.parent.cor = cor.preto\n sib.rchild.cor = cor.preto\n self.rotate_left(ptr.parent)\n return\n\n else:\n sib = ptr.parent.lchild\n if sib.cor == cor.vermelho:\n sib.cor = cor.preto\n ptr.parent.cor = cor.vermelho\n self.rotate_right(ptr.parent)\n sib = ptr.parent.lchild\n if sib.lchild.cor == cor.preto and sib.rchild.cor == cor.preto:\n sib.cor = cor.vermelho\n if ptr.parent.cor == cor.vermelho:\n ptr.parent.cor = cor.preto\n return\n ptr = ptr.parent\n else:\n if sib.lchild.cor == cor.preto:\n sib.rchild.cor = cor.preto\n sib.cor = cor.vermelho\n self.rotate_left(sib)\n sib = ptr.parent.lchild\n sib.cor = ptr.parent.cor\n ptr.parent.cor = cor.preto\n sib.lchild.cor = cor.preto\n self.rotate_right(ptr.parent)\n return\n\n def inorder_succ(self,ptr):\n ptr = ptr.rchild\n while ptr.lchild != self.ext:\n ptr = ptr.lchild\n return ptr\n\n def rotate_left(self,ptr):\n rptr = ptr.rchild\n ptr.rchild = rptr.lchild\n if rptr.lchild!=self.ext:\n rptr.lchild.parent = ptr\n rptr.parent = ptr.parent\n if ptr.parent == self.ext:\n self.raiz = rptr\n elif ptr == ptr.parent.lchild:\n ptr.parent.lchild = rptr\n else:\n ptr.parent.rchild = rptr\n rptr.lchild = ptr\n ptr.parent = rptr\n\n def rotate_right(self,ptr):\n lptr = ptr.lchild\n ptr.lchild = lptr.rchild\n if lptr.rchild!=self.ext:\n lptr.rchild.parent = ptr\n lptr.parent = ptr.parent\n if ptr.parent == self.ext:\n self.raiz = lptr\n elif ptr == ptr.parent.rchild:\n ptr.parent.rchild = lptr\n else:\n ptr.parent.lchild = lptr\n lptr.rchild = ptr\n ptr.parent = lptr\n\n def inorder(self,ptr):\n if ptr!=self.ext:\n self.inorder(ptr.lchild)\n print(ptr.info,end=' ')\n self.inorder(ptr.rchild)\n\n def display(self,ptr):\n print(ptr.info,'cor = ',('vermelho' if ptr.cor==1 else 'preto'))\n if ptr.lchild != self.ext:\n print(ptr.info,'left -> ',end='')\n self.display(ptr.lchild)\n if ptr.rchild != self.ext:\n print(ptr.info,'right -> ',end='')\n self.display(ptr.rchild)\n\nclass cor:\n preto=0\n vermelho= 1\n\nclass no:\n def __init__(self,info=None,cor=None):\n self.info = info\n self.cor = cor\n self.lchild = None\n self.rchild = None\n self.parent = None\n","sub_path":"arvore_implementada.py","file_name":"arvore_implementada.py","file_ext":"py","file_size_in_byte":7515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"150332824","text":"# -*- coding: utf-8 -*-\nfrom zope.interface import implements\nfrom twisted.plugin import IPlugin\nfrom twisted.python import log\nfrom desertbot.moduleinterface import IModule, Module, ModuleType\nfrom desertbot.message import IRCMessage\nfrom desertbot.response import IRCResponse, ResponseType\n\n\nclass Next(Module):\n implements(IPlugin, IModule)\n\n name = u\"next\"\n triggers = [u\"next\", u\"nextfan\"]\n moduleType = ModuleType.COMMAND\n\n def getHelp(self, message):\n \"\"\"\n @type message: IRCMessage\n \"\"\"\n helpDict = {\n u\"next\": u\"next [timezone] - fetches the next event from the LRR streaming calendar\",\n u\"nextfan\": u\"nextfan [timezone] - fetches the next event from the \"\n u\"LRR Fan-streamers calendar\",\n }\n return helpDict[message.parameterList[0]]\n\n def onTrigger(self, message):\n \"\"\"\n @type message: IRCMessage\n \"\"\"\n cal = message.bot.moduleHandler.getModule(\"googlecalendar\")\n if not cal:\n log.err(\"The \\\"googlecalendar\\\" module is required for \\\"next\\\" to work.\")\n return\n\n calendar = None\n if message.command == u\"next\":\n calendar = \"loadingreadyrun.com_72jmf1fn564cbbr84l048pv1go@group.calendar.google.com\"\n elif message.command == u\"nextfan\":\n calendar = \"caffeinatedlemur@gmail.com\"\n\n if len(message.parameterList) > 0: # timezone specified?\n nextEvent = cal.getNextEvent(calendar, message.parameterList[0])\n else:\n nextEvent = cal.getNextEvent(calendar)\n\n if nextEvent is None:\n return IRCResponse(ResponseType.PRIVMSG,\n u\"There don't appear to be any upcoming streams scheduled.\",\n message.user,\n message.replyTo)\n\n shortDate = nextEvent[\"start\"].strftime(\"%a %I:%M %p %Z\")\n\n if nextEvent[\"timezoneParsed\"] is False:\n tzMessage = u\" (failed to parse '{}')\".format(message.parameterList[0])\n else:\n tzMessage = u\"\"\n\n return IRCResponse(ResponseType.PRIVMSG,\n u\"Next scheduled stream: {} at {}{} ({})\".format(nextEvent[\"summary\"],\n shortDate,\n tzMessage,\n nextEvent[\"till\"]),\n message.user,\n message.replyTo)\n\nnextModule = Next()","sub_path":"desertbot/modules/command/next.py","file_name":"next.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"382303233","text":"#!/usr/bin/env python3\n\nimport utils, open_color, arcade\n\nutils.check_version((3,7))\n\nSCREEN_WIDTH = 800 # we are initializing variables from lines 7 through 9\nSCREEN_HEIGHT = 600\nSCREEN_TITLE = \"Smiley Face Example\"\n\nclass Faces(arcade.Window): # making a class here\n \"\"\" Our custom Window Class\"\"\"\n\n def __init__(self): #defining a function here where self is a keyword which would bind the attributes with the given arguments \n \"\"\" Initializer \"\"\"\n # Call the parent class initializer\n super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)\n\n # Show the mouse cursor\n self.set_mouse_visible(True) #this means we are alllowing the mouse to be visible\n\n self.x = SCREEN_WIDTH / 2 # this would mean that the smiley would at the middle of the screen by default\n self.y = SCREEN_HEIGHT / 2\n\n arcade.set_background_color(open_color.white)\n\n def on_draw(self): # this is another function which actually draws the smiley\n \"\"\" Draw the face \"\"\"\n arcade.start_render()\n face_x,face_y = (self.x,self.y) # the use of self here indicates that the smiley would go wherever the mouse would go\n smile_x,smile_y = (face_x + 0,face_y - 10) # these are the coordinates of smiley and all its parts\n eye1_x,eye1_y = (face_x - 30,face_y + 20) \n eye2_x,eye2_y = (face_x + 30,face_y + 20)\n catch1_x,catch1_y = (face_x - 25,face_y + 25) \n catch2_x,catch2_y = (face_x + 35,face_y + 25) \n\n arcade.draw_circle_filled(face_x, face_y, 100, open_color.yellow_3) #lines 37-43 draws the smiiley also giving its parts specific colors to make it look like a smiley\n arcade.draw_circle_outline(face_x, face_y, 100, open_color.black,4)\n arcade.draw_ellipse_filled(eye1_x,eye1_y,15,25,open_color.black)\n arcade.draw_ellipse_filled(eye2_x,eye2_y,15,25,open_color.black)\n arcade.draw_circle_filled(catch1_x,catch1_y,3,open_color.gray_2)\n arcade.draw_circle_filled(catch2_x,catch2_y,3,open_color.gray_2)\n arcade.draw_arc_outline(smile_x,smile_y,60,50,open_color.black,190,350,4)\n\n\n def on_mouse_motion(self, x, y, dx, dy): # helps sets x and y ( of smiley's ) to the x and y value of the mouse so that the smiley goes whereever the mouse goes\n \"\"\" Handle Mouse Motion \"\"\"\n self.x = x\n self.y = y\n\n\n\nwindow = Faces()\narcade.run()","sub_path":"main5.py","file_name":"main5.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"205500760","text":"import sys\nsys.path.append('../doubly_linked_list')\nfrom doubly_linked_list import (DoublyLinkedList, ListNode)\n\nclass LRUCache:\n \"\"\"\n Our LRUCache class keeps track of the max number of nodes it\n can hold, the current number of nodes it is holding, a doubly-\n linked list that holds the key-value entries in the correct\n order, as well as a storage dict that provides fast access\n to every node stored in the cache.\n \"\"\"\n def __init__(self, limit=10):\n #limits how many node it can hold 10\n self.limit = limit\n #current number of nodes it's holding\n self.size = 0\n #dictionary for access (hash table) s well as a storage dict that provides fast access\n #to every node stored in the cache.\n self.storage = {}\n #variable used to set the value being set by Doublylinked list\n #a doubly-linked list that holds the key-value entries in the correct order\n self.order = DoublyLinkedList()\n \n\n \"\"\"\n Retrieves the value associated with the given key. Also\n needs to move the key-value pair to the end of the order\n such that the pair is considered most-recently used.\n Returns the value associated with the key or None if the\n key-value pair doesn't exist in the cache.\n \"\"\"\n def get(self, key):\n #if key is in storage\n if key in self.storage:\n #move to end\n node = self.storage[key]\n #update order\n self.order.move_to_end(node)\n #return value\n return node.value[1] #<-tuple\n #if not:\n else:\n #return None\n return None\n\n # #if there is not a key\n # if not self.hash_table.get(key):\n # return None\n # else:\n # #new node created with a key\n # node = self.hash_table.get(key)\n # #moves to front since it's most recently used\n # self.Linked_List.move_to_front(node)\n # #\n # return node.value\n\n \"\"\"\n Adds the given key-value pair to the cache. The newly-\n added pair should be considered the most-recently used\n entry in the cache. If the cache is already at max capacity\n before this entry is added, then the oldest entry in the\n cache needs to be removed to make room. Additionally, in the\n case that the key already exists in the cache, we simply\n want to overwrite the old value associated with the key with\n the newly-specified value.\n \"\"\"\n def set(self, key, value):\n #check to see if key is in the dict\n if key in self.storage:\n #if it is\n node = self.storage[key] #<-grab the full node in the dict\n #overwrite the value\n node.value = (key, value) #<- creates tuple\n #move to the end\n self.order.move_to_end(node)#<-adding something new\n #exit function nothing left to do\n return\n\n #check if cache is full\n if self.size == self.limit:\n #if cache is full:\n #remove oldest from cache from the dict \n del self.storage[self.order.head.value[0]]# <-check 55 minutes\n #remove oldest from cache from the DLL\n self.order.remove_from_head()\n #reduce the size\n self.size -=1\n\n #add to the linked list (KVP) tuple\n self.order.add_to_tail((key, value))\n #add key and value to dictionary\n self.storage[key] = self.order.tail\n #increment the size\n self.size += 1\n\n\n\n # #checks if node exists\n # node = self.hash_table.get(key)\n # #checks if node is none then moves to front as MRU\n # if node is not None:\n # node.value = value\n # self.Linked_List.move_to_front(node)\n # else: #if the node doesn't exist and at limit\n # if self.size == self.limit:\n # #remove from end\n # self.Linked_List.remove_from_tail()\n # #decreases the number of nodes\n # self.size -= 1\n \n # #adds to the hash table\n # new_node = ListNode(value)\n # self.hash_table[key] = new_node\n \n # #add to front\n # self.Linked_List.add_to_head(new_node)\n\n # #adds to number of nodes it's holding\n # self.size += 1\n\n \n","sub_path":"lru_cache/lru_cache.py","file_name":"lru_cache.py","file_ext":"py","file_size_in_byte":4397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"567849388","text":"import json\nimport traceback\n\nfrom django.conf import settings\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.urls import reverse\nfrom jinja2 import Environment, TemplateSyntaxError\nfrom rest_framework.utils.encoders import JSONEncoder\n\nfrom extras.enums import WEBHOOK_HTTP_CONTENT_TYPE_JSON, HttpMethod\nfrom extras.utils import FeatureQuery\nfrom peering_manager.jinja2 import (\n FILTER_DICT,\n IncludeTemplateExtension,\n PeeringManagerLoader,\n)\nfrom utils.models import ChangeLoggedMixin\n\n__all__ = (\"ExportTemplate\", \"Webhook\")\n\n\nclass ExportTemplate(ChangeLoggedMixin):\n content_type = models.ForeignKey(\n to=ContentType,\n on_delete=models.CASCADE,\n limit_choices_to=FeatureQuery(\"export-templates\"),\n )\n name = models.CharField(max_length=100)\n description = models.CharField(max_length=200, blank=True)\n template = models.TextField(\n help_text=\"Jinja2 template code. The list of objects being exported is passed as a context variable named dataset.\"\n )\n jinja2_trim = models.BooleanField(\n default=False, help_text=\"Removes new line after tag\"\n )\n jinja2_lstrip = models.BooleanField(\n default=False, help_text=\"Strips whitespaces before block\"\n )\n\n class Meta:\n ordering = [\"content_type\", \"name\"]\n constraints = [\n models.UniqueConstraint(\n fields=[\"content_type\", \"name\"], name=\"contenttype_per_name\"\n )\n ]\n\n @property\n def rendered(self):\n return self.render()\n\n def __str__(self):\n return self.name\n\n def get_absolute_url(self):\n return reverse(\"extras:exporttemplate_view\", args=[self.pk])\n\n def clean(self):\n super().clean()\n\n if self.name.lower() == \"table\":\n raise ValidationError(\n {\n \"name\": f'\"{self.name}\" is a reserved name. Please choose a different name.'\n }\n )\n\n def render(self):\n \"\"\"\n Renders the content of the export template.\n \"\"\"\n environment = Environment(\n loader=PeeringManagerLoader(),\n trim_blocks=self.jinja2_trim,\n lstrip_blocks=self.jinja2_lstrip,\n )\n environment.add_extension(IncludeTemplateExtension)\n for extension in settings.JINJA2_TEMPLATE_EXTENSIONS:\n environment.add_extension(extension)\n\n # Add custom filters to our environment\n environment.filters.update(FILTER_DICT)\n\n # Try rendering the template, return a message about syntax issues if there\n # are any\n try:\n jinja2_template = environment.from_string(self.template)\n return jinja2_template.render(\n dataset=self.content_type.model_class().objects.all()\n )\n except TemplateSyntaxError as e:\n return f\"Syntax error in template at line {e.lineno}: {e.message}\"\n except Exception:\n return traceback.format_exc()\n\n\nclass Webhook(models.Model):\n \"\"\"\n A Webhook defines a request that will be sent to a remote HTTP server when an\n object is created, updated, and/or delete. The request will contain a\n representation of the object.\n \"\"\"\n\n name = models.CharField(max_length=128, unique=True)\n type_create = models.BooleanField(\n default=False, help_text=\"Call this webhook when an object is created.\"\n )\n type_update = models.BooleanField(\n default=False, help_text=\"Call this webhook when an object is updated.\"\n )\n type_delete = models.BooleanField(\n default=False, help_text=\"Call this webhook when an object is deleted.\"\n )\n url = models.CharField(\n max_length=512,\n verbose_name=\"URL\",\n help_text=\"A POST will be sent to this URL when the webhook is called.\",\n )\n enabled = models.BooleanField(default=True)\n http_method = models.CharField(\n max_length=32,\n choices=HttpMethod,\n default=HttpMethod.POST,\n verbose_name=\"HTTP method\",\n )\n http_content_type = models.CharField(\n max_length=128,\n default=WEBHOOK_HTTP_CONTENT_TYPE_JSON,\n verbose_name=\"HTTP content type\",\n help_text='The complete list of official content types is available
here.',\n )\n secret = models.CharField(\n max_length=255,\n blank=True,\n help_text=\"When provided, the request will include a 'X-Hook-Signature' header containing a HMAC hex digest of the payload body using the secret as the key. The secret is not transmitted in the request.\",\n )\n ssl_verification = models.BooleanField(\n default=True,\n verbose_name=\"SSL verification\",\n help_text=\"Enable SSL certificate verification. Disable with caution!\",\n )\n ca_file_path = models.CharField(\n max_length=4096,\n null=True,\n blank=True,\n verbose_name=\"CA File Path\",\n help_text=\"CA certificate file to use for SSL verification. Leave blank to use the system defaults.\",\n )\n\n class Meta:\n ordering = [\"name\"]\n unique_together = [\"type_create\", \"type_update\", \"type_delete\", \"url\"]\n\n def __str__(self):\n return self.name\n\n def clean(self):\n super().clean()\n\n if not self.type_create and not self.type_delete and not self.type_update:\n raise ValidationError(\n \"You must select at least one type: create, update, and/or delete.\"\n )\n if not self.ssl_verification and self.ca_file_path:\n raise ValidationError(\n {\n \"ca_file_path\": \"Do not specify a CA certificate file if SSL verification is disabled.\"\n }\n )\n\n def render_body(self, data):\n \"\"\"\n Renders the data as a JSON object.\n \"\"\"\n return json.dumps(data, cls=JSONEncoder)\n","sub_path":"extras/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"327206063","text":"#!/usr/bin/env python\r\n# coding:utf-8\r\nfrom sys import path\r\npath.append(r'../')\r\n\r\nfrom utils import tool\r\n\r\n\r\nlan_types = {\r\n\t'u8': ('byte', 'number'),\r\n\t'i8': ('sbyte', 'number'),\r\n\t'u16': ('ushort', 'number'),\r\n\t'i16': ('short', 'number'),\r\n\t'u32': ('uint', 'number'),\r\n\t'i32': ('int', 'number'),\r\n\t'u64': ('ulong', 'number'),\r\n\t'i64': ('long', 'number'),\r\n\t'f32': ('float', 'number'),\r\n\t'f64': ('double', 'number'),\r\n\t'string': ('string', 'string'),\r\n}\r\n\r\n\r\n# 类型转换\r\ndef trans_mess_type(mess_body):\r\n\tfor idx in xrange(len(mess_body['mess_fields'])):\r\n\t\tmess_field = mess_body['mess_fields'][idx]\r\n\t\tif mess_field['field_op'] == 'required':\r\n\t\t\tif mess_field['field_type'] in lan_types:\r\n\t\t\t\tmess_field['field_type'] = lan_types[mess_field['field_type']]\r\n\t\tif mess_field['field_op'] == 'optional':\r\n\t\t\tif mess_field['field_type'] in lan_types:\r\n\t\t\t\tmess_field['field_type'] = lan_types[mess_field['field_type']]\r\n\t\tif mess_field['field_op'] == 'repeated':\r\n\t\t\tif mess_field['field_type'] in lan_types:\r\n\t\t\t\tmess_field['field_type'] = lan_types[mess_field['field_type']]\r\n\r\n\t\tmess_body['mess_fields'][idx] = mess_field\r\n\r\n\treturn mess_body\r\n\r\n\r\ndef protocol_const(code_path, mess_name_ids):\r\n\tfile_name = code_path + 'Msg.ts'\r\n\r\n\t_str_msg_head = 'namespace proto {\\n\\texport const enum Msg {\\n'\r\n\t_str_msg_end = '\\t}\\n}\\n'\r\n\t_str_msg = ''\r\n\tfor mess_name_id in mess_name_ids:\r\n\t\tmess_name = mess_name_id['mess_name']\r\n\t\tif mess_name.startswith('S'):\r\n\t\t\tmess_id = mess_name_id['mess_id']\r\n\t\t\tmess_note = mess_name_id['mess_note']\r\n\t\t\t_str_msg += '\\t\\t/**' + mess_note + '*/\\n\\t\\t' + (tool.javascript_proto_name_msg(mess_name)).ljust(30, chr(32)) + '= ' + str(mess_id) + ',\\n\\n'\r\n\r\n\t_str_msg = _str_msg_head + _str_msg[:-1] + _str_msg_end\r\n\twith open(file_name, 'w+') as fd:\r\n\t\tfd.write(_str_msg)\r\n\r\n\r\nclass ProtoTypeScript(object):\r\n\tdef __init__(self, code_path, proto):\r\n\t\tproto_tmp = trans_mess_type(proto)\r\n\r\n\t\tself._proto \t\t\t= proto_tmp\r\n\r\n\t\tself._code_path\t\t\t= code_path\r\n\t\tself._mess_name \t\t= self._proto['mess_name']\r\n\r\n\t\tself._set_class_name()\r\n\t\tself._set_packet_id()\r\n\t\tself._set_filename()\r\n\t\tself._set_head()\r\n\t\tself._set_end()\r\n\t\tself._set_priv_var()\r\n\t\tself._set_encode()\r\n\t\tself._set_decode()\r\n\t\tself._set_set_get()\r\n\t\tself._set_get_buffer()\r\n\r\n\tdef _set_class_name(self):\r\n\t\tself._str_msg_name \t= tool.python_proto_name_msg(self._mess_name)\r\n\t\tself._str_class_name= tool.python_class_name(self._mess_name)\r\n\r\n\tdef _set_packet_id(self):\r\n\t\tself._packet_id = self._proto['mess_id']\r\n\r\n\tdef _set_filename(self):\r\n\t\tself._filename = self._code_path + self._str_class_name + '.ts'\r\n\r\n\tdef _set_head(self):\r\n\t\tself._str_head = 'namespace proto {'\r\n\r\n\tdef _set_end(self):\r\n\t\tself._str_end = '\\n}\\n}\\n'\r\n\r\n\tdef _set_priv_var(self):\r\n\t\tself._str_priv_var = 'export class ' + self._str_class_name + '\\n{\\n'\r\n\t\tfor mess_field in self._proto['mess_fields']:\r\n\t\t\tfield_op \t\t= mess_field['field_op']\r\n\t\t\tfield_type \t\t= mess_field['field_type']\r\n\t\t\tif not isinstance(field_type, basestring):\r\n\t\t\t\tfield_type_fun = field_type[0].capitalize()\r\n\t\t\t\tfield_type = field_type[1]\r\n\t\t\tfield_type_big = field_type.capitalize()\r\n\t\t\tfield_name \t\t= mess_field['field_name']\r\n\t\t\tfield_name_flag = field_name + '_flag'\r\n\t\t\tfield_name_m\t= '_' + field_name\r\n\t\t\tif field_op == 'repeated':\r\n\t\t\t\tself._str_priv_var += '\\tprivate ' + field_name_m + ': ' + field_type + '[] = [];\\n'\r\n\t\t\telif field_op == 'optional':\r\n\t\t\t\tself._str_priv_var += '\\tprivate ' + field_name_flag + ': number = 0;\\n'\r\n\t\t\t\tself._str_priv_var += '\\tprivate ' + field_name_m + ': ' + field_type + ';\\n'\r\n\t\t\telse:\r\n\t\t\t\tself._str_priv_var += '\\tprivate ' + field_name_m + ': ' + field_type + ';\\n'\r\n\r\n\tdef _set_encode(self):\r\n\t\tself._str_encode = '\\tpublic Encode(): game.util.Packet {\\n\\t\\tlet packet: game.util.Packet = new game.util.Packet();\\n'\r\n\t\tfor mess_field in self._proto['mess_fields']:\r\n\t\t\tfield_op \t\t= mess_field['field_op']\r\n\t\t\tfield_type \t\t= mess_field['field_type']\r\n\t\t\tif not isinstance(field_type, basestring):\r\n\t\t\t\tfield_type_fun = field_type[0].capitalize()\r\n\t\t\t\tfield_type = field_type[1]\r\n\t\t\tfield_type_big = field_type.capitalize()\r\n\t\t\tfield_name \t\t= mess_field['field_name']\r\n\t\t\tfield_name_flag\t= field_name + '_flag'\r\n\t\t\tfield_name_m \t= 'this._' + field_name\r\n\t\t\tfield_name_count= field_name + '_count'\r\n\t\t\tif field_op == 'repeated':\r\n\t\t\t\tself._str_encode += '\\t\\tlet ' + field_name_count + ': number = ' + field_name_m + '.length;\\n'\r\n\t\t\t\tself._str_encode += '\\t\\tpacket.WriteUshort(' + field_name_count + ');\\n'\r\n\t\t\t\tself._str_encode += '\\t\\tfor (var i: number = 0; i < ' + field_name_count + '; i++)\\n\\t\\t{\\n'\r\n\t\t\t\tself._str_encode += '\\t\\t\\tlet xxx: ' + field_type + ' = ' + field_name_m + '[i];\\n'\r\n\t\t\t\tif field_type.startswith('Msg'):\r\n\t\t\t\t\tself._str_encode += '\\t\\t\\tpacket.WriteBuffer(xxx' + '.GetBuffer());\\n\\t\\t}\\n'\r\n\t\t\t\telse:\r\n\t\t\t\t\tself._str_encode += '\\t\\t\\tpacket.Write' + field_type_fun + '(xxx);\\n\\t\\t}\\n'\r\n\t\t\telif field_op == 'optional':\r\n\t\t\t\tself._str_encode += '\\t\\tpacket.WriteByte(this.' + field_name_flag + ');\\n'\r\n\t\t\t\tself._str_encode += '\\t\\tif (this.' + field_name_flag + ' == 1)\\n\\t\\t{\\n'\r\n\t\t\t\tif field_type.startswith('M'):\r\n\t\t\t\t\tself._str_encode += '\\t\\t\\tpacket.WriteBuffer(' + field_name_m + '.GetBuffer());\\n\\t\\t}\\n'\r\n\t\t\t\telse:\r\n\t\t\t\t\tself._str_encode += '\\t\\t\\tpacket.Write' + field_type_fun + '(' + field_name_m + ');\\n\\t\\t}\\n'\r\n\t\t\telse:\r\n\t\t\t\tif field_type.startswith('M'):\r\n\t\t\t\t\tself._str_encode += '\\t\\tpacket.WriteBuffer(' + field_name_m + '.GetBuffer());\\n'\r\n\t\t\t\telse:\r\n\t\t\t\t\tself._str_encode += '\\t\\tpacket.Write' + field_type_fun + '(' + field_name_m + ');\\n'\r\n\t\tif not self._str_class_name.startswith('Msg'):\r\n\t\t\tself._str_encode += '\\t\\tpacket.Encode(' + self._packet_id + ');\\n'\r\n\t\tself._str_encode += '\\t\\treturn packet;\\n\\t}\\n'\r\n\r\n\tdef _set_decode(self):\r\n\t\tself._str_decode = '\\tconstructor(packet?: game.util.Packet) {\\n'\r\n\t\tself._str_decode += '\\t\\tif (packet) {\\n'\r\n\t\tfor mess_field in self._proto['mess_fields']:\r\n\t\t\tfield_op \t\t= mess_field['field_op']\r\n\t\t\tfield_type \t\t= mess_field['field_type']\r\n\t\t\tif not isinstance(field_type, basestring):\r\n\t\t\t\tfield_type_fun = field_type[0].capitalize()\r\n\t\t\t\tfield_type = field_type[1]\r\n\t\t\tfield_type_big = field_type.capitalize()\r\n\t\t\tfield_name \t\t= mess_field['field_name']\r\n\t\t\tfield_name_m \t= 'this._' + field_name\r\n\t\t\tfield_name_flag = field_name + '_flag'\r\n\t\t\tfield_name_count= field_name + '_count'\r\n\t\t\tif field_op == 'repeated':\r\n\t\t\t\tself._str_decode += '\\t\\t\\t' + field_name_m + ' = [];\\n'\r\n\t\t\t\tself._str_decode += '\\t\\t\\tlet ' + field_name_count + ': number = packet.ReadUshort();\\n'\r\n\t\t\t\tself._str_decode += '\\t\\t\\tfor (var i: number = 0; i < ' + field_name_count + '; i++)\\n\\t\\t{\\n'\r\n\t\t\t\tif field_type.startswith('Msg'):\r\n\t\t\t\t\tself._str_decode += '\\t\\t\\t\\t' + field_name_m + '.push(new ' + field_type + '(packet));\\n\\t\\t}\\n'\r\n\t\t\t\telse:\r\n\t\t\t\t\tself._str_decode += '\\t\\t\\t\\t' + field_name_m + '.push(packet.Read' + field_type_fun + '());\\n\\t\\t}\\n'\r\n\t\t\telif field_op == 'optional':\r\n\t\t\t\tself._str_decode += '\\t\\t\\tthis. ' + field_name_flag + ' = packet.ReadByte();\\n'\r\n\t\t\t\tself._str_decode += '\\t\\t\\tif (this.' + field_name_flag + ' == 1)\\n'\r\n\t\t\t\tself._str_decode += '\\t\\t\\t{\\n'\r\n\t\t\t\tif field_type.startswith('M'):\r\n\t\t\t\t\tself._str_decode += '\\t\\t\\t\\t' + field_name_m + ' = new ' + field_type + '(packet);\\n'\r\n\t\t\t\telse:\r\n\t\t\t\t\tself._str_decode += '\\t\\t\\t\\t' + field_name_m + ' = ' + 'packet.Read' + field_type_fun + '();\\n'\r\n\t\t\t\tself._str_decode += '\\t\\t\\t}\\n'\r\n\t\t\telse:\r\n\t\t\t\tif field_type.startswith('M'):\r\n\t\t\t\t\tself._str_decode += '\\t\\t\\t' + field_name_m + ' = new ' + field_type + '(packet);\\n'\r\n\t\t\t\telse:\r\n\t\t\t\t\tself._str_decode += '\\t\\t\\t' + field_name_m + ' = packet.Read' + field_type_fun + '();\\n'\r\n\t\tself._str_decode += '\\t\\t}\\n'\r\n\t\tself._str_decode += '\\t}\\n'\r\n\r\n\tdef _set_set_get(self):\r\n\t\tself._str_set_get\t= ''\r\n\t\tfor mess_field in self._proto['mess_fields']:\r\n\t\t\tfield_op \t\t= mess_field['field_op']\r\n\t\t\tfield_type \t\t= mess_field['field_type']\r\n\t\t\tif not isinstance(field_type, basestring):\r\n\t\t\t\tfield_type_fun = field_type[0].capitalize()\r\n\t\t\t\tfield_type = field_type[1]\r\n\t\t\tfield_type_big = field_type.capitalize()\r\n\t\t\tfield_name \t\t= mess_field['field_name']\r\n\t\t\tfield_name_flag = field_name + '_flag'\r\n\t\t\tfield_name_m \t= 'this._' + field_name\r\n\t\t\tif field_op == 'repeated':\r\n\t\t\t\tself._str_set_get += '\\tpublic get ' + field_name + '(): ' + field_type + '[] {return ' + field_name_m + '; }\\n'\r\n\t\t\t\tself._str_set_get += '\\tpublic set ' + field_name + '(value: ' + field_type + '[])' + ' { ' + field_name_m + ' = value; }\\n'\r\n\t\t\telif field_op == 'optional':\r\n\t\t\t\tself._str_set_get += '\\tpublic get ' + field_name + '(): ' + field_type + ' { return ' + field_name_m + '; }\\n'\r\n\t\t\t\tself._str_set_get += '\\tpublic set ' + field_name + '(value: ' + field_type + ')' + ' { this.' + field_name_flag + ' = 1; ' + field_name_m + ' = value; }\\n'\r\n\t\t\telse:\r\n\t\t\t\tself._str_set_get += '\\tpublic get ' + field_name + '(): ' + field_type + ' { return ' + field_name_m + '; }\\n'\r\n\t\t\t\tself._str_set_get += '\\tpublic set ' + field_name + '(value: ' + field_type + ')' + ' { ' + field_name_m + ' = value; }\\n'\r\n\r\n\tdef _set_get_buffer(self):\r\n\t\tself._str_get_buffer = '\\tpublic GetBuffer(): ByteBuffer\\n\\t{\\n\\t\\treturn this.Encode().GetBuffer();\\n\\t}\\n'\r\n\r\n\tdef _do_msg(self):\r\n\t\t_tmp_conn = ''\r\n\t\tcontent = self._str_head + '\\n' + self._str_priv_var + '\\n\\n' + self._str_encode + '\\n' + _tmp_conn + '\\n' + self._str_decode + '\\n' + self._str_get_buffer + '\\n\\n' + self._str_set_get[:-1] + self._str_end\r\n\r\n\t\twith open(self._filename, 'w+') as fd:\r\n\t\t\tfd.write(content)\r\n\r\n\tdef do_client(self):\r\n\t\tif self._mess_name.startswith('C'):\r\n\t\t\tcontent = self._str_head + '\\n' + self._str_priv_var + '\\n\\n' + self._str_encode + '\\n\\n' + self._str_set_get[:-1] + self._str_end\r\n\r\n\t\t\twith open(self._filename, 'w+') as fd:\r\n\t\t\t\tfd.write(content)\r\n\t\telif self._mess_name.startswith('S'):\r\n\t\t\tcontent = self._str_head + '\\n' + self._str_priv_var + '\\n\\n' + self._str_decode + '\\n\\n' + self._str_set_get[:-1] + self._str_end\r\n\r\n\t\t\twith open(self._filename, 'w+') as fd:\r\n\t\t\t\tfd.write(content)\r\n\t\telse:\r\n\t\t\tself._do_msg()\r\n\r\n\tdef do_server(self):\r\n\t\tif self._mess_name.startswith('C'):\r\n\t\t\tcontent = self._str_head + '\\n\\n' + self._str_priv_var + '\\n\\n' + self._str_decode + '\\n\\n' + self._str_set_get[:-1] + self._str_end\r\n\r\n\t\t\twith open(self._filename, 'w+') as fd:\r\n\t\t\t\tfd.write(content)\r\n\t\telif self._mess_name.startswith('S'):\r\n\t\t\tcontent = self._str_head + '\\n\\n' + self._str_priv_var + '\\n\\n' + self._str_encode + '\\n\\n' + self._str_set_get[:-1] + self._str_end\r\n\r\n\t\t\twith open(self._filename, 'w+') as fd:\r\n\t\t\t\tfd.write(content)\r\n\t\telse:\r\n\t\t\tself._do_msg()\r\n","sub_path":"proto/proto_typescript.py","file_name":"proto_typescript.py","file_ext":"py","file_size_in_byte":10679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"372620950","text":"import json, os\nfrom mymodule import stats_word\n#path = r'D:\\Github文件\\selfteaching-python-camp\\exercises\\1901100206\\d09\\tang300.json' #读取本地路径\n#path = os.path.abspath(__file__) 显示当前文件,即main.py的绝对路径\n#path = os.path.dirname(os.path.abspath(__file__)) 显示main.py所在文件夹的目录\npath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tang300.json') #实现效果与第一个path相同\ntry:\n #先转换成unicode,否则'gbk' codec can't decode byte 0x80 in position 70: illegal multibyte sequence\n with open(path, \"r\", encoding='UTF-8') as f: #\"r\"可不加\n read_one = f.read() #read()将文件内容读取,并存在read_one\n print(stats_word.stats_text_cn(read_one, 100)) \nexcept TypeError as err:\n print('TypeError:' + str(err))\n\n\n","sub_path":"exercises/1901100206/d09/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"595267119","text":"\"\"\"\nCommon and utility functions/classes for vulnerability-manager\n\"\"\"\nimport base64\nimport csv\nfrom io import StringIO\nimport json\nfrom math import floor\nfrom os import environ\nfrom distutils.util import strtobool # pylint: disable=import-error, no-name-in-module\n\nimport requests\n\nimport connexion\nfrom flask import Response\nfrom prometheus_client import Counter\n\nfrom common.logging import get_logger\n\nLOGGER = get_logger(__name__)\n\nVMAAS_HOST = environ.get('VMAAS_HOST', 'http://vmaas-webapp-1.vmaas-ci.svc:8080') # pylint: disable=invalid-name\nDEFAULT_ROUTE = \"%s/%s\" % (environ.get('PATH_PREFIX', \"/api\"),\n environ.get('APP_NAME', \"vulnerability\"))\nIDENTITY_HEADER = \"x-rh-identity\"\nDEFAULT_PAGE_SIZE = 25\nSKIP_ENTITLEMENT_CHECK = strtobool(environ.get('SKIP_ENTITLEMENT_CHECK', 'FALSE'))\nREAD_ONLY_MODE = strtobool(environ.get('READ_ONLY_MODE', 'FALSE'))\n\nLOGGER.info(\"Access URL: %s\", DEFAULT_ROUTE)\n\n# Prometheus support\n# Counter for all-the-get-calls, dealt with in BaseHandler\nREQUEST_COUNTS = Counter('ve_manager_invocations', 'Number of calls per handler', ['method', 'endpoint'])\n\n\nclass InvalidArgumentException(Exception):\n \"\"\"Illegal arguments for pagination/filtering/sorting\"\"\"\n\n\nclass ApplicationException(Exception):\n \"\"\"General exception in the application\"\"\"\n\n def __init__(self, message, status_code):\n self.message = message\n self.status_code = status_code\n super().__init__()\n\n def format_exception(self):\n \"\"\"Formats error message to desired format\"\"\"\n if isinstance(self.message, dict):\n return self.message, self.status_code\n return Request.format_exception(self.message, self.status_code)\n\n\nclass MissingEntitlementException(Exception):\n \"\"\"smart management entitlement is missing\"\"\"\n\n\nclass ReadOnlyModeException(Exception):\n \"\"\"manager is running in read-only mode\"\"\"\n\n\ndef basic_auth(username, password, required_scopes=None): # pylint: disable=unused-argument\n \"\"\"\n Basic auth is done on 3scale level.\n \"\"\"\n raise MissingEntitlementException\n\n\ndef auth(x_rh_identity, required_scopes=None): # pylint: disable=unused-argument\n \"\"\"\n Parses account number from the x-rh-identity header\n \"\"\"\n decoded_value = base64.b64decode(x_rh_identity).decode(\"utf-8\")\n LOGGER.debug('identity decoded: %s', decoded_value)\n identity = json.loads(decoded_value)\n if 'identity' not in identity:\n return None\n id_details = identity['identity']\n\n if 'account_number' not in id_details:\n return None\n rh_account_number = id_details['account_number']\n\n if SKIP_ENTITLEMENT_CHECK:\n return {'uid': rh_account_number}\n\n if 'entitlements' not in identity or 'smart_management' not in identity['entitlements']:\n raise MissingEntitlementException\n if identity['entitlements']['smart_management'].get('is_entitled', False):\n return {'uid': rh_account_number}\n raise MissingEntitlementException\n\n\ndef forbidden(exception): # pylint: disable=unused-argument\n \"\"\"Override default connexion 401 coming from auth() with 403\"\"\"\n return Response(response=json.dumps({'errors': [{'detail': 'smart_management entitlement is missing',\n 'status': '403'}]}),\n status=403, mimetype='application/vnd.api+json')\n\n\nclass Request:\n \"\"\"general class for processing requests\"\"\"\n\n _endpoint_name = None\n\n @staticmethod\n def _check_int_arg(kwargs, key, dflt, zero_allowed=False):\n val = kwargs.get(key, dflt)\n if val < 0 or (val == 0 and not zero_allowed):\n raise ApplicationException(\"Requested %s out of range: %s\" % (key, val), 400)\n return val\n\n @staticmethod\n def _check_read_only_mode():\n if READ_ONLY_MODE:\n raise ReadOnlyModeException(\"Service is running in read-only mode. Please try again later.\")\n\n @staticmethod\n def _format_data(output_data_format, data_list):\n if output_data_format == \"csv\":\n output = StringIO()\n if data_list:\n # create list of columns - type, id and all keys from attributes\n fields = [\"type\", \"id\"]\n fields.extend(data_list[0][\"attributes\"].keys())\n writer = csv.DictWriter(output, fields)\n writer.writeheader()\n for item in data_list:\n # create flat dictionary (type, id + values from attributes) and write it\n writer.writerow({field: item.get(field) or item[\"attributes\"].get(field) for field in fields})\n return output.getvalue()\n return data_list\n\n @classmethod\n def _parse_list_arguments(cls, kwargs):\n # We may get limit/offset, or page/page_size, or both\n # limit/offset 'wins', if it's set\n # page/page_size defaults to 0/DEFAULT_PAGE_SIZE and limit/offset to DEFAULT_PAGE_SIZE if *neither* are set\n # regardless, make sure limit/offset and page/page_size a) both exist, and b) are consistent, before we leave\n offset_set = kwargs.get('offset', '') or kwargs.get('limit', '')\n page_set = kwargs.get('page', '') or kwargs.get('page_size', '')\n\n if offset_set:\n limit = cls._check_int_arg(kwargs, \"limit\", DEFAULT_PAGE_SIZE)\n offset = cls._check_int_arg(kwargs, \"offset\", 0, True)\n page = floor(offset / limit) + 1\n page_size = limit\n elif page_set:\n page = cls._check_int_arg(kwargs, \"page\", 1)\n page_size = cls._check_int_arg(kwargs, \"page_size\", DEFAULT_PAGE_SIZE)\n limit = page_size\n offset = (page - 1) * page_size\n else:\n page = 1\n offset = 0\n page_size = DEFAULT_PAGE_SIZE\n limit = DEFAULT_PAGE_SIZE\n\n data_format = kwargs.get(\"data_format\", \"json\")\n if data_format not in [\"json\", \"csv\"]:\n raise InvalidArgumentException(\"Invalid data format: %s\" % kwargs.get(\"data_format\", None))\n\n return {\n \"filter\": kwargs.get(\"filter\", None),\n \"sort\": kwargs.get(\"sort\", None),\n \"page\": page,\n \"page_size\": page_size,\n \"limit\": limit,\n \"offset\": offset,\n \"data_format\": data_format\n }\n\n @staticmethod\n def format_exception(text, status_code):\n \"\"\"Formats error message to desired format\"\"\"\n return {\"errors\": [{\"status\": str(status_code), \"detail\": text}]}, status_code\n\n @staticmethod\n def hide_satellite_managed():\n \"\"\"Parses hide-satellite-managed from headers\"\"\"\n try:\n return strtobool(connexion.request.headers.get('Hide-Satellite-Managed', 'false'))\n except ValueError:\n return False\n\n @staticmethod\n def _parse_arguments(kwargs, argv):\n \"\"\"\n Utility method for getting parameters from request which come as string\n and their conversion to a object we'd like to have.\n Expects array of {'arg_name' : some_str, 'convert_func' : e.g. float, int}\n Returns dict of values if succeeds, throws exception in case of fail\n \"\"\"\n retval = {}\n errors = []\n for arg in argv:\n retval[arg['arg_name']] = kwargs.get(arg['arg_name'], None)\n if retval[arg['arg_name']]:\n try:\n if arg['convert_func'] is not None:\n retval[arg['arg_name']] = arg['convert_func'](retval[arg['arg_name']])\n except ValueError:\n errors.append({'status': '400',\n 'detail': 'Error in argument %s: %s' % (arg['arg_name'], retval[arg['arg_name']])})\n if errors:\n raise ApplicationException({'errors': errors}, 400)\n return retval\n\n @classmethod\n def vmaas_call(cls, endpoint, data):\n \"\"\"Calls vmaas and retrieves data from it\"\"\"\n headers = {'Content-type': 'application/json',\n 'Accept': 'application/json'}\n try:\n response = requests.post(VMAAS_HOST + endpoint,\n data=json.dumps(data), headers=headers)\n except requests.exceptions.ConnectionError:\n LOGGER.error('Could not connect to %s', (VMAAS_HOST,))\n raise ApplicationException('Could not connect to %s' % (VMAAS_HOST,), 500)\n if response.status_code == 200:\n return response.json()\n LOGGER.error('Received %s from vmaas on %s endpoint', response.status_code, endpoint)\n raise ApplicationException('Received %s from vmaas on %s endpoint' %\n (response.status_code, VMAAS_HOST + endpoint), response.status_code)\n\n\nclass GetRequest(Request):\n \"\"\"general class for processing GET requests\"\"\"\n\n @classmethod\n def get(cls, **kwargs):\n \"\"\"Answer GET request\"\"\"\n REQUEST_COUNTS.labels('get', cls._endpoint_name).inc()\n try:\n return cls.handle_get(**kwargs)\n except ApplicationException as exc:\n return exc.format_exception()\n except InvalidArgumentException as exc:\n return cls.format_exception(str(exc), 400)\n except Exception: # pylint: disable=broad-except\n LOGGER.exception('Unhandled exception: ')\n return cls.format_exception('Internal server error', 500)\n\n @classmethod\n def handle_get(cls, **kwargs):\n \"\"\"To be implemented in child classes\"\"\"\n raise NotImplementedError\n\n\nclass PatchRequest(Request):\n \"\"\"general class for processing PATCH requests\"\"\"\n\n @classmethod\n def patch(cls, **kwargs):\n \"\"\"Answer PATCH request\"\"\"\n REQUEST_COUNTS.labels('patch', cls._endpoint_name).inc()\n try:\n cls._check_read_only_mode()\n return cls.handle_patch(**kwargs)\n except ApplicationException as exc:\n return exc.format_exception()\n except InvalidArgumentException as exc:\n return cls.format_exception(str(exc), 400)\n except ReadOnlyModeException as exc:\n return cls.format_exception(str(exc), 503)\n except Exception: # pylint: disable=broad-except\n LOGGER.exception('Unhandled exception: ')\n return cls.format_exception('Internal server error', 500)\n\n @classmethod\n def handle_patch(cls, **kwargs):\n \"\"\"To be implemented in child classes\"\"\"\n raise NotImplementedError\n\n\nclass PostRequest(Request):\n \"\"\"general class for processing POST requests\"\"\"\n\n @classmethod\n def post(cls, **kwargs):\n \"\"\"Answer POST request\"\"\"\n REQUEST_COUNTS.labels('post', cls._endpoint_name).inc()\n try:\n cls._check_read_only_mode()\n return cls.handle_post(**kwargs)\n except ApplicationException as exc:\n return exc.format_exception()\n except InvalidArgumentException as exc:\n return cls.format_exception(str(exc), 400)\n except ReadOnlyModeException as exc:\n return cls.format_exception(str(exc), 503)\n except Exception: # pylint: disable=broad-except\n LOGGER.exception('Unhandled exception: ')\n return cls.format_exception('Internal server error', 500), 500\n\n @classmethod\n def handle_post(cls, **kwargs):\n \"\"\"To be implemented in child classes\"\"\"\n raise NotImplementedError\n\n\ndef parse_int_list(input_str):\n \"\"\"Function to parse string with ints to list, e.g. '1,2,3' -> [1,2,3]\"\"\"\n return [int(part) for part in input_str.split(\",\")]\n","sub_path":"manager/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":11615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"652623252","text":"import pandas as pd\nimport utils\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn import metrics\n\nimport pickle\n\nprint('### Reading data')\ndf = pd.read_csv(\n f'{utils.get_project_root()}/data/processed/list-of-lyrics.txt',\n delimiter='|',\n names=[\n 'artist',\n 'song_name',\n 'lyrics'])\n\ndf.drop_duplicates(subset=['artist', 'song_name'], inplace=True, keep='first')\ndf.drop_duplicates(subset='lyrics', keep='first', inplace=True)\n\n\nX = df['lyrics']\ny = df['artist']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y)\n\n# Prepocessing starts here\nmodel_pipeline = make_pipeline(\n CountVectorizer(\n lowercase=True,\n stop_words='english',\n ngram_range=(1, 2)\n ),\n LogisticRegression(\n # class_weight='balanced',\n max_iter=10000\n )\n)\n\ngrid = {\n 'logisticregression__C': [0.01, 0.1, 1, 10]\n}\n\nprint('### Training the model')\ngrid_search = GridSearchCV(\n estimator=model_pipeline,\n param_grid=grid,\n # scoring='balanced_accuracy',\n scoring='accuracy',\n return_train_score=True,\n n_jobs=-1\n)\n\n# finding the best parameter for logistig regression and training the\n# final model\ngrid_search.fit(X_train, y_train)\nfinal_model = grid_search.best_estimator_\n\nprint(\n 'Balanced accuracy score of final model: ',\n metrics.balanced_accuracy_score(\n y_test,\n final_model.predict(X_test)))\nprint(\n 'Accuracy score of final model: ',\n metrics.accuracy_score(\n y_test,\n final_model.predict(X_test)))\n\nprint('### Saving model')\nwith open(f'{utils.get_project_root()}/src/lyrics_model.pickle', 'wb') as file:\n pickle.dump(final_model, file)\n","sub_path":"src/create_model.py","file_name":"create_model.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"182907278","text":"import csv\nimport sys\nimport datetime\nfrom dateutil import parser\n\n\ndef cleanData(inFile, outFile):\n count = 1\n stats = {}\n with open(inFile, 'r') as csvfile:\n data = csvfile.readlines()\n totalRows = len(data)\n print('total rows read = {}'.format(totalRows))\n header = data[0]\n for line in data[1:]:\n line = line.strip()\n if line.startswith('D') or line.find('Infinity') >= 0 or line.find('infinity') >= 0:\n continue\n cols = line.split(',')\n\n dt = parser.parse(cols[2]) # '1/3/18 8:17'\n epochs = (dt - datetime.datetime(1970, 1, 1)).total_seconds()\n cols[2] = str(epochs)\n line = ','.join(cols)\n # clean_data.append(line)\n count += 1\n key = cols[-1]\n if key in stats:\n stats[key].append(line)\n else:\n stats[key] = [line]\n\n \"\"\"\n if count >= 1000:\n break\n \"\"\"\n\n with open(outFile+\".csv\", 'w') as csvoutfile:\n csvoutfile.write(header)\n with open(outFile + \".stats\", 'w') as fout:\n fout.write('Total Clean Rows = {}; Dropped Rows = {}\\n'.format(\n count, totalRows - count))\n for key in stats:\n fout.write('{} = {}\\n'.format(key, len(stats[key])))\n line = '\\n'.join(stats[key])\n csvoutfile.write('{}\\n'.format(line))\n with open('{}-{}.csv'.format(outFile, key), 'w') as labelOut:\n labelOut.write(header)\n labelOut.write(line)\n\n print('all done writing {} rows; dropped {} rows'.format(\n count, totalRows - count))\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 3:\n print('Usage: python data_cleanup.py inputFile.csv outputFile')\n else:\n cleanData(sys.argv[1], sys.argv[2])\n","sub_path":"data_cleanup.py","file_name":"data_cleanup.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"515157900","text":"import sys\n\n\ncache = {}\n\ndef solve(ownmote, motes):\n\tmotes.sort()\n\t# print(motes)\n\tchanges = 0\n\twhile len(motes) > 0:\n\t\tif motes[0] < ownmote:\n\t\t\townmote += motes[0]\n\t\t\tmotes = motes[1:]\n\t\telse:\n\t\t\tif ownmote > 1:\n\t\t\t\tmoteadd = [ownmote-1] + motes\n\t\t\t\tkadd = ','.join(str(x) for x in moteadd)\n\t\t\t\tif kadd in cache:\n\t\t\t\t\tchangesadd = cache[kadd]\n\t\t\t\telse:\n\t\t\t\t\tchangesadd = solve(ownmote, moteadd)\n\t\t\telse:\n\t\t\t\tchangesadd = 1000000000000\n\t\t\tmotedel = motes[1:]\n\t\t\tkdel = ','.join(str(x) for x in motedel)\n\t\t\tif kdel in cache:\n\t\t\t\tchangesdel = cache[kdel]\n\t\t\telse:\n\t\t\t\tchangesdel = solve(ownmote, motedel)\n\t\t\tif changesdel < changesadd:\n\t\t\t\t#cache[kdel] = changesdel\n\t\t\t\treturn 1 + changesdel\n\t\t\telse:\n\t\t\t\t#cache[kadd] = changesadd\n\t\t\t\treturn 1 + changesadd\n\n\treturn changes\n\nn = int(sys.stdin.readline())\nfor c in range(n):\n\t[ownmote, nummotes] = [int(x) for x in sys.stdin.readline().split()]\n\tmotes = [int(x) for x in sys.stdin.readline().split()]\n\tassert(nummotes == len(motes))\n\tmotes.sort()\n\tprint(\"Case #%d: %d\" % (c+1, solve(ownmote, motes)))\n","sub_path":"solutions_2692487_0/Python/axr123/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"245006630","text":"import pandas as pd\r\nimport plotly.express as px \r\nimport numpy \r\nfrom finalapp import*\r\n\r\n\r\n\r\n#fw=pd.read_excel('FW.xlsx')\r\n\r\n\r\nFW['value'] = FW['total_points'] / FW['now_cost']\r\n\r\nFW.sort_values(by='value',ascending=False,inplace=True)\r\nbest_fw=FW.head(20)\r\n\r\n\r\npara_fw = ['goals_scored','assists','games_starts']\r\nval_fw = [best_fw['goals_scored'].mean()*4,best_fw['assists'].mean()*3\r\n ,best_fw['games_starts'].mean()*2]\r\n\r\n\r\nfig_fw = px.pie(values=val_fw,names=para_fw,title='Forwards parameters',labels=para_fw\r\n ,color=para_fw\r\n ,color_discrete_map={'goals_scored':'85660d',\r\n 'assists':'862a16','games_starts':'620042'})\r\nfig_fw.update_traces(textposition='inside', textinfo='percent+label')\r\n\r\n\r\ndef app():\r\n st.title('Forwards')\r\n st.plotly_chart(fig_fw)","sub_path":"w9/fw.py","file_name":"fw.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"279613453","text":"#!/usr/bin/python3.6\n\nfrom flask import Flask, request, redirect, render_template, flash, url_for\nfrom flask_mysqldb import MySQL\nfrom yaml import load, FullLoader\nfrom datetime import datetime \n\napp = Flask(__name__)\nmysql = MySQL(app)\n\n# MySQL Configuration\ndb_keeps = load(open('db.yaml'), Loader=FullLoader)\napp.config['MYSQL_HOST'] = db_keeps['mysql_host']\napp.config['MYSQL_USER'] = db_keeps['mysql_user']\napp.config['MYSQL_PASSWORD'] = db_keeps['mysql_password']\napp.config['MYSQL_DB'] = db_keeps['mysql_db']\n\n@app.route('/')\ndef index():\n cur = mysql.connection.cursor()\n q = cur.execute(\"SELECT * FROM resources ORDER BY res_id DESC;\")\n if q > 0:\n resources = cur.fetchall()\n return render_template('index.html', resources=resources)\n else:\n return render_template('index.html', resources=None)\n\n@app.route('/new/')\ndef post():\n if request.method == 'POST':\n result = request.form\n description = str(result['description'])\n datetime = str(datetime.today().strftime(\"%Y-%m-%d %H:%M:%S\"))\n if result['user']: \n user = result['user']\n else:\n user = None\n tags = str(request.form.getlist('tags'))[1:-1]\n location = str(result['location']).lower()\n cur = mysql.connection.cursor()\n cur.execute(\"INSERT INTO resources(description, datetime, user, tags, location) VALUES(%s, %s, %s, %s, %s);\", (description, datetime, user, tags, location))\n mysql.connection.commit()\n cur.close()\n flash(\"Thank You for your contribution.\", \"success\")\n return redirect('/')\n return render_template('new.html')\n\n@app.route('/search/locations')\ndef search_location():\n location = str(request.args.get('q')).lower()\n cur = mysql.connection.cursor()\n q = cur.execute(\"SELECT * FROM resources WHERE location='{}';\".format(location))\n if q > 0:\n resources = cur.fetchall()\n return render_template('index.html', resources=resources)\n else:\n return render_template('index.html', resources=None)\n\n@app.route('/search/tags')\ndef search_tag():\n tag = str(request.args.get('q')).upper()\n cur = mysql.connection.cursor()\n q = cur.execute(\"SELECT * FROM resources WHERE tags LIKE '%{}%';\".format(tag))\n if q > 0:\n resources = cur.fetchall()\n return render_template('index.html', resources=resources)\n else:\n return render_template('index.html', resources=None)\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"11909036","text":"#! usr/bin/env python3\n\nimport os\n\ntextfiles = []\nfiles = os.listdir(\"/home/farii/Desktop\")\nfor i in files:\n if \".txt\" in i:\n textfiles.append(i)\nprint(textfiles)\nfor j in textfiles:\n with open(j, \"r\") as f:\n if \"is unreachable\" in f.read():\n print(f\"It's in this file {j} \\n\")\n","sub_path":"Scan_txt_files.py","file_name":"Scan_txt_files.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"100776567","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtCore import pyqtSignal, QObject\nimport widget\nimport sys\nimport time\nfrom ds18b20 import DS18B20\nimport settings\nfrom threading import Event, Thread\nimport qn8027\n\npath_settings = \"settings.ini\" # Файл настроек\n\n# Communication temperatureThread with UiApp\nclass Communicate(QObject):\n signalT = pyqtSignal(str)\n signalRds = pyqtSignal(str)\ncommun = Communicate()\n\n## UI\nclass UiApp(QtWidgets.QWidget, widget.Ui_Form):\n def __init__(self):\n super().__init__()\n self.setupUi(self) \n \n # INIT WIDGET\n self.doubleSpinBoxFreq.setValue(float(settings.get_setting(path_settings, 'Settings', 'freq')))\n self.doubleSpinBoxPow.setValue(float(settings.get_setting(path_settings, 'Settings', 'power')))\n self.lineEditRds.setText(settings.get_setting(path_settings, 'Settings', 'rds'))\n \n # SLOTS\n commun.signalT.connect(self.temperature)\n self.doubleSpinBoxFreq.valueChanged.connect(self.freq)\n self.doubleSpinBoxPow.valueChanged.connect(self.power)\n self.pushButtonRds.clicked.connect(self.rds)\n self.pushButtonTerminal.clicked.connect(self.terminal)\n \n # QN8027\n qn8027.init()\n self.freq()\n self.power()\n self.rds()\n \n #OVERHEAT\n self.overheat = False\n \n def freq(self):\n f = self.doubleSpinBoxFreq.value()\n qn8027.setFrequency(int(self.doubleSpinBoxFreq.value()*100))\n self.labelStatus.setText(\"freq: \" + str(f) + \"MHz\")\n settings.update_setting(path_settings, 'Settings', \"freq\", str(f)) \n \n def power(self):\n p = self.doubleSpinBoxPow.value()\n qn8027.setPower(self.doubleSpinBoxPow.value())\n self.labelStatus.setText(\"power: \" + str(p)+ \"%\")\n settings.update_setting(path_settings, 'Settings', \"power\", str(p))\n \n def rds(self):\n text = self.lineEditRds.text()\n qn8027.setRDS(text)\n if(len(text)>8):\n text = text[0:8:1]\n else:\n text = text.center(8,\" \")\n commun.signalRds.emit(text)\n self.labelStatus.setText(\"rds: \" + text)\n settings.update_setting(path_settings, 'Settings', \"rds\", text)\n \n \n def terminal(self):\n text = self.lineEditTerminal.text().split(\",\")\n if(len(text)==3):\n reg = int(text[0])\n mask = int(text[1])\n data = int(text[2])\n #print(reg)\n #print(mask)\n #print(data)\n qn8027.writeData(reg, mask, data)\n self.labelStatus.setText(\"Terminal: \"+str(qn8027.readData(reg, 0xFF)))\n \n \n def hello(self, text):\n self.labelStatus.setText(text)\n \n def temperature(self, text):\n self.labelTemp.setText(text)\n if(float(text)>=70. and self.overheat==False):\n qn8027.setPower(0.)\n self.overheat = True\n if(float(text)<70. and self.overheat):\n qn8027.setPower(self.doubleSpinBoxPow.value())\n self.overheat = False\n \n \n \n#TEMPERATURE THREAD\nclass temperatureThread(Thread):\n def __init__(self, event):\n Thread.__init__(self)\n self.stopped = event\n self.ds18b20 = DS18B20()\n\n def run(self):\n while not self.stopped.wait(5):\n commun.signalT.emit(str(self.ds18b20.tempC(0)))\ntemperatureTstop = Event()\ntemperatureT = temperatureThread(temperatureTstop)\n\n#RDS THREAD\nclass rdsThread(Thread):\n def __init__(self, event):\n Thread.__init__(self)\n self.stopped = event\n self.text = \"\"\n commun.signalRds.connect(self.setText)\n\n def run(self):\n while not self.stopped.wait(9):\n qn8027.setRDS(self.text)\n def setText(self, textui):\n self.text = textui \nrdsTstop = Event()\nrdsT = rdsThread(rdsTstop)\n\n###\ndef main():\n app = QtWidgets.QApplication(sys.argv) # Новый экземпляр QApplication\n window = UiApp() # Создаём объект \n window.show() # Показываем окно \n temperatureT.start()\n rdsT.start()\n app.exec_() # и запускаем приложение\n temperatureTstop.set()\n rdsTstop.set()\n sys.exit()\n\n \nif __name__ == '__main__': # Если мы запускаем файл напрямую, а не импортируем\n main() # то запускаем функцию main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"58815818","text":"import cv2\n\no = cv2.imread('yuko.jpg')\n\nup = cv2.pyrUp(o)\ndown = cv2.pyrDown(up)\ndiff = down-o\n\nprint('o.shape', o.shape)\nprint('down.shape', down.shape)\n\ncv2.imshow('o', o)\ncv2.imshow('down', down)\ncv2.imshow('diff', diff)\n\ncv2.waitKey()\ncv2.destroyAllWindows()\n","sub_path":"ex11-4.py","file_name":"ex11-4.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"152610803","text":"#!/usr/bin/python3\n\"\"\"\nAuthor: Jiangye Yuan\n Oak Ridge National Laboratory\nDescription: Building extraction for Cameroon 4 band images\n\"\"\"\n\n# cn+pool -> cn+pool -> cn+pool -> cn+pool can(1,2,6)\n# read rgb bands from OIC 4 bands\n\nimport os\nimport sys\nimport time\nimport argparse\n\nimport numpy\nfrom osgeo import gdal, gdalconst\nimport osr\nimport theano\nimport theano.tensor as T\nfrom theano.tensor.signal import downsample\nfrom theano.tensor.nnet import conv\nfrom theano.tensor.signal import conv as sgnconv\n\nimport pickle\n\nimport glob\nimport random\n\nThr = 127.5/255. # threshold on distance function for boundaries\n\ndef fnParseArgs():\n\n usage = \"usage: python %prog [options]\"\n parser = argparse.ArgumentParser(usage)\n\n parser.add_argument(\"-q\",\n action= \"store_false\",\n dest= \"verbose\",\n help= \"Quiet\",\n default= True)\n\n parser.add_argument(\"-v\",\n action = \"store_true\",\n dest = \"verbose\",\n help = \"Verbose\",\n default = False)\n\n parser.add_argument(\"-p\",\n action = \"store\",\n dest = \"paraFile\",\n help = \"Input parameter file for neural network\",\n type = str,\n required = True)\n\n parser.add_argument(\"-f\",\n action = \"store\",\n dest = \"fileName\",\n help = \"Input text file of image paths\",\n type = str,\n required = True)\n\n parser.add_argument(\"-o\",\n action = \"store\",\n dest = \"outputName\",\n help = \"Output directory\",\n type = str,\n required = True)\n\n parser.add_argument(\"-bbx\",\n action = \"store\",\n dest = \"bbx\",\n nargs = '+',\n help = \"bounding box\",\n type = int,\n required = False)\n\n args = parser.parse_args()\n\n if args.verbose:\n print ('User provided inputs:')\n print ('> INPUTNAME\\t\\t: %s' % args.fileName)\n print ('> OUTPUTNAME\\t\\t: %s' % args.outputName)\n\n return args\n\ndef UpSampling2x(input, img_shp):\n filter1 = theano.shared(numpy.asarray([.5, 1, .5], dtype=theano.config.floatX), borrow=True)\n input1fs_0 = theano.shared(numpy.zeros((img_shp[0],img_shp[1],img_shp[2],img_shp[3]), dtype=theano.config.floatX),\n borrow=True)\n input1fs_0 = T.set_subtensor(input1fs_0[:,:,0:img_shp[2]:2,0:img_shp[3]:2],input)\n\n img_shp1N = (img_shp[0]*img_shp[1],img_shp[2],img_shp[3])\n input1fs_v = sgnconv.conv2d(input1fs_0.reshape(img_shp1N),\n filter1.reshape((1,3)),\n border_mode='full',\n image_shape=img_shp1N,\n filter_shape=(1, 1, 3))[:,:,1:-1]\n input1fs = sgnconv.conv2d(input1fs_v,\n filter1.reshape((3,1)),\n border_mode='full',\n image_shape=img_shp1N,\n filter_shape=(1, 3, 1))[:,1:-1,:].reshape((img_shp[0],img_shp[1],img_shp[2],img_shp[3]))\n return input1fs\n\ndef UpSampling4x(input, img_shp):\n filter2 = theano.shared(numpy.asarray([.25, .5, .75, 1, .75, .5, .25],\n dtype=theano.config.floatX), borrow=True)\n input2fs_0 = theano.shared(numpy.zeros((img_shp[0],img_shp[1],img_shp[2],img_shp[3]), dtype=theano.config.floatX),\n borrow=True)\n input2fs_0 = T.set_subtensor(input2fs_0[:,:,2:img_shp[2]:4,2:img_shp[3]:4],input)\n\n img_shp2N = (img_shp[0]*img_shp[1],img_shp[2],img_shp[3])\n input2fs_v = sgnconv.conv2d(input2fs_0.reshape(img_shp2N),\n filter2.reshape((1,7)),\n border_mode='full',\n image_shape=img_shp2N,\n filter_shape=(1, 1, 7))[:,:,3:-3]\n input2fs = sgnconv.conv2d(input2fs_v,\n filter2.reshape((7,1)),\n border_mode='full',\n image_shape=img_shp2N,\n filter_shape=(1, 7, 1))[:,3:-3,:].reshape((img_shp[0],img_shp[1],img_shp[2],img_shp[3]))\n return input2fs\n\ndef UpSampling8x(input, img_shp):\n filter3 = theano.shared(numpy.asarray([.125, .25, .375, .5, .625, .75, .875, 1,\n .875, .75, .625, .5, .375, .25, .125],\n dtype=theano.config.floatX), borrow=True)\n input3fs_0 = theano.shared(numpy.zeros((img_shp[0],img_shp[1],img_shp[2],img_shp[3]), dtype=theano.config.floatX),\n borrow=True)\n input3fs_0 = T.set_subtensor(input3fs_0[:,:,3:img_shp[2]:8,3:img_shp[3]:8],input)\n\n img_shp3N = (img_shp[0]*img_shp[1],img_shp[2],img_shp[3])\n input3fs_v = sgnconv.conv2d(input3fs_0.reshape(img_shp3N),\n filter3.reshape((1,15)),\n border_mode='full',\n image_shape=img_shp3N,\n filter_shape=(1, 1, 15))[:,:,7:-7]\n input3fs = sgnconv.conv2d(input3fs_v,\n filter3.reshape((15,1)),\n border_mode='full',\n image_shape=img_shp3N,\n filter_shape=(1, 15, 1))[:,7:-7,:].reshape((img_shp[0],img_shp[1],img_shp[2],img_shp[3]))\n return input3fs\n\ndef relu(x):\n return T.switch(x<0, 0, x)\n\nclass LeNetConvPoolLayer(object):\n \"\"\"Pool Layer of a convolutional network \"\"\"\n\n def __init__(self, rng, input, filter_shape, image_shape, poolsize=(2, 2)):\n \"\"\"\n Allocate a LeNetConvPoolLayer with shared variable internal parameters.\n\n :type rng: numpy.random.RandomState\n :param rng: a random number generator used to initialize weights\n\n :type input: theano.tensor.dtensor4\n :param input: symbolic image tensor, of shape image_shape\n\n :type filter_shape: tuple or list of length 4\n :param filter_shape: (number of filters, num input feature maps,\n filter height, filter width)\n\n :type image_shape: tuple or list of length 4\n :param image_shape: (batch size, num input feature maps,\n image height, image width)\n\n :type poolsize: tuple or list of length 2\n :param poolsize: the downsampling (pooling) factor (#rows, #cols)\n \"\"\"\n\n assert image_shape[1] == filter_shape[1]\n self.input = input\n\n fan_in = numpy.prod(filter_shape[1:])\n\n fan_out = (filter_shape[0] * numpy.prod(filter_shape[2:]) /\n numpy.prod(poolsize))\n # initialize weights with random weights\n W_bound = numpy.sqrt(6. / (fan_in + fan_out))\n self.W = theano.shared(\n numpy.asarray(\n rng.uniform(low=-W_bound, high=W_bound, size=filter_shape),\n dtype=theano.config.floatX\n ),\n borrow=True\n )\n\n # the bias is a 1D tensor -- one bias per output feature map\n b_values = numpy.zeros((filter_shape[0],), dtype=theano.config.floatX)\n self.b = theano.shared(value=b_values, borrow=True)\n\n if filter_shape[2] == 1 and filter_shape[3] == 1:\n conv_out = conv.conv2d(\n input=input,\n filters=self.W,\n border_mode='full',\n filter_shape=filter_shape,\n image_shape=image_shape\n )\n else:\n fh = (filter_shape[2]-1)//2\n fw = (filter_shape[3]-1)//2\n\n conv_out = conv.conv2d(\n input=input,\n filters=self.W,\n border_mode='full',\n filter_shape=filter_shape,\n image_shape=image_shape\n )[:,:,fh:-fh,fw:-fw]\n\n # downsample each feature map individually, using maxpooling\n pooled_out = downsample.max_pool_2d(\n input=conv_out,\n ds=poolsize,\n ignore_border=True\n )\n\n self.output = relu(pooled_out + self.b.dimshuffle('x', 0, 'x', 'x'))\n\n self.params = [self.W, self.b]\n\n\ndef evaluate_lenet(args, nkerns=[50, 70, 100, 150, 100, 70, 70], batch_size=1):\n\n rng = numpy.random.RandomState(23455)\n wd = 1000\n ht = 1000\n ovlp = 44\n\n Width_Ninp = wd + ovlp * 2\n Height_Ninp = ht + ovlp * 2\n\n imgshp0 = (Height_Ninp, Width_Ninp)\n imgshp1 = (imgshp0[0]//2, imgshp0[1]//2)\n imgshp2 = (imgshp1[0]//2, imgshp1[1]//2)\n imgshp3 = (imgshp2[0]//2, imgshp2[1]//2)\n imgshp4 = (imgshp3[0]//2, imgshp3[1]//2)\n imgshp5 = imgshp4\n imgshp6 = imgshp5\n\n # allocate symbolic variables for the data\n index = T.lscalar() # index to a [mini]batch\n\n # start-snippet-1\n x = T.matrix('x') # the data is presented as rasterized images\n y = T.matrix('y') # the labels are presented as 1D vector of\n # [int] labels\n\n ######################\n # BUILD ACTUAL MODEL #\n ######################\n print('... building the model')\n\n layer0_input = x.reshape((batch_size, Height_Ninp, Width_Ninp, 3)).dimshuffle(0, 3, 1, 2)\n\n # Construct the first convolutional pooling layer:\n layer0 = LeNetConvPoolLayer(\n rng,\n input=layer0_input,\n image_shape=(batch_size, 3, imgshp0[0], imgshp0[1]),\n filter_shape=(nkerns[0], 3, 5, 5),\n poolsize=(2, 2)\n )\n\n # Construct the second convolutional pooling layer\n layer1 = LeNetConvPoolLayer(\n rng,\n input=layer0.output,\n image_shape=(batch_size, nkerns[0], imgshp1[0], imgshp1[1]),\n filter_shape=(nkerns[1], nkerns[0], 5, 5),\n poolsize=(2, 2)\n )\n\n layer2 = LeNetConvPoolLayer(\n rng,\n input=layer1.output,\n image_shape=(batch_size, nkerns[1], imgshp2[0], imgshp2[1]),\n filter_shape=(nkerns[2], nkerns[1], 3, 3),\n poolsize=(2, 2)\n )\n\n layer3 = LeNetConvPoolLayer(\n rng,\n input=layer2.output,\n image_shape=(batch_size, nkerns[2], imgshp3[0], imgshp3[1]),\n filter_shape=(nkerns[3], nkerns[2], 3, 3),\n poolsize=(2, 2)\n )\n\n layer4 = LeNetConvPoolLayer(\n rng,\n input=layer3.output,\n image_shape=(batch_size, nkerns[3], imgshp4[0], imgshp4[1]),\n filter_shape=(nkerns[4], nkerns[3], 3, 3),\n poolsize=(1, 1)\n )\n layer5 = LeNetConvPoolLayer(\n rng,\n input=layer4.output,\n image_shape=(batch_size, nkerns[4], imgshp5[0], imgshp5[1]),\n filter_shape=(nkerns[5], nkerns[4], 3, 3),\n poolsize=(1, 1)\n )\n layer6 = LeNetConvPoolLayer(\n rng,\n input=layer5.output,\n image_shape=(batch_size, nkerns[5], imgshp6[0], imgshp6[1]),\n filter_shape=(nkerns[6], nkerns[5], 3, 3),\n poolsize=(1, 1)\n )\n\n layer1output_2x = UpSampling2x(layer1.output, (batch_size,nkerns[1],imgshp1[0], imgshp1[1]))\n layer2output_4x = UpSampling4x(layer2.output, (batch_size,nkerns[2],imgshp1[0], imgshp1[1]))\n layer6output_8x = UpSampling8x(layer6.output, (batch_size,nkerns[6],imgshp1[0], imgshp1[1]))\n\n output_all = T.concatenate([layer0.output,\n layer1output_2x,\n layer2output_4x,\n layer6output_8x], axis=1)\n\n layer_fn = LeNetConvPoolLayer(\n rng,\n input=output_all,\n image_shape=(batch_size, nkerns[0]+nkerns[1]+nkerns[2]+nkerns[6], imgshp1[0], imgshp1[1]),\n filter_shape=(128, nkerns[0]+nkerns[1]+nkerns[2]+nkerns[6], 1, 1),\n poolsize=(1, 1)\n )\n\n softmax_input1 = layer_fn.output.dimshuffle(0, 2, 3, 1)\n p_y_given_x1 = T.nnet.softmax(softmax_input1.reshape((batch_size*imgshp1[0]*imgshp1[1], 128)))\n p1 = p_y_given_x1 * T.arange(128).astype('float32')\n net_output = T.sum(p1,axis=1).reshape((batch_size,1,imgshp1[0],imgshp1[1]))/127.#+.25/127.\n\n #net_output = (T.argmax(layer_fn.output,axis=1)/127.)\n net_output_2x = UpSampling2x(net_output.reshape((batch_size,1,imgshp1[0],imgshp1[1])),\n (batch_size,1,imgshp0[0],imgshp0[1]))\n\n save_file = open(args.paraFile,'rb')\n layer0.params[0].set_value(pickle.load(save_file), borrow=True)\n layer0.params[1].set_value(pickle.load(save_file), borrow=True)\n layer1.params[0].set_value(pickle.load(save_file), borrow=True)\n layer1.params[1].set_value(pickle.load(save_file), borrow=True)\n layer2.params[0].set_value(pickle.load(save_file), borrow=True)\n layer2.params[1].set_value(pickle.load(save_file), borrow=True)\n layer3.params[0].set_value(pickle.load(save_file), borrow=True)\n layer3.params[1].set_value(pickle.load(save_file), borrow=True)\n layer4.params[0].set_value(pickle.load(save_file), borrow=True)\n layer4.params[1].set_value(pickle.load(save_file), borrow=True)\n layer5.params[0].set_value(pickle.load(save_file), borrow=True)\n layer5.params[1].set_value(pickle.load(save_file), borrow=True)\n layer6.params[0].set_value(pickle.load(save_file), borrow=True)\n layer6.params[1].set_value(pickle.load(save_file), borrow=True)\n layer_fn.params[0].set_value(pickle.load(save_file), borrow=True)\n layer_fn.params[1].set_value(pickle.load(save_file), borrow=True)\n save_file.close()\n\n print('Processing...')\n\n # create a function to compute the mistakes that are made by the model\n test_model = theano.function([x], [net_output_2x])\n\n # img[img<0]=0\n # img[img>1]=1\n \n imageList = []\n with open(args.fileName, 'r') as handle:\n for row in handle:\n if row.rstrip() not in imageList:\n imageList.append(row.rstrip())\n\n for image in imageList:\n imgfn = os.path.join(args.outputName, os.path.basename(image).replace(os.path.splitext(image)[-1], \".tif\"))\n if not os.path.exists(imgfn):\n print(\"Working on %s...\" % image)\n start_time = time.time()\n src_ds = gdal.Open(image)\n trans = src_ds.GetGeoTransform()\n proj = src_ds.GetProjection()\n imgcols = src_ds.RasterXSize\n imgrows = src_ds.RasterYSize\n \n if args.bbx is not None:\n xoffset = args.bbx[0]\n yoffset = args.bbx[1]\n Width = args.bbx[2]\n Height = args.bbx[3]\n else:\n xoffset = 0\n yoffset = 0\n Width = imgcols\n Height = imgrows\n \n Nw = Width // wd\n Nh = Height // ht\n NwEx = 0\n NhEx = 0\n \n if Width - Nw * wd > 100: # if partial tile larger than\n Nw += 1\n NwEx = 1\n if Height - Nh * ht > 100:\n Nh += 1\n NhEx = 1 \n \n driver = gdal.GetDriverByName( \"GTiff\" )\n dst_ds = driver.Create(imgfn, Width, Height, 1, gdal.GDT_Byte)\n dst_ds.SetProjection(proj)\n dst_ds.SetGeoTransform(trans)\n outBand = dst_ds.GetRasterBand(1)\n \n for i in range(Nh):\n print('%.1f%%' % (i/Nh*100.))\n for j in range(Nw):\n img = numpy.zeros((Height_Ninp,Width_Ninp,3),dtype='float32')\n if j*wd - ovlp < 0:\n xmin = 0\n elif (j+1)*wd + ovlp > Width:\n xmin = j*wd-ovlp*2\n else:\n xmin = j*wd-ovlp\n \n if i*ht - ovlp < 0:\n ymin = 0\n elif (i+1)*ht + ovlp > Height:\n ymin = i*ht-ovlp*2\n else:\n ymin = i*ht-ovlp\n \n if i == Nh-1 and NhEx == 1:\n Htmp = Height - ymin\n else:\n Htmp = Height_Ninp\n \n if j == Nw-1 and NwEx == 1:\n Wtmp = Width - xmin\n else:\n Wtmp = Width_Ninp\n \n for band in range(3):\n band += 1\n srcband = src_ds.GetRasterBand(band)\n tmp = srcband.ReadAsArray(xoffset+xmin, yoffset+ymin, Wtmp, Htmp)\n img[0:Htmp,0:Wtmp,band-1] = tmp/255.\n \n x1 = img.reshape((1,Width_Ninp*Height_Ninp*3))\n # test_set_x = theano.tensor._shared(\n # numpy.asarray(x1,dtype=theano.config.floatX),borrow=True)\n \n # # create a function to compute the mistakes that are made by the model\n # test_model = theano.function(\n # [index],\n # [net_output_2x],\n # givens={\n # x: test_set_x[index * batch_size: (index + 1) * batch_size]\n # }\n # )\n \n tmpOut = test_model(x1)[0].reshape((Height_Ninp,Width_Ninp))\n \n if j*wd - ovlp < 0:\n xmin2 = 0\n elif (j+1)*wd + ovlp > Width:\n xmin2 = ovlp*2\n else:\n xmin2 = ovlp\n \n if i*ht - ovlp < 0:\n ymin2 = 0\n elif (i+1)*ht + ovlp > Height:\n ymin2 = ovlp*2\n else:\n ymin2 = ovlp\n \n tmpOut2 = numpy.zeros((Height_Ninp,Width_Ninp),dtype='float32')\n tmpOut2[tmpOut>=Thr] = 1\n \n if i == Nh-1 and NhEx == 1:\n Htmp2 = Htmp - ovlp*2\n else:\n Htmp2 = ht\n \n if j == Nw-1 and NwEx == 1:\n Wtmp2 = Wtmp - ovlp*2\n else:\n Wtmp2 = wd\n \n msk = tmpOut2[ymin2:ymin2+Htmp2,xmin2:xmin2+Wtmp2]\n #print(numpy.max(msk))\n \n outBand.WriteArray(msk*255, j*wd, i*ht)\n \n transN = (trans[0] + trans[1] * xoffset, trans[1], trans[2], trans[3]\n + trans[5] * yoffset, trans[4], trans[5])\n \n dst_ds = None\n src_ds = None\n \n end_time = time.time()\n print('Image completed in %f minutes...\\n' % ((end_time - start_time) / 60))\n # print >> sys.stderr, ('The code for file ' +\n # os.path.split(__file__)[1] +\n # ' ran for %.2fm' % ((end_time - start_time) / 60.))\n else:\n print(\"Skipping %s...\" % image)\n\nif __name__ == '__main__':\n args = fnParseArgs()\n evaluate_lenet(args)\n\n","sub_path":"BldgExtr_3band_v2.py","file_name":"BldgExtr_3band_v2.py","file_ext":"py","file_size_in_byte":19369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"38778096","text":"import asyncio\n\nfrom aiohttp_wsgi.wsgi import WSGIHandler\n\n\ndef wsgi(application, *, script_name=\"\", **kwargs):\n # Create the WSGI handler.\n wsgi_handler = WSGIHandler(application,\n script_name = script_name,\n **kwargs\n )\n # Create the middleware factory.\n @asyncio.coroutine\n def middleware_factory(app, handler):\n # Create the middleware.\n @asyncio.coroutine\n def middleware(request):\n # See if the script name matches.\n if request.path.startswith(script_name):\n # See if a specific route matches the app.\n route = (yield from app.router.resolve(request))\n if route.route is None:\n # Run the WSGI app.\n return (yield from wsgi_handler(request))\n return (yield from handler(request))\n # All done!\n return middleware\n # All done!\n return middleware_factory\n","sub_path":"aiohttp_wsgi/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"348952662","text":"import numpy as np\nimport pickle\nout_overall = pickle.load(open('../data/input/all_regions.pkl','r'))\n\nimport sys\n\ntrain_region, test_region, test_home, appliance, month_compute, transform, K = sys.argv[1:]\ntest_home = int(test_home)\nmonth_compute = int(month_compute)\nK = int(K)\n\ntrain_df = out_overall[train_region]\ntest_df = out_overall[test_region]\n\n\nimport os\n\nineq_base_path = \"../data/model/inequalities/\"\nineq_path = os.path.join(ineq_base_path, \"%s_%s_%s_%s_%d_%d.pkl\" %(train_region,\n test_region,\n transform,\n appliance,\n month_compute,\n test_home))\n\nrequired_inequalities = pickle.load(open(ineq_path, 'r'))\n\ndef solve_ilp(inequalities, time_limit=50):\n from collections import defaultdict\n import pandas as pd\n co = defaultdict(int)\n for ineq in inequalities:\n lt = ineq[0]\n gt = ineq[1]\n co[lt]-= 1\n co[gt]+= 1\n co_ser = pd.Series(co)\n co_ser.sort()\n\n return co_ser.index.values.tolist()\n\nranks = solve_ilp(required_inequalities)\nmean_proportion = (train_df.ix[ranks[:K]]['%s_%d' %(appliance, month_compute)]/ train_df.ix[ranks[:K]]['aggregate_%d' %(month_compute)]).mean()\npred = test_df.ix[test_home]['aggregate_%d' %month_compute]*mean_proportion\ngt = test_df.ix[test_home]['%s_%d' %(appliance, month_compute)]\n\nimport pickle\npickle.dump(pred, open('../data/output/ineq_cross_proportion/%s_%s_%s_%s_%d_%d_%d.pkl' %(train_region,\n test_region,\n transform,\n appliance,\n month_compute,\n test_home, K),'w'))","sub_path":"new_experiments/pred_ineq.py","file_name":"pred_ineq.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"622403034","text":"from os import listdir\nfrom os.path import isfile, join\nimport cv2\nimport numpy as np\n\nfrom PIL import Image\nfrom matplotlib import cm\nimport scipy.io\n\ndef get_image_segs_name():\n image_path = \"data\\\\images\"\n segs_path = \"data\\\\groundTruth\"\n\n images_names = [f for f in listdir(image_path) if isfile(join(image_path, f))]\n segs_names = [f for f in listdir(segs_path) if isfile(join(segs_path, f))]\n return images_names,segs_names\n\ndef image_reader(image_path,segs_path,image_name,seg_name):\n img = cv2.imread(image_path + '\\\\' + image_name)\n # print(img.shape)\n x = scipy.io.loadmat(segs_path + \"\\\\\" + seg_name)\n temp_data = x['groundTruth'][0]\n\n segments = np.zeros((5, 321 * 481))\n boundries = np.zeros((5, 321 * 481))\n for j in range(5):\n temp_segemant = temp_data[j]['Segmentation'][0, 0]\n # print(temp_segemant.shape)\n temp_segemant = temp_segemant.reshape(321 * 481)\n segments[j, :] = temp_segemant\n temp_boundries = temp_data[j]['Boundaries'][0, 0]\n temp_boundries = temp_boundries.reshape(321 * 481)\n boundries[j, :] = temp_boundries\n\n return img,segments,boundries\ndef calc_distance_to_centres(points , centers ):\n distance_matrix=np.zeros(shape=(len(points),len(centers)))\n for i in range(len(points)):\n for j in range(len(centers)):\n distance_matrix[i,j]=np.linalg.norm(points[i]-centers[j])\n return distance_matrix\ndef euclidian(a, b):\n return np.linalg.norm(a-b)\n\ndef kmeans(dataset, k):\n old_centres= dataset[np.random.randint(1, len(dataset)-1, size=k)]\n new_centres = np.zeros(shape=old_centres.shape)\n distance_between_centres = euclidian(new_centres, old_centres)\n centres_history = []\n labels = np.zeros(shape=(len(dataset)))\n labels_history = []\n while distance_between_centres > 0:\n\n dis = calc_distance_to_centres(dataset, old_centres)\n\n for i in range(len(dis)):\n arr1inds = dis[i].argsort()\n # print(arr1inds[0])\n labels[i] = arr1inds[0]\n # print(dataset[i], \"---->\", dis[i], \"--->\", labels[i])\n temp_centres = np.zeros((old_centres.shape))\n for j in range(len(old_centres)):\n indexes = [k for k in range(len(dataset)) if labels[k] == j]\n temp_centres[j, :] = np.mean(dataset[indexes], axis=0)\n centres_history.append(temp_centres)\n new_centres = temp_centres\n\n # print(new_centres)\n # print(old_centres)\n distance_between_centres = euclidian(new_centres, old_centres)\n old_centres = new_centres\n\n labels_history.append(labels)\n # print(labels_history)\n print(\"centres history\")\n return centres_history,labels_history\n\n\ndef visualize_image_gt(image,segmantes,boundries):\n gt = np.zeros(0)\n\n from matplotlib import pyplot as plt\n # a, b, c = shapes[i]\n #visualize image\n\n plt.imshow(image, interpolation='nearest')\n plt.show()\n a,b,c=image.shape\n\n # trial = boundTry.reshape(image.shape)\n k=np.hstack((segmantes[0].reshape((a,b)),segmantes[1].reshape((a,b)),segmantes[2].reshape((a,b)),segmantes[3].reshape((a,b))))\n\n plt.imshow(k, interpolation='nearest')\n plt.show()\n\n #visualize segmentics\n k=segmantes[3]\n a,b,c=image.shape\n # f=k.reshape((a,b))\n f=np.hstack((boundries[0].reshape((a,b)),boundries[1].reshape((a,b)),boundries[2].reshape((a,b)),boundries[3].reshape((a,b))))\n\n from matplotlib import pyplot as plt\n plt.imshow(f, interpolation='nearest')\n plt.show()\n\n\n\n # visualize boundries\n # k=boundries[3]\n # a,b,c=image.shape\n # f=k.reshape((a,b))\n # from matplotlib import pyplot as plt\n # plt.imshow(f, interpolation='nearest')\n # plt.show()\n '''for i in range(len(gt)):\n for j in range(len(gt[0])):\n if gt[i][j] == 0:\n gt[i][j] = 255\n '''\n # 1st method for image visualization\n # img1 = Image.fromarray(np.uint8(cm.gist_earth(gt0)*255))\n # img2 = Image.fromarray(np.uint8(cm.gist_earth(gt)*255))\n #\n # img1.show()\n # img2.show()\n\n # 2nd method for image visualization\n\n # from matplotlib import pyplot as plt\n # plt.imshow(gt, interpolation='nearest')\n\n # plt.imshow(gt0, interpolation='nearest')\n #\n # plt.show()\n return\ndef calc_confusion_matrix(clusters,ground_truth,k):\n confusion=np.zeros(shape=(k,len(ground_truth)),dtype=int)\n\n for i in range(len(clusters)):\n for j in range(len(ground_truth)):\n if i in int(ground_truth[j]):\n m=int(clusters[i])\n confusion[m,j]=confusion[m,j]+1\n return confusion\n\ndef calc_confusion_matrix2(clustered,ground_truth,k):\n new_shaped_data = np.zeros(shape=(k,len(ground_truth)), dtype=int)\n clusters_sizes = []\n m = 0\n diff_shapes = []\n for i in range(0, k):\n m = 0\n for j in range(len(clustered)):\n if clustered[j] == i:\n new_shaped_data[i, m] = ground_truth[j]\n m += 1\n if ground_truth[j] == 0:\n print(\"Zerooooooooooooooooooo\")\n if ground_truth[j] not in diff_shapes:\n diff_shapes.append(ground_truth[j])\n #new_shaped_data[i] = new_shaped_data[i, :m]\n clusters_sizes.append(m)\n return new_shaped_data, diff_shapes, clusters_sizes\n\ndef cond_entropy(clustered_ground, diff_shapes, N, clusters_sizes):\n total_entropy = 0\n # table = dict(zip(diff_shapes, np.zeros(len(diff_shapes))))\n from math import log\n\n for i in range(len(clustered_ground)):\n # Calculating number of each shape in each cluster\n ni = clusters_sizes[i]\n table = dict(zip(diff_shapes, np.zeros(len(diff_shapes))))\n #print(diff_shapes)\n #print(table)\n #print(table.get(0))\n #for k in range(len(diff_shapes)):\n for j in range(ni+1):\n #print(table)\n key = clustered_ground[i, j]\n if(key != 0):\n #print(key)\n num = table.get(key)+1\n new = {key: num}\n table.update(new)\n # Calculating entropy\n entropy = 0\n for m in range(len(diff_shapes)):\n print(\"m:\", m)\n print(\"Shape: \", diff_shapes[m])\n print(diff_shapes)\n print(\"table: \", table)\n fraction = (table.get(diff_shapes[m])/ni)\n print(\"Table's: \", table.get(diff_shapes[m]))\n print(\"ni: \", ni)\n print(\"Fraction: \", fraction)\n ent = -fraction*log(fraction, 2)\n print(\"Ent: \", ent)\n entropy += ent\n total_entropy += (ni/N)*entropy\n\n return total_entropy\n\nimage_path = \"data\\\\images\"\nsegs_path = \"data\\\\groundTruth\"\nimage_names,image_segs=get_image_segs_name() #get all the file names in a directory\n# print(image_names)\n# print(image_segs)\n'''\nimage,seg,boundries=image_reader(image_path,segs_path,image_names[5],image_segs[5])# your segmantation function + boundries\nk=5\n#print(image)\n#print(seg[0].shape)\n#print(seg[0][0:200])\n#print(boundries)\nb = image.reshape(321 * 481, 3)\n#print(b)\n#from sklearn.cluster import KMeans\n\n#centres_history, labels_history = kmeans(b, k) # k means implementation\n#a = labels_history[-1] # get the final clustring\n\nfrom sklearn.cluster import KMeans\nclustered = KMeans(n_clusters=k, random_state=0)\nclustered.fit(b)\n#print(clustered)\ncolors = clustered.cluster_centers_\nprint(colors)\nlabels = clustered.labels_\n#print(labels.shape)\n'''\ndef plotClusters(LABELS, IMAGE, CENTROID_COLORS):\n new_image = []\n # plotting\n #fig = plt.figure()\n #ax = Axes3D(fig)\n for label, pix in zip(LABELS, IMAGE):\n #ax.scatter(pix[0], pix[1], pix[2], color=rgb_to_hex(COLORS[label]))\n curr_color = CENTROID_COLORS[label]\n new_image.append(curr_color)\n #print(label, pix)\n #plt.show()\n #print(new_image)\n #print(new_image[3])\n new_image = np.reshape(new_image, (321, 481, 3))\n from matplotlib import pyplot as plt\n plt.imshow(new_image, interpolation='nearest')\n plt.show()\n\n#plotClusters(clustered.labels_, b, colors.astype(int))\n\ndef process_five_images_KMEANS(k):\n from sklearn.cluster import KMeans\n for i in range(20, 26):\n clustered = KMeans(n_clusters=k, random_state=0)\n image, seg, boundries = image_reader(image_path, segs_path, image_names[i], image_segs[i])\n imageAs1D = image.reshape(321 * 481, 3)\n clustered.fit(imageAs1D)\n colors = clustered.cluster_centers_\n labels = clustered.labels_\n visualize_image_gt(image, seg, boundries)\n plotClusters(clustered.labels_, imageAs1D, colors.astype(int))\n\n\n\ndef process_five_images_NCUT(k):\n from sklearn.neighbors import kneighbors_graph\n from sklearn.cluster import spectral_clustering\n from sklearn.cluster import SpectralClustering\n from sklearn.cluster import KMeans\n for i in range(21, 26):\n image, seg, boundries = image_reader(image_path, segs_path, image_names[i], image_segs[i])\n imageAs1D = image.reshape(321 * 481, 3)\n #simMatrix1 = kneighbors_graph(imageAs1D, 5)\n #print(np.shape(simMatrix1))\n #simMatrix = simMatrix1.toarray()\n clustered = SpectralClustering(n_clusters=k, affinity='nearest_neighbors', n_neighbors=5, assign_labels='kmeans', n_jobs=1).fit(imageAs1D)\n #colors = clustered.cluster_centers_\n #spectral_clustering(simMatrix1, n_clusters=k, n_components=None, assign_labels='kmeans')\n print(clustered.labels_)\n colors =[]\n import random\n for j in range(0, k):\n r = random.randint(0, 255)\n colors.append([r, r, r])\n #print('#%02X%02X%02X' % (r(), r(), r()))\n\n print(colors)\n visualize_image_gt(image, seg, boundries)\n plotClusters(clustered.labels_, imageAs1D, colors)\n\n\n\nprocess_five_images_NCUT(5)\n\n#process_five_images_KMEANS(5)\n\n\n\n\n#TRY FOR N CUT\n'''\n# Delta matrix ( Degree matrix )\ndef buildDegreeMatrix(simMatrix):\n diag = np.array(simMatrix.sum(axis=1)).ravel()\n result = np.diag(diag)\n return result\n# La Matrix ( Difference between degree and similarity matrix\ndef buildLaplacianMatrix(simMatrix, degreeM):\n result = degreeM - simMatrix\n return result\n\ndef process_five_images_NCUT(k):\n from sklearn.neighbors import kneighbors_graph\n from sklearn.cluster import KMeans\n for i in range(20, 26):\n image, seg, boundries = image_reader(image_path, segs_path, image_names[i], image_segs[i])\n imageAs1D = image.reshape(321 * 481, 3)\n simMatrix1 = kneighbors_graph(imageAs1D, 5, mode='connectivity')\n simMatrix = simMatrix1.toarray()\n delaMatrix = buildDegreeMatrix(simMatrix)\n # print(delaMatrix)\n laplacianMatrix = buildLaplacianMatrix(simMatrix, delaMatrix)\n # print(laplacianMatrix)\n eig_values, eigVectors = np.linalg.eigh(laplacianMatrix)\n ind = eig_values.real.argsort()[:k]\n result = np.ndarray(shape=(laplacianMatrix.shape[0], 0))\n for i in range(0, ind.shape[0]):\n egVecs = np.transpose(np.matrix(eigVectors[:, np.asscalar(ind[i])]))\n result = np.concatenate((result, egVecs), axis=1)\n\n clustered = KMeans(n_clusters=k, random_state=0)\n clustered.fit(result)\n colors = clustered.cluster_centers_\n\n plotClusters(clustered.labels_, imageAs1D, colors.astype(int))\n visualize_image_gt(image, seg, boundries)\n\n'''\n\n'''new_image = np.reshape(plotClusters(clustered.labels_, b, colors.astype(int)), (321, 481, 3))\nfrom matplotlib import pyplot as plt\n\nplt.imshow(new_image, interpolation='nearest')\nplt.show()'''\n\n#print(zip(labels, b))\n\n\n# print(labels_history)\n#print(a.shape)\n#print(a[0:200])\n#output, diff_values ,clusters_sizes= calc_confusion_matrix2(a, seg[0], k)\n#print(clusters_sizes)\n#print(diff_values)\n\n'''for i in range(0,3):\n for j in range(len(output[0])):\n if(output[i, j] == 0):\n print(\"ZEROOOOOOOOOO Damn!\")\n'''\n#cond_entroppy = cond_entropy(output, diff_values, len(a), clusters_sizes)\n\n#print(cond_entroppy)\n'''for i in range(0, k):\n print(\"Class number :\", i)\n for j in range(0, 201):\n print(out[i, j])\n'''\n\n#print(calc_confusion_matrix2(a, seg[0], k)[0][0:200])\n#print(calc_confusion_matrix2(a, seg[0], k)[1][0:200])\n#print(calc_confusion_matrix2(a, seg[0], k)[2][0:200])\n\n#from sklearn.metrics.cluster import completeness_score\n#print(completeness_score(seg[0], a))\n#k,b,c=image.shape\n#f=a.reshape((k,b)) # return the image to it's normal dimensions\n# dataset ,segmantes,boundries,shapes=dataset_reader()\n#visualize_image_gt(image,seg,boundries) # your function + boundries + segmentation\nfrom matplotlib import pyplot as plt\n# segTry=segmantes[0]\n# boundTry=boundries[0]\n# a,b,c=shapes[0]\n# trial=boundTry.reshape(5,a,b)\n\n#plt.imshow(f, interpolation='nearest')\n#plt.show()\n\n\n","sub_path":"Image-Segmentation/main 0(Part 4).py","file_name":"main 0(Part 4).py","file_ext":"py","file_size_in_byte":12943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"554285666","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File : yidianhao.py\n# @Author: Cedar\n# @Date : 2020/4/17\n# @Desc :\n\nimport time\nimport asyncio, aiohttp\nfrom aiohttp import ClientSession\nimport re\nimport json\nfrom datetime import datetime\nfrom elasticsearch import Elasticsearch\nimport hashlib\n\n\ntasks = []\n# url_template = \"http://www.yidianzixun.com/channel/m324649\"\nurl_template = \"http://www.yidianzixun.com/channel/m{}\"\n\n\ndef get_token(md5str):\n # md5str = \"abc\"\n # 生成一个md5对象\n m1 = hashlib.md5()\n # 使用md5对象里的update方法md5转换\n m1.update(md5str.encode(\"utf-16LE\"))\n token = m1.hexdigest()\n return token\n\n\nasync def get_response(url, semaphore):\n async with semaphore:\n async with aiohttp.ClientSession() as session:\n try:\n headers = {\n 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',\n }\n async with session.get(url, headers=headers) as response:\n text = await response.text()\n json_text = re.findall('yidian.docinfo = ({.*});', text)[0]\n result = json.loads(json_text)\n source_name = result[\"channel_name\"]\n\n if len(source_name) > 0:\n try:\n print(url)\n _id = get_token(url)\n\n es = Elasticsearch(\"192.168.2.56:9200\")\n data = {\n \"@timestamp\": datetime.now().strftime(\"%Y-%m-%dT%H:%M:%S.000+0800\"),\n \"title\": source_name,\n \"listpage_url\": url\n }\n es.index(index=\"yidianhao_all\", doc_type=\"yidianhao\", id=_id, body=data)\n\n except Exception as e:\n print(e)\n\n except Exception as e:\n pass\n\n\nasync def create_task(start, end):\n semaphore = asyncio.Semaphore(10) # 限制并发量为500\n for i in range(start, end):\n task = asyncio.ensure_future(get_response(url_template.format(i + 1), semaphore))\n tasks.append(task)\n\n\ndef run():\n loop = asyncio.get_event_loop()\n # for j in range(26953, 100000):\n for j in range(0, 10000):\n print(1000*j, 1000*j+1000)\n global tasks\n tasks = []\n loop.run_until_complete(create_task(1000*j-1, 1000*j+1000))\n loop.run_until_complete(asyncio.gather(*tasks))\n loop.close()\n\n\nif __name__ == '__main__':\n run()\n\n\n\n\n","sub_path":"model/self_media/temp_es/yidianhao/yidianhao.py","file_name":"yidianhao.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"201016852","text":"import iptc\nfrom .utils import format_address\n\n\ndef create_chain(table='filter', chain='input'):\n chain = iptc.Chain(\n iptc.Table(table),\n chain.upper())\n\n return chain\n\n\ndef create_rule():\n rule = iptc.Rule()\n rule.out_interface = 'veth-receiver'\n rule.dst = \"192.168.0.2\"\n rule.protocol = 'icmp'\n match = rule.create_match('icmp')\n match.icmp_type = 'echo-request'\n rule.create_target('DROP')\n\n return rule\n\n\ndef apply_rule(chain, rule, position=0):\n chain.insert_rule(rule, position)\n\n\ndef delete_rule(chain, rule):\n chain.delete_rule(rule)\n","sub_path":"pilter/pilter.py","file_name":"pilter.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"193566620","text":"#add.py\ndef add(x:int, *, y:int)->int:\n\tif type(x) is not int:\n\t\traise TypeError(\"Please enter integer value\")\n\t\tprint (type(x))\n\t'''add two numbers:\n\tx: postional argument\n\ty: keyword argument\n\t'''\n\treturn (x+y)\n\nintAdd=add(y=3, x=2)\nprint(\"intAdd =\", intAdd)\n\nstrAdd=add(\"Meher \", y = \"Krishna\")\nprint(\"strAdd =\", strAdd)\n\n\n","sub_path":"source/validation/pycodes/addVal.py","file_name":"addVal.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"505996664","text":"from django.urls import path \nfrom . import views\n\nurlpatterns = [\n # renders\n path('', views.index),\n path('login/', views.login),\n path('register/', views.register),\n path('logout/', views.logout),\n path('loginReg/', views.loginReg),\n path('description/', views.description)\n \n\n # redirects\n\n]","sub_path":"shop_assist-main/shop_assist/shop_assist_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"124066504","text":"from Tkinter import *\r\nimport tkMessageBox\r\nfrom datetime import datetime\r\n\r\ntop = None\r\ncamper_id_tb = None\r\ncamp_id_tb = None\r\n\r\ndef assign_to_camp_bt_handler():\r\n try:\r\n camper_id = int(camper_id_tb.get())\r\n camp_id = int(camp_id_tb.get())\r\n except:\r\n tkMessageBox.showinfo(title=\"message\",message=\"camper and camp id must be nubmers\")\r\n return\r\n from controller.camper import Camper\r\n from controller.camp import Camp\r\n from controller.bunkhouse import Bunkhouse\r\n from controller.team import Team\r\n checked_in_camper = Camper(camper_id)\r\n checked_in_camp = Camp(camp_id)\r\n if checked_in_camper.select_camper() == None:\r\n tkMessageBox.showinfo(title=\"message\",message=\"camper not found\")\r\n return\r\n tmp_camp_data = checked_in_camp.select_camp()\r\n if tmp_camp_data == None:\r\n tkMessageBox.showinfo(title=\"message\",message=\"camp not found\")\r\n return\r\n #check there is a room for this camper in bunkhouse gender?\r\n data_camper = checked_in_camper.select_camper()\r\n gender = data_camper[3]\r\n bunkhouses_ids = Bunkhouse.get_available_bunkgouses(gender, camp_id)\r\n if len(bunkhouses_ids) < 1:\r\n tkMessageBox.showinfo(title=\"message\",message=\"Sorry, This camp is not available, Choose another one\")\r\n return\r\n #check if this camper is already regestered in this camp\r\n data_camp = Bunkhouse.select_camp_team_bunkhouse(camper_id)\r\n if str(camp_id) in data_camp[0]:\r\n tkMessageBox.showinfo(title=\"message\",message=\"Sorry, This camper is already registered in this camp\")\r\n return\r\n teams_ids = Team.get_available_team(camp_id)\r\n #assign this camper to a team and a bunkhouse and get their ids(inc checked_in_num)\r\n Bunkhouse.increment_checked_in(bunkhouses_ids[0][0])\r\n Team.increment_checked_in(teams_ids[0][0])\r\n #insert a record in Camper_Camp_BunckHouse_Team(camper_id,camp_id,team_id,bunk_house_id,student_checked_in)\r\n Bunkhouse.insert_check_in(camper_id,camp_id,teams_ids[0][0],bunkhouses_ids[0][0])\r\n #show a message box saying, the camper checked in successfully\r\n tkMessageBox.showinfo(title=\"message\",message=\"Camper Assigned successfully\")\r\n mailing_date = str(datetime.now().date())\r\n first_name = data_camper[0]\r\n last_name = data_camper[1]\r\n address = data_camper[4]\r\n camp_start_date = tmp_camp_data[0]\r\n camp_end_date = tmp_camp_data[1]\r\n f1 = open(\"Mailing Label.txt\", 'w')\r\n f1.write(mailing_date + \"\\n\" + first_name + ' ' + last_name + \"\\n\" + address)\r\n f1.close()\r\n import webbrowser\r\n webbrowser.open(\"Mailing Label.txt\")\r\n\r\n f2 = open(\"acceptance letter.txt\", 'w')\r\n f2.write(\"Congratulations \" + first_name + ' ' + last_name +\"! you have been accepted for the camp starting on \" + camp_start_date + \" and ending on \" + camp_end_date + \".\\nThanks\")\r\n f2.close()\r\n webbrowser.open(\"acceptance letter.txt\")\r\n cancel_bt_handler()\r\n\r\ndef cancel_bt_handler():\r\n top.destroy()\r\n\r\ndef start_assign_to_camp():\r\n\r\n global top, camper_id_tb, camp_id_tb\r\n\r\n top = Tk()\r\n top.title(\"Check-in Forum\")\r\n top.minsize(width=400, height=400)\r\n\r\n camper_id_label = Label(top, text = \"Enter camper ID\")\r\n camper_id_tb = Entry(top, width=20)\r\n camp_id_label = Label(top, text = \"Enter Camp ID\")\r\n camp_id_tb = Entry(top, width=20)\r\n\r\n assign_to_camp_bt = Button(top, text=\"Assign to Camp\", width=30, command = assign_to_camp_bt_handler)\r\n cancel_bt = Button(top, text=\"Cancel\", width=30, command = cancel_bt_handler)\r\n\r\n camper_id_label.pack()\r\n camper_id_tb.pack(expand=True)\r\n camp_id_label.pack()\r\n camp_id_tb.pack(expand=True)\r\n assign_to_camp_bt.pack(expand=True)\r\n cancel_bt.pack(expand=True)\r\n\r\n top.mainloop()\r\n","sub_path":"gui/assign_to_camp.py","file_name":"assign_to_camp.py","file_ext":"py","file_size_in_byte":3784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"153767365","text":"# Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Utilities for testing time series models.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.contrib.timeseries.python.timeseries import estimators\nfrom tensorflow.contrib.timeseries.python.timeseries import input_pipeline\nfrom tensorflow.contrib.timeseries.python.timeseries import state_management\nfrom tensorflow.contrib.timeseries.python.timeseries.feature_keys import TrainEvalFeatures\n\nfrom tensorflow.python.client import session\nfrom tensorflow.python.estimator import estimator_lib\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework import random_seed\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.training import adam\nfrom tensorflow.python.training import basic_session_run_hooks\nfrom tensorflow.python.training import coordinator as coordinator_lib\nfrom tensorflow.python.training import queue_runner_impl\nfrom tensorflow.python.util import nest\n\n\nclass AllWindowInputFn(input_pipeline.TimeSeriesInputFn):\n \"\"\"Returns all contiguous windows of data from a full dataset.\n\n In contrast to WholeDatasetInputFn, which does basic shape checking but\n maintains the flat sequencing of data, this `TimeSeriesInputFn` creates\n batches of windows. However, unlike `RandomWindowInputFn` these windows are\n deterministic, starting at every possible offset (i.e. batches of size\n series_length - window_size + 1 are produced).\n \"\"\"\n\n def __init__(self, time_series_reader, window_size):\n \"\"\"Initialize the input_pipeline.\n\n Args:\n time_series_reader: A `input_pipeline.TimeSeriesReader` object.\n window_size: The size of contiguous windows of data to produce.\n \"\"\"\n self._window_size = window_size\n self._reader = time_series_reader\n super(AllWindowInputFn, self).__init__()\n\n def create_batch(self):\n features = self._reader.read_full()\n times = features[TrainEvalFeatures.TIMES]\n num_windows = array_ops.shape(times)[0] - self._window_size + 1\n indices = array_ops.reshape(math_ops.range(num_windows), [num_windows, 1])\n # indices contains the starting point for each window. We now extend these\n # indices to include the elements inside the windows as well by doing a\n # broadcast addition.\n increments = array_ops.reshape(math_ops.range(self._window_size), [1, -1])\n all_indices = array_ops.reshape(indices + increments, [-1])\n # Select the appropriate elements in the batch and reshape the output to 3D.\n features = {\n key: array_ops.reshape(\n array_ops.gather(value, all_indices),\n array_ops.concat(\n [[num_windows, self._window_size], array_ops.shape(value)[1:]],\n axis=0))\n for key, value in features.items()\n }\n return (features, None)\n\n\nclass _SavingTensorHook(basic_session_run_hooks.LoggingTensorHook):\n \"\"\"A hook to save Tensors during training.\"\"\"\n\n def __init__(self, tensors, every_n_iter=None, every_n_secs=None):\n self.tensor_values = {}\n super(_SavingTensorHook, self).__init__(\n tensors=tensors, every_n_iter=every_n_iter,\n every_n_secs=every_n_secs)\n\n def after_run(self, run_context, run_values):\n del run_context\n if self._should_trigger:\n for tag in self._current_tensors.keys():\n self.tensor_values[tag] = run_values.results[tag]\n self._timer.update_last_triggered_step(self._iter_count)\n self._iter_count += 1\n\n\ndef _train_on_generated_data(\n generate_fn, generative_model, train_iterations, seed,\n learning_rate=0.1, ignore_params_fn=lambda _: (),\n derived_param_test_fn=lambda _: (),\n train_input_fn_type=input_pipeline.WholeDatasetInputFn,\n train_state_manager=state_management.PassthroughStateManager()):\n \"\"\"The training portion of parameter recovery tests.\"\"\"\n random_seed.set_random_seed(seed)\n generate_graph = ops.Graph()\n with generate_graph.as_default():\n with session.Session(graph=generate_graph):\n generative_model.initialize_graph()\n time_series_reader, true_parameters = generate_fn(generative_model)\n true_parameters = {\n tensor.name: value for tensor, value in true_parameters.items()}\n eval_input_fn = input_pipeline.WholeDatasetInputFn(time_series_reader)\n eval_state_manager = state_management.PassthroughStateManager()\n true_parameter_eval_graph = ops.Graph()\n with true_parameter_eval_graph.as_default():\n generative_model.initialize_graph()\n ignore_params = ignore_params_fn(generative_model)\n feature_dict, _ = eval_input_fn()\n eval_state_manager.initialize_graph(generative_model)\n feature_dict[TrainEvalFeatures.VALUES] = math_ops.cast(\n feature_dict[TrainEvalFeatures.VALUES], generative_model.dtype)\n model_outputs = eval_state_manager.define_loss(\n model=generative_model,\n features=feature_dict,\n mode=estimator_lib.ModeKeys.EVAL)\n with session.Session(graph=true_parameter_eval_graph) as sess:\n variables.global_variables_initializer().run()\n coordinator = coordinator_lib.Coordinator()\n queue_runner_impl.start_queue_runners(sess, coord=coordinator)\n true_param_loss = model_outputs.loss.eval(feed_dict=true_parameters)\n true_transformed_params = {\n param: param.eval(feed_dict=true_parameters)\n for param in derived_param_test_fn(generative_model)}\n coordinator.request_stop()\n coordinator.join()\n\n saving_hook = _SavingTensorHook(\n tensors=true_parameters.keys(),\n every_n_iter=train_iterations - 1)\n\n class _RunConfig(estimator_lib.RunConfig):\n\n @property\n def tf_random_seed(self):\n return seed\n\n estimator = estimators._TimeSeriesRegressor( # pylint: disable=protected-access\n model=generative_model,\n config=_RunConfig(),\n state_manager=train_state_manager,\n optimizer=adam.AdamOptimizer(learning_rate))\n train_input_fn = train_input_fn_type(time_series_reader=time_series_reader)\n trained_loss = (estimator.train(\n input_fn=train_input_fn,\n max_steps=train_iterations,\n hooks=[saving_hook]).evaluate(\n input_fn=eval_input_fn, steps=1))[\"loss\"]\n logging.info(\"Final trained loss: %f\", trained_loss)\n logging.info(\"True parameter loss: %f\", true_param_loss)\n return (ignore_params, true_parameters, true_transformed_params,\n trained_loss, true_param_loss, saving_hook,\n true_parameter_eval_graph)\n\n\ndef test_parameter_recovery(\n generate_fn, generative_model, train_iterations, test_case, seed,\n learning_rate=0.1, rtol=0.2, atol=0.1, train_loss_tolerance_coeff=0.99,\n ignore_params_fn=lambda _: (),\n derived_param_test_fn=lambda _: (),\n train_input_fn_type=input_pipeline.WholeDatasetInputFn,\n train_state_manager=state_management.PassthroughStateManager()):\n \"\"\"Test that a generative model fits generated data.\n\n Args:\n generate_fn: A function taking a model and returning a `TimeSeriesReader`\n object and dictionary mapping parameters to their\n values. model.initialize_graph() will have been called on the model\n before it is passed to this function.\n generative_model: A timeseries.model.TimeSeriesModel instance to test.\n train_iterations: Number of training steps.\n test_case: A tf.test.TestCase to run assertions on.\n seed: Same as for TimeSeriesModel.unconditional_generate().\n learning_rate: Step size for optimization.\n rtol: Relative tolerance for tests.\n atol: Absolute tolerance for tests.\n train_loss_tolerance_coeff: Trained loss times this value must be less\n than the loss evaluated using the generated parameters.\n ignore_params_fn: Function mapping from a Model to a list of parameters\n which are not tested for accurate recovery.\n derived_param_test_fn: Function returning a list of derived parameters\n (Tensors) which are checked for accurate recovery (comparing the value\n evaluated with trained parameters to the value under the true\n parameters).\n\n As an example, for VARMA, in addition to checking AR and MA parameters,\n this function can be used to also check lagged covariance. See\n varma_ssm.py for details.\n train_input_fn_type: The `TimeSeriesInputFn` type to use when training\n (likely `WholeDatasetInputFn` or `RandomWindowInputFn`). If None, use\n `WholeDatasetInputFn`.\n train_state_manager: The state manager to use when training (likely\n `PassthroughStateManager` or `ChainingStateManager`). If None, use\n `PassthroughStateManager`.\n \"\"\"\n (ignore_params, true_parameters, true_transformed_params,\n trained_loss, true_param_loss, saving_hook, true_parameter_eval_graph\n ) = _train_on_generated_data(\n generate_fn=generate_fn, generative_model=generative_model,\n train_iterations=train_iterations, seed=seed, learning_rate=learning_rate,\n ignore_params_fn=ignore_params_fn,\n derived_param_test_fn=derived_param_test_fn,\n train_input_fn_type=train_input_fn_type,\n train_state_manager=train_state_manager)\n trained_parameter_substitutions = {}\n for param in true_parameters.keys():\n evaled_value = saving_hook.tensor_values[param]\n trained_parameter_substitutions[param] = evaled_value\n true_value = true_parameters[param]\n logging.info(\"True %s: %s, learned: %s\",\n param, true_value, evaled_value)\n with session.Session(graph=true_parameter_eval_graph):\n for transformed_param, true_value in true_transformed_params.items():\n trained_value = transformed_param.eval(\n feed_dict=trained_parameter_substitutions)\n logging.info(\"True %s [transformed parameter]: %s, learned: %s\",\n transformed_param, true_value, trained_value)\n test_case.assertAllClose(true_value, trained_value,\n rtol=rtol, atol=atol)\n\n if ignore_params is None:\n ignore_params = []\n else:\n ignore_params = nest.flatten(ignore_params)\n ignore_params = [tensor.name for tensor in ignore_params]\n if trained_loss > 0:\n test_case.assertLess(trained_loss * train_loss_tolerance_coeff,\n true_param_loss)\n else:\n test_case.assertLess(trained_loss / train_loss_tolerance_coeff,\n true_param_loss)\n for param in true_parameters.keys():\n if param in ignore_params:\n continue\n evaled_value = saving_hook.tensor_values[param]\n true_value = true_parameters[param]\n test_case.assertAllClose(true_value, evaled_value,\n rtol=rtol, atol=atol)\n\n\ndef parameter_recovery_dry_run(\n generate_fn, generative_model, seed,\n learning_rate=0.1,\n train_input_fn_type=input_pipeline.WholeDatasetInputFn,\n train_state_manager=state_management.PassthroughStateManager()):\n \"\"\"Test that a generative model can train on generated data.\n\n Args:\n generate_fn: A function taking a model and returning a\n `input_pipeline.TimeSeriesReader` object and a dictionary mapping\n parameters to their values. model.initialize_graph() will have been\n called on the model before it is passed to this function.\n generative_model: A timeseries.model.TimeSeriesModel instance to test.\n seed: Same as for TimeSeriesModel.unconditional_generate().\n learning_rate: Step size for optimization.\n train_input_fn_type: The type of `TimeSeriesInputFn` to use when training\n (likely `WholeDatasetInputFn` or `RandomWindowInputFn`). If None, use\n `WholeDatasetInputFn`.\n train_state_manager: The state manager to use when training (likely\n `PassthroughStateManager` or `ChainingStateManager`). If None, use\n `PassthroughStateManager`.\n \"\"\"\n _train_on_generated_data(\n generate_fn=generate_fn, generative_model=generative_model,\n seed=seed, learning_rate=learning_rate,\n train_input_fn_type=train_input_fn_type,\n train_state_manager=train_state_manager,\n train_iterations=2)\n","sub_path":"tensorflow/contrib/timeseries/python/timeseries/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":12799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"260863266","text":"import math\nfrom copy import deepcopy\n\nclass Rational:\n def __init__(self, num, denom):\n if not isinstance(num, int):\n raise RuntimeError('numerator must be integral')\n if not isinstance(denom, int):\n raise RuntimeError('denominator must be integral')\n\n self.num = num\n self.denom = denom\n\n self.reduce()\n\n def reduce(self):\n negative = (self.denom < 0 and self.num > 0) or (self.denom > 0 and self.num < 0)\n if negative:\n if self.denom < 0:\n self.denom = -self.denom\n self.num = -self.num\n\n g = int(math.gcd(self.num, self.denom))\n if g == 1:\n return\n self.num //= g\n self.denom //= g\n\n def invert(self):\n tmp = self.num\n self.num = self.denom\n self.denom = tmp\n\n self.reduce()\n\n return self\n\n def __add__(self, other):\n if isinstance(other, int):\n return self + Rational(other, 1)\n if isinstance(other, Rational):\n final_denom = self.denom * other.denom\n selfnum = self.num * other.denom\n othernum = other.num * self.denom\n\n self.num = selfnum + othernum\n self.denom = final_denom\n\n self.reduce()\n\n return self\n\n return NotImplemented\n\n def __sub__(self, other):\n if isinstance(other, int):\n return self + Rational(other, -1)\n\n if isinstance(other, Rational):\n copy = deepcopy(other)\n copy.num = -copy.num\n return self + copy\n\n return NotImplemented\n\n def __mul__(self, other):\n if isinstance(other, int):\n return self * Rational(other, 1)\n\n if isinstance(other, Rational):\n self.num *= other.num\n self.denom *= other.denom\n\n self.reduce()\n\n return self\n\n return NotImplemented\n\n def __truediv__(self, other):\n if isinstance(other, int):\n return self * Rational(1, other)\n\n if isinstance(other, Rational):\n return self * other.invert()\n\n return NotImplemented\n\n def __floordiv__(self, other):\n self = self / other\n self.num = int(math.floor(float(self)))\n self.denom = 1\n\n return self\n\n def __lt__(self, other):\n return float(self) < float(other)\n\n def __eq__(self, other):\n self.reduce()\n other.reduce()\n return self.num == other.num and self.denom == other.denom\n\n def __le__(self, other):\n return self < other or self == other\n\n def __float__(self):\n return self.num / self.denom\n\n def __repr__(self):\n return '{}'.format(float(self))\n\ndef test(N=10):\n d = {}\n for i in range(1, N):\n for j in range(1,N):\n if Rational(i, j) > Rational(1,1):\n continue\n if i == j:\n continue\n d[(i,j)] = Rational(i,j)\n if N * N < 1000:\n print('{}/{} -> {}'.format( i, j, Rational(i,j)))\n\n l = [float(f) for f in sorted(d.values())]\n l = sorted(list(set(l)))\n import matplotlib.pyplot as plt\n plt.plot(l, [1]*len(l), linestyle='', marker='|')\n plt.show()\n if N * N < 1000:\n print(l)\n MM = -1\n prev = Rational(0,1)\n\n import numpy as np\n\n print(np.diff(l).max())\n\n for r in l:\n continue\n print(np.diff(np.array(l)), r.num, r.denom)\n\n","sub_path":"fracs.py","file_name":"fracs.py","file_ext":"py","file_size_in_byte":3467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"230349469","text":"import logging\nimport piweather\nfrom datetime import datetime\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import Integer, Float, DateTime\n\n\nDTYPE_MAP = {\n int: Integer,\n float: Float,\n datetime: DateTime,\n}\n\n\ndef get_engine(url=None):\n if piweather.db is None:\n\n if url is not None:\n db_url = url\n elif piweather.config is not None:\n db_url = piweather.config.DB_ENGINE\n else:\n logging.error(\"No DB_ENGINE url specified\")\n raise RuntimeError\n piweather.db = create_engine(db_url)\n\n return piweather.db\n\n\ndef map_dtype(dtype):\n if dtype not in DTYPE_MAP:\n raise TypeError(\"No column known to map for '{}'\".format(dtype))\n return DTYPE_MAP[dtype]\n","sub_path":"piweather/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"137745162","text":"# Faça um algoritmo que receba o peso, a idade e a altura de cem pessoas, calcule e informe os\n# valores de: maior peso, menor peso, maior altura, menor altura, maior idade e menor idade deste grupo.\n\ncounter = 2\n\npeso=int\nmenorpeso=int\nmaiorpeso=int(0)\n\nidade=int\nmenoridade=int\nmaioridade=int(0)\n\naltura=int\nmenoraltura=int\nmaioraltura=int(0)\n\nprint(\"Escreva os dados do 1º participante:\")\nmenorpeso=input(\"Peso:\")\nmenorpeso=int(menorpeso)\n\nmenoridade=input(\"Idade:\")\nmenoridade=int(menoridade)\n\nmenoraltura=input(\"Altura:\")\nmenoraltura=int(menoraltura)\n\nwhile counter < 101:\n\tprint(\"Escreva os dados do\",counter,\"º participante:\")\n\tpeso=input(\"Peso:\")\n\tpeso=int(peso)\n\n\tif pesomaiorpeso:\n\t\tmaiorpeso = peso\n\n\tidade=input(\"Idade:\")\n\tidade=int(idade)\n\n\tif idademaioridade:\n\t\tmaioridade = idade\n\n\taltura=input(\"Altura:\")\n\taltura=int(altura)\n\n\tif alturamaioraltura:\n\t\tmaioraltura = altura\n\n\tcounter += 1\n\nprint(\"O menor peso é:\",menorpeso)\t\nprint(\"O maior peso é:\",maiorpeso)\nprint(\"A menor altura é:\",menoraltura)\t\nprint(\"A maior altura é:\",maioraltura)\nprint(\"A menor idade é:\",menoridade)\t\nprint(\"A maior idade é:\",maioridade)\n\n","sub_path":"10.py","file_name":"10.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"423863183","text":"from spacy.tokens import Doc\nfrom spacy.tokens import Span\nfrom spacy.language import Language\nfrom taxonerd.linking.candidate_generation import CandidateGenerator, LinkerPaths\nfrom typing import Optional\n\n\n@Language.factory(\"taxo_linker\")\nclass EntityLinker:\n \"\"\"\n A spacy pipeline component which identifies entities in text which appear\n in a knowledge base.\n\n Currently, there are two defaults: the Unified Medical Language System (UMLS) and\n the Medical Subject Headings (MESH) dictionary.\n\n To use these configured default KBs, pass the `name` parameter, either 'umls' or 'mesh'.\n\n Currently this implementation just compares string similarity, returning\n entities above a given threshold.\n\n This class sets the `._.kb_ents` attribute on spacy Spans, which consists of a\n List[Tuple[str, float]] corresponding to the KB concept_id and the associated score\n for a list of `max_entities_per_mention` number of entities.\n\n You can look up more information for a given id using the kb attribute of this class:\n\n print(linker.kb.cui_to_entity[concept_id])\n\n A Note on Definitions:\n Only 187767 entities, or 6.74% of the UMLS KB have definitions. However,\n the MedMentions dataset links to entities which have definitions 82.9% of the time. So by\n default, we only link to entities which have definitions (typically they are more salient / cleaner),\n but this might not suit your use case. YMMV.\n\n\n Parameters\n ----------\n\n nlp: `Language`, a required argument for spacy to use this as a factory\n name: `str`, a required argument for spacy to use this as a factory\n candidate_generator : `CandidateGenerator`, optional, (default = None)\n A CandidateGenerator to generate entity candidates for mentions.\n If no candidate generator is passed, the default pretrained one is used.\n resolve_abbreviations : bool = True, optional (default = False)\n Whether to resolve abbreviations identified in the Doc before performing linking.\n This parameter has no effect if there is no `AbbreviationDetector` in the spacy\n pipeline.\n k : int, optional, (default = 30)\n The number of nearest neighbours to look up from the candidate generator per mention.\n threshold : float, optional, (default = 0.7)\n The threshold that a entity candidate must reach to be added to the mention in the Doc\n as a mention candidate.\n no_definition_threshold : float, optional, (default = 0.95)\n The threshold that a entity candidate must reach to be added to the mention in the Doc\n as a mention candidate if the entity candidate does not have a definition.\n filter_for_definitions: bool, default = True\n Whether to filter entities that can be returned to only include those with definitions\n in the knowledge base.\n max_entities_per_mention : int, optional, default = 5\n The maximum number of entities which will be returned for a given mention, regardless of\n how many are nearest neighbours are found.\n linker_name: str, optional (default = None)\n The name of the pretrained entity linker to load.\n \"\"\"\n\n def __init__(\n self,\n nlp: Optional[Language] = None,\n name: str = \"taxonerd_linker\",\n candidate_generator: Optional[CandidateGenerator] = None,\n resolve_abbreviations: bool = True,\n k: int = 30,\n threshold: float = 0.7,\n no_definition_threshold: float = 0.95,\n filter_for_definitions: bool = True,\n max_entities_per_mention: int = 5,\n linker_name: Optional[str] = None,\n ):\n # TODO(Mark): Remove in scispacy v1.0.\n # Span.set_extension(\"umls_ents\", default=[], force=True)\n Span.set_extension(\"kb_ents\", default=[], force=True)\n\n self.candidate_generator = candidate_generator or CandidateGenerator(\n name_or_path=linker_name\n )\n self.resolve_abbreviations = resolve_abbreviations\n self.k = k\n self.threshold = threshold\n self.no_definition_threshold = no_definition_threshold\n self.kb = self.candidate_generator.kb\n self.filter_for_definitions = filter_for_definitions\n self.max_entities_per_mention = max_entities_per_mention\n\n # TODO(Mark): Remove in scispacy v1.0. This is for backward compatability only.\n # self.umls = self.kb\n\n def __call__(self, doc: Doc) -> Doc:\n mentions = doc.ents\n mention_strings = []\n\n if self.resolve_abbreviations and Doc.has_extension(\"abbreviations\"):\n # TODO: This is possibly sub-optimal - we might\n # prefer to look up both the long and short forms.\n mention_strings = [\n ent._.long_form.text for ent in doc.ents if ent._.long_form is not None\n ]\n # mention_strings = [\n # \" \".join([tok.lemma_ for tok in ent._.long_form]) for ent in doc.ents if ent._.long_form is not None\n # ]\n else:\n mention_strings = [ent.text for ent in doc.ents]\n # mention_strings = [\n # \" \".join([tok.lemma_ for tok in ent]) for ent in doc.ents\n # ]\n # print(doc.ents, mention_strings)\n unique_mention_strings = set(mention_strings)\n\n if len(unique_mention_strings) > 0:\n batch_candidates = self.candidate_generator(unique_mention_strings, self.k)\n # batch_candidates = self.candidate_generator(mention_strings, self.k)\n\n kb_ents_per_mention_string = {}\n\n for mention_string, candidates in zip(\n unique_mention_strings, batch_candidates\n ):\n # for mention, candidates in zip(doc.ents, batch_candidates):\n predicted = []\n for cand in candidates:\n score = max(cand.similarities)\n if (\n self.filter_for_definitions\n and self.kb.cui_to_entity[cand.concept_id].definition is None\n and score < self.no_definition_threshold\n ):\n continue\n if score > self.threshold:\n predicted.append((cand.concept_id, cand.aliases[0], score))\n sorted_predicted = sorted(predicted, reverse=True, key=lambda x: x[2])\n # mention._.umls_ents = sorted_predicted[: self.max_entities_per_mention]\n kb_ents = sorted_predicted[: self.max_entities_per_mention]\n\n kb_ents_per_mention_string[mention_string] = (\n kb_ents if kb_ents else None\n )\n # mention._.kb_ents = kb_ents if kb_ents != [] else None\n\n new_ents = []\n for mention in mentions:\n if self.resolve_abbreviations and Doc.has_extension(\"abbreviations\"):\n if mention._.long_form is not None:\n mention._.kb_ents = kb_ents_per_mention_string[\n mention._.long_form.text\n ]\n # mention_text = \" \".join([tok.lemma_ for tok in mention._.long_form])\n else:\n # mention_text = \" \".join([tok.lemma_ for tok in mention])\n mention._.kb_ents = kb_ents_per_mention_string[mention.text]\n # mention._.kb_ents = kb_ents_per_mention_string[mention_text] #mention.text]\n if mention._.kb_ents:\n new_ents.append(mention)\n\n doc.set_ents(new_ents) # Remove unlinked entities (fix #3)\n\n return doc\n","sub_path":"taxonerd/linking/linking.py","file_name":"linking.py","file_ext":"py","file_size_in_byte":7660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"503111121","text":"import xml.etree.ElementTree as ET\nfrom os import getcwd\n\nsets=[('train')]\n\n#classes = [\"aeroplane\", \"bicycle\", \"bird\", \"boat\", \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\", \"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\", \"sofa\", \"train\", \"tvmonitor\"]\nclasses = [\"car\" , \"face\"]\n\ndef convert_annotation(image_id, list_file):\n in_file = open('train_data/xml/%s.xml'%image_id,encoding='gbk', errors='ignore')\n tree=ET.parse(in_file)\n root = tree.getroot()\n\n for obj in root.iter('object'):\n difficult = obj.find('difficult').text\n cls = obj.find('name').text\n if cls not in classes or int(difficult)==1:\n continue\n cls_id = classes.index(cls)\n xmlbox = obj.find('bndbox')\n b = (int(xmlbox.find('xmin').text), int(xmlbox.find('ymin').text), int(xmlbox.find('xmax').text), int(xmlbox.find('ymax').text))\n list_file.write(\" \" + \",\".join([str(a) for a in b]) + ',' + str(cls_id))\n\n\nwd = getcwd()\n\nfor image_set in sets:\n image_ids = open('train_data/Main/%s.txt'%image_set).read().strip().split()\n list_file = open('training_list/Checklist_%s.txt'%image_set, 'w')\n for image_id in image_ids:\n in_file = open('train_data/xml/%s.xml'%image_id,encoding='gbk', errors='ignore')\n tree=ET.parse(in_file)\n root = tree.getroot()\n clas = root.find('folder').text\n imgname = (root.find('filename').text)#.replace('.jpg', '')\n list_file.write('train_data/images/%s/%s'%(clas,imgname))\n\n convert_annotation(image_id, list_file)\n list_file.write('\\n')\n list_file.close()\n","sub_path":"2_make_train_list_for_windows.py","file_name":"2_make_train_list_for_windows.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"226979981","text":"# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n###############################################################################\n# PURPOSE:\n# Lambda function to check the status of a Rekognition job and save that job's\n# data to the MIE dataplane when the job is complete.\n###############################################################################\n\nimport os\nimport boto3\nimport json\nfrom botocore import config\nfrom MediaInsightsEngineLambdaHelper import OutputHelper\nfrom MediaInsightsEngineLambdaHelper import MasExecutionError\nfrom MediaInsightsEngineLambdaHelper import DataPlane\n\noperator_name = os.environ['OPERATOR_NAME']\noutput_object = OutputHelper(operator_name)\n\nmie_config = json.loads(os.environ['botoConfig'])\nconfig = config.Config(**mie_config)\nrek = boto3.client('rekognition', config=config)\n\ndef lambda_handler(event, context):\n print(\"We got the following event:\\n\", event)\n try:\n status = event[\"Status\"]\n asset_id = event['MetaData']['AssetId']\n except KeyError as e:\n output_object.update_workflow_status(\"Error\")\n output_object.add_workflow_metadata(ContentModerationError=\"Missing key {e}\".format(e=e))\n raise MasExecutionError(output_object.return_output_object())\n # Images will have already been processed, so return if job status is already set.\n if status == \"Complete\":\n output_object.update_workflow_status(\"Complete\")\n return output_object.return_output_object()\n try:\n job_id = event[\"MetaData\"][\"JobId\"]\n workflow_id = event[\"MetaData\"][\"WorkflowExecutionId\"]\n except KeyError as e:\n output_object.update_workflow_status(\"Error\")\n output_object.add_workflow_metadata(ContentModerationError=\"Missing a required metadata key {e}\".format(e=e))\n raise MasExecutionError(output_object.return_output_object())\n # Check rekognition job status:\n dataplane = DataPlane()\n pagination_token = ''\n is_paginated = False\n # If pagination token is in event[\"MetaData\"] then use that to start\n # reading reko results from where this Lambda's previous invocation left off.\n if (\"PageToken\" in event[\"MetaData\"]):\n pagination_token = event[\"MetaData\"][\"PageToken\"]\n is_paginated = True\n # Read and persist 10 reko pages per invocation of this Lambda\n for page_number in range(11):\n # Get reko results\n print(\"job id: \" + job_id + \" page token: \" + pagination_token)\n try:\n response = rek.get_content_moderation(JobId=job_id, NextToken=pagination_token)\n except rek.exceptions.InvalidPaginationTokenException as e:\n # Trying to reverse seek to the last valid pagination token would be difficult\n # to implement, so in the rare case that a pagination token expires we'll\n # just start over by reading from the first page.\n print(e)\n print(\"WARNING: Invalid pagination token found. Restarting read from first page.\")\n pagination_token = ''\n continue\n # If the reko job is IN_PROGRESS then return. We'll check again after a step function wait.\n if response['JobStatus'] == \"IN_PROGRESS\":\n output_object.update_workflow_status(\"Executing\")\n output_object.add_workflow_metadata(JobId=job_id, AssetId=asset_id, WorkflowExecutionId=workflow_id)\n return output_object.return_output_object()\n # If the reko job is FAILED then mark the workflow status as Error and return.\n elif response['JobStatus'] == \"FAILED\":\n output_object.update_workflow_status(\"Error\")\n output_object.add_workflow_metadata(JobId=job_id, ContentModerationError=str(response[\"StatusMessage\"]))\n raise MasExecutionError(output_object.return_output_object())\n # If the reko job is SUCCEEDED then save this current reko page result\n # and continue to next page_number.\n elif response['JobStatus'] == \"SUCCEEDED\":\n # If reko results contain more pages then save this page and continue to the next page\n if 'NextToken' in response:\n is_paginated = True\n # Persist rekognition results (current page)\n metadata_upload = dataplane.store_asset_metadata(asset_id=asset_id, operator_name=operator_name, workflow_id=workflow_id, results=response, paginate=True, end=False)\n # If dataplane request succeeded then get the next pagination token and continue.\n if \"Status\" in metadata_upload and metadata_upload[\"Status\"] == \"Success\":\n # Log that this page has been successfully uploaded to the dataplane\n print(\"Uploaded metadata for asset: {asset}, job {JobId}, page {page}\".format(asset=asset_id, JobId=job_id, page=pagination_token))\n # Get the next pagination token:\n pagination_token = response['NextToken']\n # In order to avoid Lambda timeouts, we're only going to persist 10 pages then\n # pass the pagination token to the workflow metadata and let our step function\n # invoker restart this Lambda. The pagination token allows this Lambda\n # continue from where it left off.\n if page_number == 10:\n output_object.update_workflow_status(\"Executing\")\n output_object.add_workflow_metadata(PageToken=pagination_token, JobId=job_id, AssetId=asset_id, WorkflowExecutionId=workflow_id)\n return output_object.return_output_object()\n # If dataplane request failed then mark workflow as failed\n else:\n output_object.update_workflow_status(\"Error\")\n output_object.add_workflow_metadata(ContentModerationError=\"Unable to upload metadata for asset: {asset}\".format(asset=asset_id), JobId=job_id)\n raise MasExecutionError(output_object.return_output_object())\n # If reko results contain no more pages then save this page and mark the stage complete\n else:\n # If we've been saving pages, then tell dataplane this is the last page\n if is_paginated:\n metadata_upload = dataplane.store_asset_metadata(asset_id=asset_id, operator_name=operator_name, workflow_id=workflow_id, results=response, paginate=True, end=True)\n # If there is only one page then save to dataplane without dataplane options\n else:\n metadata_upload = dataplane.store_asset_metadata(asset_id=asset_id, operator_name=operator_name, workflow_id=workflow_id, results=response)\n # If dataplane request succeeded then mark the stage complete\n if \"Status\" in metadata_upload and metadata_upload[\"Status\"] == \"Success\":\n print(\"Uploaded metadata for asset: {asset}\".format(asset=asset_id))\n output_object.add_workflow_metadata(JobId=job_id)\n output_object.update_workflow_status(\"Complete\")\n return output_object.return_output_object()\n # If dataplane request failed then mark workflow as failed\n else:\n output_object.update_workflow_status(\"Error\")\n output_object.add_workflow_metadata(ContentModerationError=\"Unable to upload metadata for {asset}: {error}\".format(asset=asset_id, error=metadata_upload))\n output_object.add_workflow_metadata(JobId=job_id)\n raise MasExecutionError(output_object.return_output_object())\n # If reko job failed then mark workflow as failed\n else:\n output_object.update_workflow_status(\"Error\")\n output_object.add_workflow_metadata(ContentModerationError=\"Unable to determine status\")\n raise MasExecutionError(output_object.return_output_object())\n","sub_path":"source/operators/rekognition/check_content_moderation_status.py","file_name":"check_content_moderation_status.py","file_ext":"py","file_size_in_byte":8047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"351030352","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/colin/Projects/pyqode.core/pyqode/core/_forms/dlg_unsaved_files_ui.py\n# Compiled at: 2016-12-29 05:31:31\n# Size of source mod 2**32: 1658 bytes\nfrom pyqode.qt import QtCore, QtGui, QtWidgets\n\nclass Ui_Dialog(object):\n\n def setupUi(self, Dialog):\n Dialog.setObjectName('Dialog')\n Dialog.resize(717, 301)\n self.verticalLayout = QtWidgets.QVBoxLayout(Dialog)\n self.verticalLayout.setObjectName('verticalLayout')\n self.label = QtWidgets.QLabel(Dialog)\n self.label.setObjectName('label')\n self.verticalLayout.addWidget(self.label)\n self.listWidget = QtWidgets.QListWidget(Dialog)\n self.listWidget.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)\n self.listWidget.setObjectName('listWidget')\n self.verticalLayout.addWidget(self.listWidget)\n self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)\n self.buttonBox.setOrientation(QtCore.Qt.Horizontal)\n self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Discard | QtWidgets.QDialogButtonBox.SaveAll)\n self.buttonBox.setObjectName('buttonBox')\n self.verticalLayout.addWidget(self.buttonBox)\n self.retranslateUi(Dialog)\n self.buttonBox.accepted.connect(Dialog.accept)\n self.buttonBox.rejected.connect(Dialog.reject)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n\n def retranslateUi(self, Dialog):\n Dialog.setWindowTitle(_('Dialog'))\n self.label.setText(_('The following files have unsaved changes:'))","sub_path":"pycfiles/OpenCobolIDE-4.7.6.tar/dlg_unsaved_files_ui.cpython-35.py","file_name":"dlg_unsaved_files_ui.cpython-35.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"139310562","text":"\n\nimport pygame \nimport random \n\npygame.init() \n\n#screen set up\nscreen_width = 1040\nscreen_height = 680\n\nscreen = pygame.display.set_mode((screen_width,screen_height)) \n\n#player set up\nplayer_image = pygame.image.load(\"mouse.png\")\nplayer_image_height = player_image.get_height()\nplayer_image_width = player_image.get_width()\n\nplayer_image_X = 800 #position of player along X and Y axis \nplayer_image_Y = 50\nplayer_image_up = 0 #variables to be used later fot player movement \nplayer_image_down = 0\nplayer_image_left = 0\nplayer_image_right = 0\n\n#enemy one \nenemy_one = pygame.image.load(\"cat_1.png\")\nenemy_one_height = enemy_one.get_height()\nenemy_one_length = enemy_one.get_width()\n\nenemy_one_X = 100\nenemy_one_Y = -200\n\n#enemy two\nenemy_two = pygame.image.load(\"cat_2.png\")\nenemy_two_height = enemy_two.get_height()\nenemy_two_length = enemy_two.get_width()\n\nenemy_two_X = -200\nenemy_two_Y = 100\n\n#enemy three\nenemy_three = pygame.image.load(\"cat_3.png\")\nenemy_three_height = enemy_three.get_height()\nenemy_three_length = enemy_three.get_width()\n\nenemy_three_X = 500\nenemy_three_Y = 900\n\n# prize set up\nprize_image = pygame.image.load(\"prize.png\")\nprize_height = prize_image.get_height()\nprize_length = prize_image.get_width()\n\nprize_X = 50\nprize_Y = 300\n\n#game loop\nrunning = True\nwhile running:\n\n screen.fill(0) \n screen.blit(player_image, (player_image_X, player_image_Y))\n screen.blit(prize_image, (prize_X, prize_Y))\n screen.blit(enemy_one, (enemy_one_X, enemy_one_Y ))\n screen.blit(enemy_two, (enemy_two_X, enemy_two_Y ))\n screen.blit(enemy_three, (enemy_three_X, enemy_three_Y ))\n \n \n pygame.display.flip()\n \n for event in pygame.event.get(): #creates an event in loop to enable player to Quit \n if event.type == pygame.QUIT:\n pygame.quit()\n exit(0)\n\n if event.type == pygame.KEYDOWN: #creates an event in loop for when directional keystrokes are pressed\n if event.key == pygame.K_UP: #up key\n if player_image_Y > 0: #prevents player from moving off screen\n player_image_up -= 0.9\n\n if event.key == pygame.K_DOWN: #down key\n if player_image_Y < screen_height - player_image_height: #prevents player from moving off screen\n player_image_down += 0.9\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT: #left key\n if player_image_X > 0: #prevents player from moving off screen\n player_image_left -= 0.9\n \n if event.key == pygame.K_RIGHT: #right key\n if player_image_X < screen_width - player_image_height: #prevents player from moving off screen\n player_image_right += 0.9 \n \n\n if event.type == pygame.KEYUP: #creates event in loop for when directional keys are released \n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.key == pygame.K_DOWN: \n player_image_up = 0 #makes sure that player character doesn't move when key is released \n player_image_down = 0\n player_image_left = 0\n player_image_right = 0 \n \n player_image_Y += player_image_up #movement for player character \n player_image_Y += player_image_down \n player_image_X += player_image_left\n player_image_X += player_image_right \n\n playerBox = pygame.Rect(player_image.get_rect()) #creates rectangular borders around each character\n playerBox.top = player_image_Y\n playerBox.left = player_image_X\n\n enemy_one_Box = pygame.Rect(enemy_one.get_rect())\n enemy_one_Box.top = enemy_one_Y\n enemy_one_Box.left = enemy_one_X\n\n enemy_two_Box = pygame.Rect(enemy_two.get_rect())\n enemy_two_Box.top = enemy_two_Y\n enemy_two_Box.left = enemy_two_X\n\n enemy_three_Box = pygame.Rect(enemy_three.get_rect())\n enemy_three_Box.top = enemy_three_Y\n enemy_three_Box.left = enemy_three_X\n\n prize_Box = pygame.Rect(prize_image.get_rect())\n prize_Box.top = prize_Y\n prize_Box.left = prize_X\n\n if playerBox.colliderect(enemy_one_Box): #used rectangualr borders to detect collison\n print(\"You lose!\")\n pygame.quit()\n exit(0)\n \n if playerBox.colliderect(enemy_two_Box):\n print(\"You lose!\")\n pygame.quit()\n exit(0)\n\n if playerBox.colliderect(enemy_three_Box):\n print(\"You lose!\")\n pygame.quit()\n exit(0) \n\n if playerBox.colliderect(prize_Box):\n print(\"You win!\")\n pygame.quit()\n exit(0) \n\n\n enemy_one_Y += 0.8 #enemy character's movement speed \n enemy_two_X += 0.8\n enemy_three_Y -= 0.8\n\n# Resources Used:\n# Example game\n# https://www.youtube.com/watch?v=FfWpgLFMI7w&t=195s","sub_path":"game/my_game.py","file_name":"my_game.py","file_ext":"py","file_size_in_byte":4830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"345552386","text":"# Autor: Victor Manuel Ceron Navarrete\r\n# Descripcion: El código calcula el costo total por mayoreo de un software\r\n\r\n\r\n#Calcula el descuento de acuerdo a las unidades compradas\r\ndef sacarDescuento(unidades, costoSinDescuento):\r\n if unidades >= 10 and unidades <= 19:\r\n descuento = (costoSinDescuento * 0.15)\r\n return descuento\r\n elif unidades >= 20 and unidades <= 29:\r\n descuento = (costoSinDescuento * 0.22)\r\n return descuento\r\n elif unidades >= 30 and unidades <= 99:\r\n descuento = (costoSinDescuento * 0.35)\r\n return descuento\r\n elif unidades >= 100:\r\n descuento = (costoSinDescuento * 0.44)\r\n return descuento\r\n else:\r\n return 0\r\n\r\n\r\n# Función main que lee la cantidad de paquetes e imprime el resultado con descuento y el descuento\r\ndef main():\r\n unidades = int(input(\"Teclee el total de paquetes de software adquiridos: \"))\r\n if unidades <= 0:\r\n print(\"ERROR: No ha comprado softwares\")\r\n else:\r\n costoSinDescuento = 2300 * unidades\r\n descuento = sacarDescuento(unidades , costoSinDescuento)\r\n totalAPagar = (costoSinDescuento - descuento)\r\n print(\"El descuento de su compra es : $%.2f\"% descuento, \"MXN\")\r\n print(\"Su total a pagar es : $%.2f \"% totalAPagar, \"MXN\")\r\n\r\n\r\nmain()","sub_path":"Software.py","file_name":"Software.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"532312824","text":"#!/usr/bin/env python\n#\n# tournament.py -- implementation of a Swiss-system tournament\n#\n\nimport psycopg2\n\n\ndef connect(database_name=\"tournament\"):\n try:\n db = psycopg2.connect(\"dbname={}\".format(database_name))\n cursor = db.cursor()\n return db, cursor\n except:\n print(\"Error: Could not connect to database\")\n\n\ndef deleteMatches():\n \"\"\"Remove all the match records from the database.\"\"\"\n db, c = connect()\n\n query = \"DELETE FROM matches\"\n c.execute(query)\n db.commit()\n db.close()\n\n\ndef deletePlayers():\n \"\"\"Remove all the player records from the database.\"\"\"\n db, c = connect()\n\n query = \"DELETE FROM players\"\n c.execute(query)\n db.commit()\n db.close()\n\n\ndef deleteTournamentPlayers(t_id):\n \"\"\"Remove all the player records from the database.\n\n Args:\n t_id: Tournament ID (unique)\n\n \"\"\"\n db, c = connect()\n\n query = \"DELETE FROM players WHERE tournament = %s\"\n c.execute(query, (t_id,))\n db.commit()\n db.close()\n\n\ndef deleteTournaments():\n \"\"\"Remove all the tournament records from the database.\"\"\"\n db, c = connect()\n\n query = \"DELETE FROM tournaments\"\n c.execute(query)\n db.commit()\n db.close()\n\n\ndef deleteTournament(t_id):\n \"\"\"Remove specific tournament records from the database.\n\n Args:\n t_id: Tournament ID (unique)\n\n \"\"\"\n db, c = connect()\n\n query = \"DELETE FROM tournaments WHERE tournament = %s\"\n c.execute(query, (t_id,))\n db.commit()\n db.close()\n\n\ndef deleteTournamentMatches(t_id):\n \"\"\"Remove all the specific tournament matches records from the database.\n\n Args:\n t_id: Tournament ID (unique)\n\n \"\"\"\n db, c = connect()\n\n query = \"DELETE FROM matches WHERE tournament = %s\"\n c.execute(query, (t_id,))\n db.commit()\n db.close()\n\n\ndef countPlayers():\n \"\"\"Returns the number of players currently registered.\"\"\"\n db, c = connect()\n\n query = \"SELECT COUNT(*) AS num FROM players\"\n c.execute(query)\n count = c.fetchone()[0]\n db.close()\n\n return count\n\n\ndef countTournamentPlayers(t_id):\n \"\"\"Returns the number of players currently registered in a specific\n tournament from player_standings table.\n\n Args:\n t_id: tournament id (unique)\n\n \"\"\"\n db, c = connect()\n\n query = \"\"\"SELECT COUNT(*) AS num FROM player_standings\n WHERE tournament = %s\"\"\"\n c.execute(query, (t_id,))\n count = c.fetchone()[0]\n db.close()\n\n return count\n\n\ndef registerPlayer(name, t_id):\n \"\"\"Adds a player to the tournament database to a specific tournament.\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 t_id: tournament id (unique).\n \"\"\"\n db, c = connect()\n\n query_player = \"INSERT INTO players (name, tournament, byes) VALUES(%s, %s, %s)\"\n c.execute(query_player, (name, t_id, 0))\n\n db.commit()\n db.close()\n\n\ndef getTournamentPlayers(t_id):\n \"\"\" Get all players from a tournament, sorted by id.\n\n Args:\n t_id: tournament id (unique)\n \"\"\"\n\n db, c = connect()\n query = \"SELECT * FROM players WHERE tournament = %s\"\n c.execute(query, (t_id,))\n players = c.fetchall()\n db.close()\n\n return players\n\n\ndef registerTournament(name):\n \"\"\"Adds a tournament to the tournament database.\n\n The database assigns a unique serial id number for the tournament. (This\n should be handled by your SQL database schema, not in your Python code.)\n\n Args:\n name: the tournament's name (need not be unique).\n\n Returns:\n id: tournament id (unique) for use in other functions\n \"\"\"\n db, c = connect()\n\n query = \"INSERT INTO tournaments (name) VALUES(%s) RETURNING id\"\n c.execute(query, (name,))\n id = c.fetchone()[0]\n\n db.commit()\n db.close()\n\n return id\n\n\ndef playerStandings(t_id):\n \"\"\"Returns a list of the players and their total wins, sorted by wins, in\n a specific tournament.\n\n The first entry in the list should be the player in first place, or a player\n tied for first place if there is currently a tie.\n\n Args:\n t_id: tournament id (unique).\n\n Returns:\n A list of tuples, each of which contains\n (id, name, wins, ties, matches, omw, byes):\n id: the player's unique id (assigned by the database)\n name: the player's full name (as registered)\n wins: total wins\n ties: total ties\n matches: the number of matches the player has played\n omw: total points of opponents a player has faced\n byes: the number of skips rounds player has in case of uneven players\n \"\"\"\n db, c = connect()\n\n query = \"\"\"SELECT player, name, wins, ties, matches, omw, byes\n FROM player_standings WHERE tournament = %s\"\"\"\n c.execute(query, (t_id,))\n players = c.fetchall()\n db.close()\n\n return players\n\n\ndef reportMatch(t_id, winner, loser, draw=False):\n \"\"\"Records the outcome of a single match between two players. Updates\n Player Standings.\n\n Args:\n t_id: the tournament id\n winner: the id number of the player who won\n loser: the id number of the player who lost\n draw: boolean of if match was a tie. Changes points allotted in match\n \"\"\"\n\n db, c = connect()\n\n query_match = \"\"\"INSERT INTO matches (tournament, winner, loser, draw)\n VALUES (%s, %s, %s, %s)\"\"\"\n c.execute(query_match, (t_id, winner, loser, draw))\n\n db.commit()\n db.close()\n\n\ndef checkForEvenPlayers(players, t_id):\n \"\"\"Returns an even number of players, assigning a bye to one of the players,\n if there was an odd number of players to begin with\n\n Args:\n players: a list of tuples containing (id, name) of the player\n t_id: tournament id\n\n Returns:\n A even list of tuples containing (id, name) of the player, excluding\n the player assigned the bye if the initial list length was an odd\n \"\"\"\n\n if len(players) % 2 != 0:\n db, c = connect()\n\n # Get player standings and select 1st place player without a bye (id)\n query = \"\"\"SELECT player FROM player_standings WHERE byes = 0 LIMIT 1\"\"\"\n c.execute(query)\n id = c.fetchone()[0]\n\n # Update player with (id) to have a bye in players table\n query_bye = \"UPDATE players SET byes=1 WHERE id = %s\"\n c.execute(query_bye, (id,))\n\n # Get List of players excluding player with (id)\n query_players = \"\"\"SELECT ps.player, p.name\n FROM player_standings AS ps, players AS p\n WHERE ps.player != %s AND ps.player = p.id\n AND ps.tournament = %s\"\"\"\n c.execute(query_players, (id, t_id))\n players_modified = c.fetchall()\n\n db.commit()\n db.close()\n\n # Return modified players list of tuples (id, name)\n return players_modified\n else:\n return players\n\n\ndef swissPairings(t_id):\n \"\"\"Returns a list of pairs of players for the next round of a match in a\n specific tournament.\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 adjacent\n to him or her in the standings.\n\n Args:\n t_id: the tournament id\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 db, c = connect()\n\n query = \"\"\"SELECT ps.player, p.name\n FROM player_standings AS ps, players AS p\n WHERE ps.player = p.id AND ps.tournament = %s\n ORDER BY ps.wins DESC, ps.ties DESC\"\"\"\n c.execute(query, (t_id,))\n players = c.fetchall()\n\n players = checkForEvenPlayers(players, t_id)\n\n pairings = []\n for i in range(0, len(players), 2):\n # Append a tuple (player1 id, player1 name, player2 id, player2 name)\n pairings.append(\n (players[i][0], players[i][1], players[i+1][0], players[i+1][1],)\n )\n\n db.close()\n\n return pairings\n","sub_path":"vagrant/tournament/tournament.py","file_name":"tournament.py","file_ext":"py","file_size_in_byte":8422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"274999025","text":"import time\r\nimport cv2\r\nimport numpy as np\r\nimport os; os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\";\r\nimport tensorflow as tf\r\nfrom tensorflow.keras.layers import (\r\n Add,\r\n Concatenate,\r\n Conv2D,\r\n Input,\r\n Lambda,\r\n LeakyReLU,\r\n MaxPool2D,\r\n UpSampling2D,\r\n ZeroPadding2D,\r\n)\r\nfrom tensorflow.keras.regularizers import l2\r\nfrom tensorflow.keras.losses import (\r\n binary_crossentropy,\r\n sparse_categorical_crossentropy\r\n)\r\nfrom tensorflow.keras import Model\r\nfrom tqdm import tqdm\r\n\r\nclasses = './data/classes.names'\r\nweights = './saved_models/yolov3_ts30.tf'\r\nsize = 416\r\nimage = './test_data/test4.jpg'\r\noutput = './test_data/output4.jpg'\r\nnum_classes = 12\r\nvideo = False\r\nvideo_path = \"./test_data/test.mp4\"\r\noutput_video = \"./test_data/test_out.avi\"\r\nyolo_iou_threshold = 0.22\r\nyolo_score_threshold = 0.22\r\nyolo_max_boxes = 500\r\nyolo_anchors = np.array([(10, 13), (16, 30), (33, 23), (30, 61), (62, 45),\r\n (59, 119), (116, 90), (156, 198), (373, 326)],\r\n np.float32) / size\r\nyolo_anchor_masks = np.array([[6, 7, 8], [3, 4, 5], [0, 1, 2]])\r\n\r\nclass BatchNormalization(tf.keras.layers.BatchNormalization):\r\n def call(self, x, training=False):\r\n if training is None:\r\n training = tf.constant(False)\r\n training = tf.logical_and(training, self.trainable)\r\n return super().call(x, training)\r\n\r\ndef transform_images(x_train, size):\r\n x_train = tf.image.resize(x_train, (size, size))\r\n x_train = x_train / 255.0\r\n return x_train\r\n\r\ndef draw_outputs(img, outputs, class_names):\r\n boxes, objectness, classes, nums = outputs\r\n boxes, objectness, classes, nums = boxes[0], objectness[0], classes[0], nums[0]\r\n wh = np.flip(img.shape[0:2])\r\n for i in range(nums):\r\n x1y1 = tuple((np.array(boxes[i][0:2]) * wh).astype(np.int32))\r\n x2y2 = tuple((np.array(boxes[i][2:4]) * wh).astype(np.int32))\r\n img = cv2.rectangle(img, x1y1, x2y2, (255, 0, 0), 2)\r\n img = cv2.putText(img, '{} {:.4f}'.format(\r\n class_names[int(classes[i])], objectness[i]),\r\n x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 2)\r\n return img\r\n\r\ndef DarknetConv(x, filters, size, strides=1, batch_norm=True):\r\n if strides == 1:\r\n padding = 'same'\r\n else:\r\n x = ZeroPadding2D(((1, 0), (1, 0)))(x) # top left half-padding\r\n padding = 'valid'\r\n x = Conv2D(filters=filters, kernel_size=size,\r\n strides=strides, padding=padding,\r\n use_bias=not batch_norm, kernel_regularizer=l2(0.0005))(x)\r\n if batch_norm:\r\n x = BatchNormalization()(x)\r\n x = LeakyReLU(alpha=0.1)(x)\r\n return x\r\n\r\ndef DarknetResidual(x, filters):\r\n prev = x\r\n x = DarknetConv(x, filters // 2, 1)\r\n x = DarknetConv(x, filters, 3)\r\n x = Add()([prev, x])\r\n return x\r\n\r\ndef DarknetBlock(x, filters, blocks):\r\n x = DarknetConv(x, filters, 3, strides=2)\r\n for _ in range(blocks):\r\n x = DarknetResidual(x, filters)\r\n return x\r\n\r\ndef Darknet(name=None):\r\n x = inputs = Input([None, None, 3])\r\n x = DarknetConv(x, 32, 3)\r\n x = DarknetBlock(x, 64, 1)\r\n x = DarknetBlock(x, 128, 2) # skip connection\r\n x = x_36 = DarknetBlock(x, 256, 8) # skip connection\r\n x = x_61 = DarknetBlock(x, 512, 8)\r\n x = DarknetBlock(x, 1024, 4)\r\n return tf.keras.Model(inputs, (x_36, x_61, x), name=name)\r\n\r\ndef DarknetConv(x, filters, size, strides=1, batch_norm=True):\r\n if strides == 1:\r\n padding = 'same'\r\n else:\r\n x = ZeroPadding2D(((1, 0), (1, 0)))(x) # top left half-padding\r\n padding = 'valid'\r\n x = Conv2D(filters=filters, kernel_size=size,\r\n strides=strides, padding=padding,\r\n use_bias=not batch_norm, kernel_regularizer=l2(0.0005))(x)\r\n if batch_norm:\r\n x = BatchNormalization()(x)\r\n x = LeakyReLU(alpha=0.1)(x)\r\n return x\r\n\r\ndef YoloConv(filters, name=None):\r\n def yolo_conv(x_in):\r\n if isinstance(x_in, tuple):\r\n inputs = Input(x_in[0].shape[1:]), Input(x_in[1].shape[1:])\r\n x, x_skip = inputs\r\n # concat with skip connection\r\n x = DarknetConv(x, filters, 1)\r\n x = UpSampling2D(2)(x)\r\n x = Concatenate()([x, x_skip])\r\n else:\r\n x = inputs = Input(x_in.shape[1:])\r\n x = DarknetConv(x, filters, 1)\r\n x = DarknetConv(x, filters * 2, 3)\r\n x = DarknetConv(x, filters, 1)\r\n x = DarknetConv(x, filters * 2, 3)\r\n x = DarknetConv(x, filters, 1)\r\n return Model(inputs, x, name=name)(x_in)\r\n return yolo_conv\r\n\r\ndef YoloOutput(filters, anchors, classes, name=None):\r\n def yolo_output(x_in):\r\n x = inputs = Input(x_in.shape[1:])\r\n x = DarknetConv(x, filters * 2, 3)\r\n x = DarknetConv(x, anchors * (classes + 5), 1, batch_norm=False)\r\n x = Lambda(lambda x: tf.reshape(x, (-1, tf.shape(x)[1], tf.shape(x)[2],\r\n anchors, classes + 5)))(x)\r\n return tf.keras.Model(inputs, x, name=name)(x_in)\r\n return yolo_output\r\n\r\ndef yolo_boxes(pred, anchors, classes):\r\n # pred: (batch_size, grid, grid, anchors, (x, y, w, h, obj, ...classes))\r\n grid_size = tf.shape(pred)[1]\r\n box_xy, box_wh, objectness, class_probs = tf.split(\r\n pred, (2, 2, 1, classes), axis=-1)\r\n box_xy = tf.sigmoid(box_xy)\r\n objectness = tf.sigmoid(objectness)\r\n class_probs = tf.sigmoid(class_probs)\r\n pred_box = tf.concat((box_xy, box_wh), axis=-1) # original xywh for loss\r\n # !!! grid[x][y] == (y, x)\r\n grid = tf.meshgrid(tf.range(grid_size), tf.range(grid_size))\r\n grid = tf.expand_dims(tf.stack(grid, axis=-1), axis=2) # [gx, gy, 1, 2]\r\n box_xy = (box_xy + tf.cast(grid, tf.float32)) / \\\r\n tf.cast(grid_size, tf.float32)\r\n box_wh = tf.exp(box_wh) * anchors\r\n box_x1y1 = box_xy - box_wh / 2\r\n box_x2y2 = box_xy + box_wh / 2\r\n bbox = tf.concat([box_x1y1, box_x2y2], axis=-1)\r\n return bbox, objectness, class_probs, pred_box\r\n\r\ndef yolo_nms(outputs, anchors, masks, classes):\r\n # boxes, conf, type\r\n b, c, t = [], [], []\r\n for o in outputs:\r\n b.append(tf.reshape(o[0], (tf.shape(o[0])[0], -1, tf.shape(o[0])[-1])))\r\n c.append(tf.reshape(o[1], (tf.shape(o[1])[0], -1, tf.shape(o[1])[-1])))\r\n t.append(tf.reshape(o[2], (tf.shape(o[2])[0], -1, tf.shape(o[2])[-1])))\r\n bbox = tf.concat(b, axis=1)\r\n confidence = tf.concat(c, axis=1)\r\n class_probs = tf.concat(t, axis=1)\r\n scores = confidence * class_probs\r\n boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression(\r\n boxes=tf.reshape(bbox, (tf.shape(bbox)[0], -1, 1, 4)),\r\n scores=tf.reshape(\r\n scores, (tf.shape(scores)[0], -1, tf.shape(scores)[-1])),\r\n max_output_size_per_class=yolo_max_boxes,\r\n max_total_size=yolo_max_boxes,\r\n iou_threshold=yolo_iou_threshold,\r\n score_threshold=yolo_score_threshold\r\n )\r\n return boxes, scores, classes, valid_detections\r\n\r\n\r\ndef YoloV3(size=None, channels=3, anchors=yolo_anchors,\r\n masks=yolo_anchor_masks, classes=80, training=False):\r\n x = inputs = Input([size, size, channels], name = 'input')\r\n x_36, x_61, x = Darknet(name='yolo_darknet')(x)\r\n x = YoloConv(512, name='yolo_conv_0')(x)\r\n output_0 = YoloOutput(512, len(masks[0]), classes, name='yolo_output_0')(x)\r\n x = YoloConv(256, name='yolo_conv_1')((x, x_61))\r\n output_1 = YoloOutput(256, len(masks[1]), classes, name='yolo_output_1')(x)\r\n x = YoloConv(128, name='yolo_conv_2')((x, x_36))\r\n output_2 = YoloOutput(128, len(masks[2]), classes, name='yolo_output_2')(x)\r\n if training:\r\n return Model(inputs, (output_0, output_1, output_2), name='yolov3')\r\n boxes_0 = Lambda(lambda x: yolo_boxes(x, anchors[masks[0]], classes),\r\n name='yolo_boxes_0')(output_0)\r\n boxes_1 = Lambda(lambda x: yolo_boxes(x, anchors[masks[1]], classes),\r\n name='yolo_boxes_1')(output_1)\r\n boxes_2 = Lambda(lambda x: yolo_boxes(x, anchors[masks[2]], classes),\r\n name='yolo_boxes_2')(output_2)\r\n outputs = Lambda(lambda x: yolo_nms(x, anchors, masks, classes),\r\n name='yolo_nms')((boxes_0[:3], boxes_1[:3], boxes_2[:3]))\r\n return Model(inputs, outputs, name='yolov3')\r\n\r\ndef main():\r\n global classes\r\n physical_devices = tf.config.experimental.list_physical_devices('GPU')\r\n if len(physical_devices) > 0:\r\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\r\n yolo = YoloV3(classes=num_classes)\r\n yolo.load_weights(weights).expect_partial()\r\n print('weights loaded')\r\n class_names = [c.strip() for c in open(classes).readlines()]\r\n print('classes loaded')\r\n if video==False:\r\n img_raw = tf.image.decode_image(open(image, 'rb').read(), channels=3)\r\n img = tf.expand_dims(img_raw, 0)\r\n img = transform_images(img, size)\r\n t1 = time.time()\r\n boxes, scores, classes, nums = yolo(img)\r\n t2 = time.time()\r\n print('Inference time: {}'.format(t2 - t1))\r\n print(\"Detections are : \") \r\n for i in range(nums[0]):\r\n print('\\t{}, {}, {}'.format(class_names[int(classes[0][i])],\r\n np.array(scores[0][i]),\r\n np.array(boxes[0][i])))\r\n img = cv2.cvtColor(img_raw.numpy(), cv2.COLOR_RGB2BGR)\r\n img = draw_outputs(img, (boxes, scores, classes, nums), class_names)\r\n cv2.imwrite(output, img)\r\n cv2.imshow('output', img)\r\n cv2.waitKey(0)\r\n print('output saved to: {}'.format(output))\r\n elif video==True:\r\n times = []\r\n try:\r\n vid = cv2.VideoCapture(int(video_path))\r\n except:\r\n vid = cv2.VideoCapture(video_path)\r\n width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))\r\n height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))\r\n fps = int(vid.get(cv2.CAP_PROP_FPS))\r\n codec = cv2.VideoWriter_fourcc(*'XVID')\r\n out = cv2.VideoWriter(output_video, codec, fps//2, (width, height))\r\n length = int(vid.get(cv2.CAP_PROP_FRAME_COUNT))\r\n for i in tqdm(range(length)):\r\n _, img = vid.read()\r\n if img is None:\r\n print(\"Empty Frame\")\r\n time.sleep(0.1)\r\n break\r\n img_in = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) \r\n img_in = tf.expand_dims(img_in, 0)\r\n img_in = transform_images(img_in, size)\r\n t1 = time.time()\r\n boxes, scores, classes, nums = yolo.predict(img_in)\r\n t2 = time.time()\r\n times.append(t2-t1)\r\n times = times[-20:]\r\n img = draw_outputs(img, (boxes, scores, classes, nums), class_names)\r\n img = cv2.putText(img, \"Time: {:.2f}ms\".format(sum(times)/len(times)*1000), (0, 30),\r\n cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255, 0, 0), 2)\r\n if output_video:\r\n out.write(img)\r\n cv2.imshow('output', img)\r\n if cv2.waitKey(1) == ord('q'):\r\n break\r\n cv2.destroyAllWindows()\r\n else:\r\n print(\"Invalid Settings!! check the paths!\")\r\n\r\nif __name__ == '__main__':\r\n try:\r\n main()\r\n tf.keras.backend.clear_session()\r\n except SystemExit:\r\n pass\r\n\r\n\r\n","sub_path":"06 - Traffic-Signs-Detection/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":11486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"597806253","text":"# coding:utf-8 \n'''\ncreated on 2018/10/22\n\n@author:sunyihuan\n'''\n\nfrom PIL import Image\nimport numpy as np\nimport os\n\n\nclass ahash(object):\n\n # 计算hash值\n def getHashCode(self, img, size=(64, 64)):\n pixel = []\n for i in range(size[0]):\n for j in range(size[1]):\n pixel.append(img[i][j])\n\n mean = sum(pixel) / len(pixel)\n\n result = []\n for i in pixel:\n if i > mean:\n result.append(1)\n else:\n result.append(0)\n\n return result\n","sub_path":"picture_search/hash_method/ahash.py","file_name":"ahash.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"631426952","text":"# -*- coding: utf-8 -*-\n\n\nimport numpy as np\n\n# definimos as matrices necesarias\nU=np.array([[1,2,-1],[2,4,5],[3,-1,-2]],float)\nF,C=np.shape(U)\nL=np.zeros((F,C))\nP=np.identity(F) # para un caso máis xeral poderiamos usar eye\nb=np.array([[2],[25],[-5]],float) # definimos a columna de termos independentes\n\n# inicializamos un vector onde almacenaremos as posicións dos pivotes\npivote=np.arange(C)\n\n\nfor j in range(C-1): # facemos o pivoteo nas matrices U, L e P (bucle j) e eliminación (bucle i)\n\t\n\tpivote[j]=np.argmax(np.fabs(U[:,j])) # pivoteo en U\n\tauxU=U[pivote[j],:].copy()\n\tU[pivote[j],:]=U[j,:]\n\tU[j,:]=auxU\n\n\tauxL=L[pivote[j],:].copy() # pivoteo en L\n\tL[pivote[j],:]=L[j,:]\n\tL[j,:]=auxL\n\n\tauxP=P[pivote[j],:].copy() # pivoteo en P\n\tP[pivote[j],:]=P[j,:]\n\tP[j,:]=auxP\n\n\n\tfor i in range(j+1,F):\n\t\tL[i,j]=U[i,j]/U[j,j]\n\t\tU[i,:]=U[i,:]-L[i,j]*U[j,:]\n\nfor i in range(F): # engadimos 1 na diagonal ppal de L (52)\n\tL[i,i]+=1\n\nPb=np.dot(P,b) # calculamos o produto P*b (53)\n\nsoly=np.zeros((F,1),float) # designo unha columna de solucións para y\n\nfor i in range(F): # resolvemos soly por substitucion progresiva (54)\n\tsuma=0\n\tfor j in range(i):\n\t\tsuma+=L[i,j]*soly[j,0]\n\tsoly[i,0]=(Pb[i,0]-suma)/L[i,i]\n\n\nsolx=np.zeros((F,1),float) # designo unha columna de solucións para x e soluciono o sistema por substitución regresiva (56)\nfor i in range(F-1,-1,-1): \n\tsuma=0\n\tfor j in range(F):\n\t\tsuma+=U[i,j]*solx[j,0]\n\tsolx[i,0]=(soly[i,0]-suma)/U[i,i]\n\n#output\nprint()\nprint('Método factorización LU con pivoteo parcial\\n')\nprint('Matriz triangular inferior L:')\nprint(L, '\\n')\nprint('Matriz triangular superior U:')\nprint(U, '\\n')\nprint('Matriz de permutación P:')\nprint(P, '\\n')\nprint('Solución por factorización LU:')\nfor i in range(len(solx)):\n\tprint('x(%i)= %.6f' % (i+1,solx[i]))","sub_path":"bol2/bol2_ex6_optativo(entregado).py","file_name":"bol2_ex6_optativo(entregado).py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"561805429","text":"from flask import render_template\nimport json\nimport random\nfrom app import app, db, bcrypt\nfrom app.models import User, Note, Tag, Collection\nfrom app.render import md_to_html, html_to_md, html_to_md_simple\n\n\ndef query_multiple(tag=None, collection=None):\n \"\"\"Query via multiple options\"\"\"\n\n if tag is not None and collection is not None:\n notes = Note.query.filter(Note.collection.has(Collection.id == collection)).filter(Note.tag.any(Tag.id == tag))\n elif collection is not None:\n notes = Note.query.filter(Note.collection.has(Collection.id == collection))\n elif tag is not None:\n notes = Note.query.filter(Note.tag.any(Tag.id == tag))\n else:\n notes = Note.query.all()\n return notes\n\n# ------------------------------------------------------------\n# Tags\n# ------------------------------------------------------------\n\ndef add_tags(tag):\n \"\"\"add tags to database\"\"\"\n\n tag = Tag(title=tag)\n db.session.add(tag)\n db.session.commit()\n\ndef query_tags(tag):\n \"\"\"Query tags\"\"\"\n\n result = Tag.query.filter_by(title=tag).first()\n return result\n\ndef query_and_add_tags(tag_list):\n \"\"\"Query list of tags. Add tags that are not found\"\"\"\n\n tag_results = [] \n for tag in tag_list:\n result = Tag.query.filter_by(title=tag).first()\n if result == None:\n add_tags(tag)\n result = Tag.query.filter_by(title=tag).first()\n tag_results.append(result)\n return tag_results\n\n# ------------------------------------------------------------\n# Collection\n# ------------------------------------------------------------\n\ndef add_collection(collection):\n \"\"\"Add collection to database\"\"\"\n\n collection = Collection(title=collection)\n db.session.add(collection)\n db.session.commit()\n\ndef query_collection(col_name):\n \"\"\"Query Collection\"\"\"\n\n collection = Collection.query.filter_by(title=col_name).first()\n return collection\n\ndef query_and_add_collection(col_name):\n \"\"\"Query collection. Add collection to database if not found\"\"\"\n\n collection = Collection.query.filter_by(title=col_name).first()\n if collection == None:\n add_collection(col_name)\n collection = Collection.query.filter_by(title=col_name).first()\n return collection\n\n# ------------------------------------------------------------\n# Database\n# ------------------------------------------------------------\ndef return_render(note):\n \"\"\"return render template based on note type\"\"\"\n\n try:\n markers = json.loads(note.markers)\n except:\n markers = ''\n if note.note_type == 'video':\n if 'youtube' in note.source:\n rtemplate = render_template('video.html', note = note, youtube_url = note.source, timestamp = markers)\n else:\n rtemplate = render_template('video.html', note = note, local_video = note.source, timestamp = markers)\n elif note.note_type == 'audio':\n rtemplate = render_template('audio.html', note = note, youtube_url = note.source, timestamp = markers)\n elif note.note_type == 'snippet':\n rtemplate = render_template('note.html', title = note.title, note = note)\n elif note.note_type == 'article':\n rtemplate = render_template('article.html', title = note.title, note=note)\n else:\n rtemplate = render_template('note.html', title = note.title, note = note)\n return rtemplate\n\ndef update_db(note_id, data):\n \"\"\"Updates a note after save\"\"\"\n\n note = Note.query.get_or_404(note_id)\n note.title = data['title']\n note.source = data['source']\n collection = data['collection']\n collection = query_and_add_collection(collection)\n note.collection = collection\n tags = data['tags']\n tags = tags.strip(',').split(',')\n tags = query_and_add_tags(tags)\n note.tag = tags\n note.note_type = data['note_type']\n note.content = data['content']\n note.position = data['position']\n if data['render'] == True:\n note.content = html_to_md_simple(note.content)\n try:\n note.markers = data['markers']\n except:\n note.markers = ''\n # print('before pickle', note.markers)\n note.markers = json.dumps(note.markers)\n # print(\"after pickle\", note.markers)\n # db.session.add(note)\n db.session.commit()\n\ndef random_data(notes):\n \"\"\"Generates a random note from query\"\"\"\n\n weighted = []\n for note in notes:\n weighted.append(note.weight) \n weighted = sum(weighted)\n random_number = random.uniform(0, weighted)\n for note in notes:\n random_number -= note.weight\n if random_number <= 0:\n return note\n\n# ------------------------------------------------------------\n# Inactive\n# ------------------------------------------------------------\n\n# def weightedsample(note):\n# for number in range(10):\n# randomize()\n# result = weightedsample(random_number)\n# print(result)\n# modifying(result)\n \n# def modifying(result):\n# value = input(\"Enter modifier\\n\")\n# items[result] = items[result] * modifiers[value]\n# print(\"final item value is: \" + str(items[result]))\n# if items[result] <= 1:\n# items[result] = 1\n# return items[result]\n\n\n","sub_path":"app/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":5199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"142684189","text":"import os\n\nMODULE_ROOT = os.path.dirname(os.path.realpath(__file__))\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': ':memory:'\n }\n}\nUSE_TZ = True,\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',\n }\n}\n\nTEMPLATE_DIRS = (os.path.join(MODULE_ROOT, 'templates'),)\n\nINSTALLED_APPS = (\n # django modules\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"django.contrib.sessions\",\n # third parties\n \"djbetty\",\n \"djes\",\n \"rest_framework\",\n \"polymorphic\",\n # local apps\n \"bulbs.api\",\n \"bulbs.campaigns\",\n \"bulbs.feeds\",\n \"bulbs.redirects\",\n \"bulbs.cms_notifications\",\n \"bulbs.content\",\n \"bulbs.contributions\",\n \"bulbs.promotion\",\n \"bulbs.special_coverage\",\n \"bulbs.sections\",\n # local testing apps\n \"example.testcontent\",\n)\n\nROOT_URLCONF = \"example.urls\"\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.core.context_processors.tz\",\n \"django.contrib.messages.context_processors.messages\",\n \"django.core.context_processors.request\"\n)\n\nMIDDLEWARE_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 'bulbs.promotion.middleware.PromotionMiddleware'\n)\n\nCELERY_ALWAYS_EAGER = True\n\nCELERY_EAGER_PROPAGATES_EXCEPTIONS = True\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.SessionAuthentication',\n )\n}\n\nSECRET_KEY = \"no-op\"\n\nES_DISABLED = False\n\nES_URLS = ['http://localhost:9200']\nES_INDEX = \"django-bulbs\"\n\nES_INDEX_SETTINGS = {\n \"django-bulbs\": {\n \"index\": {\n \"analysis\": {\n \"filter\": {\n \"autocomplete_filter\": {\n \"type\": \"edge_ngram\",\n \"min_gram\": 1,\n \"max_gram\": 20\n }\n },\n \"analyzer\": {\n \"autocomplete\": {\n \"type\": \"custom\",\n \"tokenizer\": \"standard\",\n \"filter\": [\n \"lowercase\",\n \"autocomplete_filter\"\n ]\n }\n }\n }\n }\n }\n}\n","sub_path":"example/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"102387196","text":"\"\"\"\n\\\\v - value\n\\\\n - new line\n\\\\bU - level up\n\\\\bD - level down\n\"\"\"\ndef insertValues(rule, value1, value2 = ''):\n\tresult = ''\n\tn = 0\n\tfor c in rule:\n\t\tif c == '\\v':\n\t\t\tif n == 0:\n\t\t\t\tresult += value1\n\t\t\telif n == 1:\n\t\t\t\tresult += value2\n\t\t\tn += 1\n\t\telse:\n\t\t\tresult += c\n\treturn result\n\ndef applyStyle(lexems, pos, style):\n\tvalue, cmd = lexems[pos]\n\tif pos < len(lexems) - 1:\n\t\tnextValue, nextCmd = lexems[pos + 1]\n\t\t# Пара имеет приоритет выше, чем одиночное правило\n\t\tpairKey = cmd + '+' + nextCmd\n\t\trule = style['cvt'].get(pairKey)\n\t\tif rule:\n\t\t\treturn insertValues(rule, value, nextValue), 2\n\trule = style['cvt'].get(cmd)\n\tif rule:\n\t\treturn insertValues(rule, value), 1\n\treturn value, 1\n\ndef formatLexems(outRows, lexems, pos, level, style):\n\tdef createLine():\n\t\toutRows.append('')\n\tdef outChar(c):\n\t\tif len(outRows[-1]) == 0:\n\t\t\tindent = '\\t' * level if style['useTabs'] else ' ' * (level * style['tabSize'])\n\t\t\toutRows[-1] += indent\n\t\toutRows[-1] += c\n\tcreateLine()\n\twhile pos < len(lexems):\n\t\tvalue, deltaPos = applyStyle(lexems, pos, style)\n\t\tpos += deltaPos\n\t\tisCmd = False\n\t\tfor c in value:\n\t\t\tif isCmd:\n\t\t\t\tif c == 'U':\n\t\t\t\t\tlevel += 1\n\t\t\t\telif c == 'D':\n\t\t\t\t\tlevel -= 1\n\t\t\t\tisCmd = False\n\t\t\telif c == '\\n':\n\t\t\t\tcreateLine()\n\t\t\telif c == '\\b':\n\t\t\t\tisCmd = True\n\t\t\telse:\n\t\t\t\toutChar(c)\n","sub_path":"src3/out/formatter.py","file_name":"formatter.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"318595481","text":"from django import forms\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom suggestions.forms import InstanceCreateSuggestionForm\nfrom .models import ICON_CHOICES, Tidbit, Feedback\n\n\nclass SearchForm(forms.Form):\n q = forms.CharField()\n\n\nclass TidbitSuggestionForm(InstanceCreateSuggestionForm):\n title = forms.CharField(label=_('Title'), max_length=40,\n initial=_('Did you know ?'))\n icon = forms.ChoiceField(label=_('Icon'), choices=ICON_CHOICES)\n content = forms.CharField(label=_('Content'),\n widget=forms.Textarea(attrs={'rows': 3}))\n button_text = forms.CharField(label=_('Button text'), max_length=100)\n button_link = forms.CharField(label=_('Button link'), max_length=255)\n\n class Meta:\n model = Tidbit\n caption = _('Suggest Tidbit')\n\n def get_data(self, request):\n \"Add suggested_by for the tidbit to the action data\"\n\n data = super(TidbitSuggestionForm, self).get_data(request)\n data['suggested_by'] = request.user\n\n return data\n\n\nclass FeedbackSuggestionForm(InstanceCreateSuggestionForm):\n content = forms.CharField(label=_('Content'),\n widget=forms.Textarea(attrs={'rows': 7, 'cols': 120}),\n help_text=mark_safe(_(\n 'Content of your suggestion will be available to the public.
If you want to send us sensitive information please send it via email:
mail@oknesset.org')))\n url = forms.CharField(widget=forms.HiddenInput, max_length=400)\n\n class Meta:\n model = Feedback\n caption = _('Send Feedback')\n\n def __init__(self, *args, **kwargs):\n super(FeedbackSuggestionForm, self).__init__(*args, **kwargs)\n self.helper.form_action = 'feedback-post'\n\n def get_data(self, request):\n \"Add suggested_by for the tidbit to the action data\"\n\n data = super(FeedbackSuggestionForm, self).get_data(request)\n\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n\n data.update({\n 'suggested_by': request.user,\n 'ip_address': ip,\n 'user_agent': request.META.get('HTTP_USER_AGENT'),\n })\n\n return data\n","sub_path":"auxiliary/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"105565471","text":"N = int(input())\n#all_numは0~9の数字から成るNの数列の全部の個数\nall_num = 10**N\n#not_9は9が数列のどこにもいない数列の個数\n#よって、(-not_9)は9が数列のどこかにいる数列の個数\nnot_9 = 9**N\n#not_0は0が数列のどこにもいない数列の個数\n#よって、(-not_0)は9が数列のどこかにいる数列の個数\nnot_0 = 9**N\n#(-not_9) ∩ (-not_0) = 0と9が両方ともどこかにいる数列\n#よって、積集合をひかないといけない\n#not_0_9は 0と9が両方ともどこにもいない数列\nnot_0_9 = 8**N\nprint((all_num-(not_9+not_0)+not_0_9) % (10**9+7))","sub_path":"Python_codes/p02554/s659389749.py","file_name":"s659389749.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"242273309","text":"# -*- coding: utf-8 -*-\r\nimport json\r\nfrom pprint import pprint\r\nfrom lxml import etree\r\nfrom lxml.etree import XMLSyntaxError\r\n\r\nfrom flask import Flask, render_template, request\r\nfrom jinja2 import Environment, meta, TemplateSyntaxError, StrictUndefined, UndefinedError\r\n\r\n# For dynamic loading of filters\r\nimport imp\r\nfrom inspect import getmembers, isfunction\r\nimport os\r\n\r\napp = Flask(__name__)\r\n\r\n# Load filters in filters dir\r\nfilter_path = 'filters'\r\nfilter_files = []\r\nadded_filters = {}\r\n\r\n# Find py files and turn then into filterpath/blah/filter.py\r\nfor e in os.walk(filter_path, followlinks=True):\r\n for f in e[2]:\r\n if f.endswith('py'):\r\n print(\"Adding %s\" % os.path.join(e[0], f))\r\n filter_files.append(os.path.join(e[0], f))\r\n\r\nfor filter in filter_files:\r\n mod_name, file_ext = os.path.splitext(os.path.split(filter)[-1])\r\n py_mod = imp.load_source(mod_name, filter)\r\n for name, function in getmembers(py_mod):\r\n if isfunction(function) and not name.startswith('_'):\r\n # Saving filter info to put it in HTML at some point\r\n added_filters[name] = function.__doc__\r\n # add filter to jinja\r\n app.jinja_env.filters[name] = function\r\n\r\n\r\n# These are the added filters. must add these name + doc strings to the html\r\n# Also do this for built-in jinja filters\r\n# for f in sorted(added_filters):\r\n# print(\"%s: %s\" % (f, added_filters[f]))\r\n\r\n@app.route(\"/\")\r\ndef hello():\r\n return render_template('index.html',\r\n all_filters=app.jinja_env.filters\r\n )\r\n\r\n\r\n@app.route('/convert', methods=['GET', 'POST'])\r\ndef convert():\r\n # Verify that macros section compiles\r\n try:\r\n if int(request.form['strictformat']):\r\n app.jinja_env.undefined = StrictUndefined\r\n # tpl = app.jinja_env.from_string(request.form['template'])\r\n tpl = app.jinja_env.from_string(request.form['macros'])\r\n except TemplateSyntaxError as err:\r\n response = {'macros-error': \"ERROR: \" + err.message}\r\n return json.dumps(response)\r\n # Verify that macros plus template compile correctly\r\n try:\r\n if int(request.form['strictformat']):\r\n app.jinja_env.undefined = StrictUndefined\r\n # tpl = app.jinja_env.from_string(request.form['template'])\r\n tpl = app.jinja_env.from_string(request.form['macros'] + \"\\n\" + request.form['template'])\r\n except TemplateSyntaxError as err:\r\n response = {'template-error': \"ERROR: \" + err.message}\r\n return json.dumps(response)\r\n\r\n response = {}\r\n\r\n try:\r\n values = json.loads(request.form['values'])\r\n formatted = tpl.render(values)\r\n except ValueError as err:\r\n # Invalid JSON\r\n response['values-error'] = \"ERROR: \" + err.message\r\n return json.dumps(response)\r\n except UndefinedError as err:\r\n # Variable not present in template\r\n response['macros-error'] = \"ERROR: \" + err.message\r\n response['template-error'] = \"ERROR: \" + err.message\r\n return json.dumps(response)\r\n\r\n pprint(formatted)\r\n if int(request.form['xmlformat']):\r\n try:\r\n parser = etree.XMLParser(remove_blank_text=True)\r\n elem = etree.XML(formatted, parser=parser)\r\n formatted = etree.tostring(elem, pretty_print=True)\r\n except XMLSyntaxError as err:\r\n # Template output was not valid XML\r\n response['render-error'] = \"ERROR: Output was not valid XML \"\r\n\r\n response['render'] = formatted\r\n return json.dumps(response)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.debug = True\r\n app.run(host='0.0.0.0')\r\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":3683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"279925551","text":"from flask import Flask, request, render_template\nfrom werkzeug import secure_filename\nimport numpy as np\nimport pandas as pd\nimport re, base64, io, uuid, os, cv2\nfrom keras.preprocessing import image\nfrom PIL import Image\nfrom keras.models import load_model\nfrom keras import backend as K\nfrom flask import jsonify\nimport FaceNet_satya_util as satya\nimport csv\nimport nlp_util as nlp_satya\nfrom keras.preprocessing.text import Tokenizer\nimport nlp_prediction_functios as nlp_predict\n\napp = Flask(__name__)\nAPP_ROOT = os.path.dirname(os.path.realpath(__file__))\n#APP_ROOT = os.path.dirname(os.path.curdir)\n\n#facenet_keras = load_model(os.path.join(APP_ROOT, \"models\", \"facenet_keras.h5\"))\n\n \ndef factors(num):\n return [x for x in range(1, num+1) if num%x==0]\n\n@app.route('/')\ndef hello_world():\n return render_template(\n \"./home.html\" # name of template\n )\n \n@app.route('/image_prediction')\ndef image_prediction():\n return render_template(\n \"./image_prediction.html\" # name of template\n )\n\n@app.route('/digit_recognizer')\ndef digit_recognizer():\n return render_template(\n \"./digit_recognizer.html\" # name of template\n )\n\n@app.route('/cloth_recognizer')\ndef cloth_recognizer():\n return render_template(\n \"./cloth_recognizer.html\" # name of template\n )\n@app.route('/face_extractor')\ndef face_extractor():\n return render_template(\n \"./face_extractor.html\" # name of template\n )\n@app.route('/face_recognizer')\ndef face_recognizer():\n return render_template(\n \"./face_recognizer.html\" # name of template\n )\n \n@app.route('/nlp_sentiment_movie_review')\ndef nlp_sentiment_movie_review():\n return render_template(\n \"./nlp_sentiment_movie_review.html\" # name of template\n )\n@app.route('/nlp_news_classification_01')\ndef nlp_news_classification_01():\n return render_template(\n \"./nlp_news_classification_01.html\" # name of template\n )\n\n@app.route('/nlp_next_word_prediction_01')\ndef nlp_next_word_prediction_01():\n return render_template(\n \"./nlp_next_word_prediction_01.html\" # name of template\n )\n \n@app.route('/nlp_english_to_french')\ndef nlp_english_to_french():\n return render_template(\n \"./nlp_english_to_french.html\" # name of template\n )\n \n@app.route('/predict_image', methods=['GET','POST'])\ndef predict_image():\n file = request.files['file']\n filename = secure_filename(file.filename)\n destination = os.path.join(APP_ROOT,\"images\")\n if not os.path.isdir(destination):\n os.mkdir(destination)\n \n filename = file.filename\n destination = os.path.join(destination, filename)\n file.save(destination)\n \n #Make the prediction\n classifier = load_model(os.path.join(APP_ROOT, \"models\", \"cnn_satya_dataset_64X64_10000.h5\"))\n test_image = image.load_img(destination, target_size=(64,64))\n test_image = image.img_to_array(test_image)\n test_image = np.expand_dims(test_image, axis=0)\n result = classifier.predict(test_image)\n K.clear_session()\n prediction = 'dog'\n \n if(result[0][0] == 0):\n prediction = 'cat'\n\n # logic to load image\n return prediction, 200\n\n\n@app.route('/identify_digit', methods=['GET','POST'])\ndef identify_digit():\n imgstring=request.form['file']\n base64_data = re.sub('data:image/.+;base64,', '', imgstring)\n byte_data = base64.b64decode(base64_data)\n image_data = io.BytesIO(byte_data)\n img = Image.open(image_data)\n \n destination = os.path.join(APP_ROOT,\"images\")\n if not os.path.isdir(destination):\n os.mkdir(destination)\n \n input_folder = os.path.join(destination,'test.png')\n print(input_folder)\n img.save(input_folder, \"png\") \n \n #Make prediction\n model = load_model(os.path.join(APP_ROOT, 'models', 'digit_recognizer.h5'))\n\n test_image = image.load_img(input_folder, target_size=(28,28),color_mode = \"grayscale\",grayscale=True)\n test_image = np.array(test_image)\n \n num_pixels = test_image.shape[0] * test_image.shape[1] #it will be 784\n \n # change the imege array of type (60000, 28,28) to (60000,784)\n test_image = test_image.reshape(1,num_pixels).astype('float32')\n test_image = test_image / 255\n \n result = model.predict(test_image)\n K.clear_session()\n #a = {'result':result, 'prediction': np.argmax(a)}\n #np.argmax(a)\n # logic to load image\n return str(np.argmax(result)), 200\n\n@app.route('/predict_cloth', methods=['GET','POST'])\ndef predict_cloth():\n file = request.files['file']\n filename = secure_filename(file.filename)\n destination = os.path.join(APP_ROOT,\"images\")\n if not os.path.isdir(destination):\n os.mkdir(destination)\n \n filename = file.filename\n destination = os.path.join(destination, filename)\n file.save(destination)\n \n #Make the prediction\n classifier = load_model(os.path.join(APP_ROOT, \"models\", \"cloth_model.h5\"))\n test_image = image.load_img(destination, target_size=(28,28), grayscale=True)\n test_image = image.img_to_array(test_image)\n test_image = test_image / 255\n test_image = np.expand_dims(test_image, axis=0)\n result = classifier.predict(test_image)\n K.clear_session()\n prediction = np.argmax(result)\n cloth = pd.read_csv(os.path.join(APP_ROOT, \"models\", \"cloth_types.csv\"))\n prediction = cloth.iloc[prediction][1]\n\n # logic to load image\n return prediction, 200\n\n@app.route('/extract_faces', methods=['GET','POST'])\ndef extract_faces():\n file = request.files['file']\n filename = secure_filename(file.filename)\n destination = os.path.join(APP_ROOT,\"images\")\n if not os.path.isdir(destination):\n os.mkdir(destination)\n \n filename = file.filename\n destination = os.path.join(destination, filename)\n file.save(destination)\n \n # Extract the faces\n imagePath = destination\n cascPath = os.path.join(APP_ROOT,\"static/cascades/haarcascade_frontalface_default.xml\")\n face_cascade = cv2.CascadeClassifier(cascPath)\n # Read the image\n image = cv2.imread(imagePath)\n gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\n # SEARCH CORDINATE OF FACES\n faces = face_cascade.detectMultiScale(\n gray, \n scaleFactor=1.2,\n minNeighbors=5\n )\n facelist = []\n facepath = os.path.join(APP_ROOT,'static/faces')\n if not os.path.isdir(facepath):\n os.mkdir(facepath)\n \n for x,y,w,h in faces:\n roi_color = image[y:y + h, x:x + w]\n tname = str(uuid.uuid4()).replace('-','') + '.jpg'\n facename = os.path.join(facepath, tname)\n cv2.imwrite(facename, roi_color)\n facelist.append(tname)\n \n # mark the border on identified faces\n for x,y,w,h in faces:\n image = cv2.rectangle(image,(x, y), (x+w, y+h), (0,255,0),2)\n \n # make the prediction on extracted faces\n \n tname = str(uuid.uuid4()).replace('-','') + '.jpg'\n facename = os.path.join(facepath, tname)\n cv2.imwrite(facename, image)\n facelist.append(tname)\n \n return jsonify(facelist), 200\n\n@app.route('/recognize_single_faces', methods=['GET','POST'])\ndef recognize_single_faces():\n destination = os.path.join(APP_ROOT,\"images\")\n filename = satya.save_uploaded_file(request, destination)\n destination = os.path.join(destination, filename)\n \n #load pretrained model\n model = load_model(os.path.join(APP_ROOT, \"models\", \"facenet_keras.h5\"))\n \n all_faces, face_positions = satya.extract_all_face(destination)\n datafile = os.path.join(APP_ROOT, \"models/face_list.csv\");\n facepath = os.path.join(APP_ROOT,'static/faces')\n facelist = []\n \n for index, face_pixel in enumerate(all_faces):\n face_encodeing = satya.get_embedding(model, face_pixel)\n \n #Check the encoding in csv file\n predictedName = satya.get_person_name_by_encodding(face_encodeing, datafile)\n if len(predictedName) == 0:\n predictedName = \"unknown\"\n \n tname = satya.save_extracted_face(facepath, face_pixel)\n dict1 = { 'Name' : predictedName, 'Image' : tname } \n facelist.append(dict1)\n \n K.clear_session()\n \n #create borders on main image to shocase the face identification\n result_image = cv2.imread(destination)\n for fpos in face_positions:\n result_image = satya.put_border_and_text_on_image(result_image, fpos, 'NA')\n \n tname = satya.save_extracted_face(facepath, result_image)\n dict1 = { 'Name' : predictedName, 'Image' : tname } \n facelist.append(dict1)\n \n return jsonify(facelist), 200\n\n@app.route('/upload_new_faces/', methods=['GET','POST'])\ndef upload_new_faces(name):\n destination = os.path.join(APP_ROOT,\"images\")\n filename = satya.save_uploaded_file(request, destination)\n personName = os.path.splitext(filename)[0]\n destination = os.path.join(destination, filename)\n \n face_pixel = satya.extract_face(destination)\n\n #load pretrained model\n model = load_model(os.path.join(APP_ROOT, \"models\", \"facenet_keras.h5\"))\n \n face_encodeing = satya.get_embedding(model, face_pixel)\n K.clear_session()\n \n #Check and update the encoding in csv file\n datafile = os.path.join(APP_ROOT, \"models/face_list.csv\");\n predictedName = satya.get_person_name_by_encodding(face_encodeing, datafile)\n \n if len(predictedName) > 0:\n personName = predictedName\n else:\n add_person_name_with_encodding(name, face_encodeing, datafile)\n\n return personName, 200\n \n\ndef add_person_name_with_encodding(personName, newface, datafile):\n newface = np.append(personName, newface)\n newface = newface.reshape(1,129)\n with open(datafile, 'a') as writeFile:\n writer = csv.writer(writeFile)\n writer.writerows(newface.tolist())\n writeFile.close()\n\n############## NLP CODE START HERE ##########################\n@app.route('/nlp_check_sentiment_movie_review/', methods=['GET','POST'])\ndef nlp_check_sentiment_movie_review(text):\n text = request.form['inputText']\n \n import urllib.parse\n text = urllib.parse.unquote_plus(text)\n reviews_test = []\n reviews_test.append(text)\n reviews_test = nlp_satya.CleanAndRemoveHtmlAndOtherSpacialChars(reviews_test)\n reviews_test = nlp_satya.NTLK_remove_stop_words(reviews_test)\n reviews_test = nlp_satya.NTLK_get_stemmed_text(reviews_test)\n reviews_test = nlp_satya.NTLK_get_lemmatized_text(reviews_test)\n \n #load pretrained model\n model = nlp_satya.pickle_LoadModal(os.path.join(APP_ROOT, \"models\", \"Movie_Review.h5\"))\n ngram_vectorizer = nlp_satya.pickle_LoadModal(os.path.join(APP_ROOT, \"models\", \"Movie_Review_ngram_vectorizer.h5\"))\n reviews_test = ngram_vectorizer.transform(reviews_test)\n prediction = model.predict(reviews_test)\n K.clear_session()\n return str(prediction[0]), 200\n\n@app.route('/nlp_predict_news_classification_01', methods=['GET','POST'])\ndef nlp_predict_news_classification_01():\n text = request.form['inputText']\n \n import urllib.parse\n text = urllib.parse.unquote_plus(text)\n model_input = []\n model_input.append(text)\n \n #load pretrained model\n model = load_model(os.path.join(APP_ROOT, \"models\", \"model_news_classification_01.h5\"))\n tokenizer = Tokenizer()\n tokenizer = nlp_satya.pickle_LoadModal(os.path.join(APP_ROOT,\"models\",\"tokenizer_news_classification_01.pickle\"))\n model_input = tokenizer.texts_to_matrix(model_input, mode='tfidf')\n prediction = model.predict(model_input)\n K.clear_session()\n return str(np.argmax(prediction)), 200\n# return 'ok',200\n \n@app.route('/nlp_predict_next_word_01', methods=['GET','POST'])\ndef nlp_predict_next_word_01():\n text = request.form['inputText']\n result = nlp_predict.nlp_predict_next_word_01(APP_ROOT, text)\n return result, 200\n\n@app.route('/nlp_convert_english_to_french', methods=['GET','POST'])\ndef nlp_convert_english_to_french():\n text = request.form['inputText']\n modelName = request.form['modelName']\n import nlp_english_to_french as convertor\n result = ''\n if (modelName == 'eng-fra'):\n result = convertor.convert_english_to_french(APP_ROOT, text)\n else:\n result = convertor.convert_english_to_hindi(APP_ROOT, text)\n return result, 200\n \nif __name__ == '__main__':\n app.run(host='0.0.0.0',port=80)","sub_path":"flask_app.py","file_name":"flask_app.py","file_ext":"py","file_size_in_byte":12468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"473168176","text":"import sys\nimport time\nimport logging\n\nLOG_FILENAME = '~/i3bar-debug.log'\n\nfrom widget import *\n\n#-------------------------------------------------------------------------\n\nfrom widgets.date import *\nfrom widgets.network import *\nfrom widgets.battery import *\nfrom widgets.temperature import *\nfrom widgets.fortune import *\nfrom widgets.mpd import *\n\nif __name__ == \"__main__\":\n bar = i3barPrinter()\n if (len(sys.argv) > 1 and sys.argv[1] == '--debug'):\n pr = Printer(Printer.debugFormat)\n else:\n pr = Printer(Printer.jsonFormat)\n bar.PrintHeader()\n\n widgets = []\n widgets.append(MpdWidget())\n widgets.append(Temperature())\n widgets.append(BatteryWidget())\n widgets.append(NetworkWidget_Left())\n widgets.append(NetworkWidget_Right())\n widgets.append(DateWidget())\n widgets.append(ClockWidget())\n\n try:\n while True:\n print('[')\n length = len(widgets)\n for i in range(length - 1):\n tick = time.time()\n w = widgets[i]\n w.TryUpdate(tick)\n pr.PrintWidget(w.GetFrame())\n print(',')\n w = widgets[length - 1]\n w.TryUpdate(tick)\n pr.PrintWidget(w.GetFrame())\n print('],')\n sys.stdout.flush()\n time.sleep(0.5)\n except:\n logging.exception('>>> Got an unhandled exception!')\n raise\n","sub_path":"i3widgets/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"578874974","text":"n,k=map(int,input().split())\nar=list(map(str,input().split()))\nl=[]\nfor i in range(n-1):\n co=1\n for j in range(i+1,n):\n if(ar[i]==ar[j]):\n co=co+1\n l.append(int(co==k))\nif(any(l)):\n print(\"yes\")\nelse:\n print(\"no\")\n","sub_path":"NoOfoccurenceString.py","file_name":"NoOfoccurenceString.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"21941583","text":"def inorder(id):\n global num\n if id > N: return\n\n inorder(id << 1)\n arr[id] = num\n num += 1\n inorder((id << 1) + 1)\n\n\nT = int(input())\nfor test_case in range(1, T + 1):\n N = int(input())\n num = 1\n arr = [0] * (N + 1)\n\n inorder(1)\n\n print(\"#%d %d %d\" % (test_case, arr[1], arr[N//2]))\n\n\n","sub_path":"08 Tree/실습문제/[5176]이진탐색.py","file_name":"[5176]이진탐색.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"255099647","text":"__author__ = 'taosituo'\n\nimport numpy as np\n\n\ndef get_feature(company_dict):\n \"\"\"\n :param company_dict[company_id][campaign_id][cluster_id] = times\n :return company_list = [[company_id1, total_cluster_num, ptp, var, max], [company_id2, ... ], ... ]\n \"\"\"\n company_list = list()\n for company_id in company_dict:\n feature_list = [company_id]\n\n # total_cluster_num\n total_cluster_num = feature_cluster_num(company_dict[company_id])\n\n # rate\n rate_boundary = 0.2\n rate_range_num, ptp, var, max = feature_frequency(company_dict[company_id], rate_boundary)\n\n feature_list.extend([total_cluster_num, ptp, var, max])\n company_list.append(feature_list)\n return company_list\n\n\ndef feature_cluster_num(campaign_dict):\n \"\"\"\n campaign_dict is company_dict[company_id]\n campaign_dict[campaign_id][cluster_id] = times\n \"\"\"\n cluster_num = 0\n for campaign_id in campaign_dict:\n cluster_num += len(campaign_dict[campaign_id])\n return cluster_num\n\n\ndef feature_frequency(campaign_dict, rate_boundary):\n ### cluster_dict[cluster_id] = times\n cluster_dict = dict()\n document_nums = 0\n for campaign_id in campaign_dict:\n for cluster_id in campaign_dict[campaign_id]:\n times = campaign_dict[campaign_id][cluster_id]\n document_nums += times\n if cluster_id not in cluster_dict:\n cluster_dict[cluster_id] = times\n else:\n cluster_dict[cluster_id] += times\n\n rate_range_num = 0\n for cluster_id in cluster_dict.keys():\n times = float(cluster_dict[cluster_id])\n frequency = times / document_nums\n cluster_dict[cluster_id] = frequency\n if frequency > rate_boundary:\n rate_range_num += 1\n\n frequency_array = np.array(cluster_dict.values())\n # ptp = max - min\n ptp = np.ptp(frequency_array)\n # var\n var = np.var(frequency_array)\n # max\n max = np.max(frequency_array)\n return rate_range_num, ptp, var, max","sub_path":"categorization/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"10008886","text":"import copy\r\nimport heapq\r\nimport time\r\n\r\n\r\ndef heuristic (puzzle):\r\n\r\n \"\"\"\r\n call succ(state), and print each element with its heuristic value\r\n \"\"\"\r\n\r\n row = 0\r\n col = 0\r\n h = 0\r\n\r\n for element in puzzle:\r\n # print(element)\r\n expect_corrd = get_expect_coord(element)\r\n\r\n if(element == 0):\r\n col += 1\r\n if col % 3 == 0 and col != 0:\r\n row += 1\r\n if col % 3 == 0 and col != 0:\r\n col = 0\r\n\r\n continue\r\n\r\n # calculate the manhattan distance of the element location and expected location\r\n h += abs(expect_corrd[0] - row) + abs(expect_corrd[1] - col)\r\n\r\n col += 1\r\n\r\n # update the row\r\n if col %3 == 0 and col != 0:\r\n row += 1\r\n if col % 3 == 0 and col != 0:\r\n col = 0\r\n return h\r\n\r\n\r\ndef print_succ(state):\r\n\r\n \"\"\"\r\n # call succ(state), and print each element with its heuristic value\r\n \"\"\"\r\n\r\n succ_list = succ(state)\r\n\r\n for element in succ_list:\r\n print(element, 'h=' + str(heuristic(element)))\r\n\r\n# return all the possible successors of the state\r\ndef succ(state):\r\n row = 0\r\n succ_list = []\r\n for i in range(9):\r\n if state[i] == 0:\r\n # for the first row\r\n if row == 0:\r\n # first row tiles can always switch with the tile under them\r\n succ1 = swap_pos(state, i, i + 3)\r\n succ_list.append(succ1)\r\n\r\n # determine to swith left of right or both for col is middle\r\n # same for the latter two rows\r\n succs = help_print(state, i)\r\n if i % 3 == 1:\r\n succ_list.append(succs[0])\r\n succ_list.append(succs[1])\r\n else:\r\n succ_list.append(succs)\r\n\r\n elif row == 1:\r\n # second row can always swith up and down\r\n succ1 = swap_pos(state, i, i + 3)\r\n succ3 = swap_pos(state, i, i - 3)\r\n\r\n succ_list.append(succ1)\r\n succ_list.append(succ3)\r\n\r\n succs = help_print(state, i)\r\n\r\n if i % 3 == 1:\r\n succ_list.append(succs[0])\r\n succ_list.append(succs[1])\r\n else:\r\n succ_list.append(succs)\r\n\r\n elif row == 2:\r\n # third row can always swithc up\r\n succ1 = swap_pos(state, i, i - 3)\r\n succ_list.append(succ1)\r\n\r\n succs = help_print(state, i)\r\n\r\n if i % 3 == 1:\r\n succ_list.append(succs[0])\r\n succ_list.append(succs[1])\r\n else:\r\n succ_list.append(succs)\r\n # update row\r\n if i % 3 == 2:\r\n row += 1\r\n\r\n # sorted(succ_list)\r\n\r\n\r\n return sorted(succ_list)\r\n\r\n# helper function to determine the possible successors by switching horizontally\r\n# return the list of horizontally swtich successors if i in middle col, else return successor\r\ndef help_print(state, i):\r\n succ_list = []\r\n\r\n # col in the left\r\n if i % 3 == 0:\r\n # col 0\r\n succ2 = swap_pos(state, i, i + 1)\r\n succ_list = succ2\r\n\r\n # col in the middle, return two possible successors\r\n if i % 3 == 1:\r\n # col 1\r\n succ2 = swap_pos(state, i, i + 1)\r\n succ3 = swap_pos(state, i, i - 1)\r\n\r\n succ_list.append(succ2)\r\n succ_list.append(succ3)\r\n\r\n # col in the right\r\n if i % 3 == 2:\r\n # col 2\r\n succ2 = swap_pos(state, i, i - 1)\r\n succ_list = succ2\r\n\r\n return succ_list\r\n\r\n\r\ndef swap_pos (state, pos1, pos2):\r\n state_copy = copy.deepcopy(state)\r\n a = state_copy[pos1]\r\n state_copy[pos1] = state_copy[pos2]\r\n state_copy[pos2] = a\r\n # print(state_copy)\r\n\r\n return state_copy\r\n\r\n\r\ndef get_expect_coord(value):\r\n coord = []\r\n if value == 1:\r\n coord = [0,0]\r\n elif value == 2:\r\n coord = [0,1]\r\n elif value == 3:\r\n coord = [0,2]\r\n elif value == 4:\r\n coord = [1,0]\r\n elif value == 5:\r\n coord = [1,1]\r\n elif value == 6:\r\n coord = [1,2]\r\n elif value == 7:\r\n coord = [2,0]\r\n elif value == 8:\r\n coord = [2,1]\r\n return coord\r\n\r\ndef solve(state):\r\n goal_state = [1, 2, 3, 4, 5, 6, 7, 8, 0]\r\n\r\n a = A_star(state, goal_state)\r\n moves = 0\r\n\r\n i = len(a) - 1\r\n\r\n while i >= 0:\r\n # print(a[i])\r\n print(a[i], 'h='+ str(heuristic(a[i])), 'moves: ' + str(moves))\r\n\r\n i = i - 1\r\n moves += 1\r\n\r\n pq = []\r\n# perform A star algorithm\r\n# return the reconstruct path\r\ndef A_star(start, goal_state):\r\n open = []\r\n closed = []\r\n open_heap = []\r\n\r\n a = -1 # parent index\r\n\r\n current = start\r\n open.append(current)\r\n\r\n # dict with parents as key and children as value\r\n parents = dict()\r\n\r\n\r\n heapq.heappush(open_heap, (heuristic(start), start, (0, heuristic(start), a)))\r\n\r\n # used for reconstruct_path1 but ends with higher time complexity\r\n # static_heap.append((heuristic(start), start, (0, heuristic(start), a)))\r\n\r\n while len(open_heap) > 0:\r\n\r\n f_score, current, info = heapq.heappop(open_heap)\r\n\r\n open.remove(current)\r\n closed.append(current)\r\n\r\n if current == goal_state:\r\n return reconstruct_path(parents, current)\r\n\r\n for node in succ(current):\r\n\r\n # update the g score and f score\r\n temp_g_score = info[0] + 1\r\n temp_f_score = temp_g_score + heuristic(node)\r\n\r\n # parent_index = static_heap.index((f_score, current, info))\r\n\r\n if node not in closed:\r\n parents[str(node)] = current\r\n\r\n open.append(node)\r\n heapq.heappush(open_heap,(temp_f_score, node, (temp_g_score, heuristic(node), a + 1)))\r\n\r\n # used for reconstruct_path1 but ends with higher time complexity\r\n # static_heap.append((temp_f_score, node, (temp_g_score, heuristic(node), parent_index)))\r\n\r\n\r\n\r\n\r\n\"\"\"\r\ndef reconstruct_path1(current, static_heap, info):\r\n total_path = [(info[0] + info[1], current, info)]\r\n\r\n while info[2] != -1:\r\n\r\n current = static_heap[info[2]]\r\n info = static_heap[info[2]][2]\r\n total_path.append(current)\r\n return total_path\r\n\r\n\"\"\"\r\n\r\n\r\ndef reconstruct_path(parents, current):\r\n\r\n total_path = [current]\r\n\r\n while str(current) in parents.keys():\r\n current = parents[str(current)]\r\n total_path.append(current)\r\n\r\n return total_path\r\n\r\n\r\nif __name__ == \"__main__\":\r\n puzzle = [8, 7, 6, 5, 4, 3, 2, 1, 0]\r\n print_succ([1, 2, 3, 4, 5, 0, 6, 7, 8])\r\n print_succ([8, 7, 6, 5, 4, 3, 2, 1, 0])\r\n\r\n solve(puzzle)\r\n","sub_path":"funny_puzzle.py","file_name":"funny_puzzle.py","file_ext":"py","file_size_in_byte":6820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"519499486","text":"import argparse\nfrom os.path import dirname, abspath, join, exists\nfrom operator import itemgetter\nimport os\nimport logging\nimport sys\n\nfrom onmt.utils.misc import jarWrapper, call_subprocess\nfrom onmt.utils.scores import make_ext_evaluators\nimport multiprocessing\nimport math\nimport concurrent.futures\nimport timeit\nimport urllib.request\nfrom multiprocessing.pool import ThreadPool\nimport numpy as np\nfrom functools import reduce\nimport collections\n\n\nimport sys\nimport re\nimport os\n\n\nBASE_DIR = dirname(dirname(abspath(__file__)))\n\n\nclass JavaDelimiter:\n @property\n def varargs(self):\n return \"...\"\n\n @property\n def rightBrackets(self):\n return \"]\"\n\n @property\n def leftBrackets(self):\n return \"[\"\n\n @property\n def rightCurlyBrackets(self):\n return \"}\"\n\n @property\n def leftCurlyBrackets(self):\n return \"{\"\n\n @property\n def biggerThan(self):\n return \">\"\n\n @property\n def semicolon(self):\n return \";\"\n\n @property\n def comma(self):\n return \",\"\n\n @property\n def dot(self):\n return \".\"\n\n @property\n def assign(self):\n return \"=\"\n\n @property\n def left(self):\n return \".\"\n\n\ndef get_logger(run_name=\"logs\", save_log=None, isDebug=False):\n log_filename = f'{run_name}.log'\n if save_log is None:\n log_dir = join(BASE_DIR, 'logs')\n if not exists(log_dir):\n os.makedirs(log_dir)\n log_filepath = join(log_dir, log_filename)\n else:\n log_filepath = save_log\n\n logger = logging.getLogger(run_name)\n\n debug_level = logging.DEBUG if isDebug else logging.INFO\n logger.setLevel(debug_level)\n\n if not logger.handlers: # execute only if logger doesn't already exist\n file_handler = logging.FileHandler(log_filepath, 'a', 'utf-8')\n stream_handler = logging.StreamHandler(os.sys.stdout)\n\n formatter = logging.Formatter('[%(levelname)s] %(asctime)s > %(message)s', datefmt='%Y-%m-%d %H:%M:%S')\n\n file_handler.setFormatter(formatter)\n stream_handler.setFormatter(formatter)\n\n logger.addHandler(file_handler)\n logger.addHandler(stream_handler)\n\n return logger\n\n\ndef get_total_nums_line(path):\n return len(open(path).readlines())\n\n\ndef chunks(lst, chunk_size):\n \"\"\"Yield n chunks from lst.\"\"\"\n for i in range(0, len(lst), chunk_size):\n yield lst[i:i + chunk_size]\n\n\nclass PredictionSplit(object):\n def __init__(self, opt, logger):\n self.opt = opt\n self.logging = logger\n self.args_checkup()\n\n self.score = make_ext_evaluators(self.opt.measure)[0]\n\n self.src_buggy = [line.strip() for line in open(self.opt.src_buggy, 'r')]\n self.src_fixed = [line.strip() for line in open(self.opt.src_fixed, 'r')]\n self.pred_fixed = [line.strip() for line in open(self.opt.pred_fixed, 'r')]\n self.n_best = self.opt.n_best\n self.nums_buggy = len(self.src_buggy)\n self.nums_thread = self.opt.nums_thread\n\n self.jar_exe_args = ['scala', f'-Dlog4j.configuration=file://{self.opt.log4j_config}', self.opt.jar, 'astdiff']\n\n self.delimiter = JavaDelimiter()\n\n logging.debug(f\"The number of n_best is [{args.n_best}], \"\n f\"the threshold of best ratio is {args.best_ratio}, \"\n f\"The nums thread {self.nums_thread}\")\n\n def get_score(self, src, tgt):\n if self.opt.measure == 'bleu':\n return self.score([src], [tgt]) / 100\n elif self.opt.measure == 'ast':\n args = self.jar_exe_args + [src] + [tgt]\n nums = self.score(args)\n total = nums / ((len(src.split()) + len(src.split())) / 2)\n return 1.0 - total\n else:\n return self.score(src, tgt)\n\n def args_checkup(self):\n nums_src_buggy = get_total_nums_line(self.opt.src_buggy)\n nums_src_fixed = get_total_nums_line(self.opt.src_fixed)\n nums_pred_fixed = get_total_nums_line(self.opt.pred_fixed)\n nums_best = self.opt.n_best\n if nums_src_buggy != nums_src_fixed:\n self.logging.error(f\"The nums of buggy[{nums_src_buggy}] and fixed[{nums_src_fixed}] does not match\")\n exit(-1)\n\n if nums_src_buggy != (nums_pred_fixed / nums_best):\n self.logging.error(f\"The nums of buggy[{nums_src_buggy}] does not match predict[{nums_src_fixed}] \"\n f\"with nums of best[{nums_best}]\")\n exit(-1)\n\n def debug_accuarcy(self):\n result = self.thread_run(0, self.src_buggy, self.src_fixed, self.pred_fixed)\n\n count_perfect, count_changed, count_bad = result[\"statistics\"]\n self.logging.info(\n f\"Count Perfect[{count_perfect}], changed {count_changed}, \"\n f\"bad {count_bad}, performance {(count_perfect * 1.0 / self.nums_buggy): 0.4f}\")\n\n\n pred_best = result[\"pred_best\"]\n with open(self.opt.output, 'w') as output:\n output.writelines(\"%s\\n\" % place for place in pred_best)\n\n\n\n return count_perfect, count_changed, count_bad\n\n def thread_run(self, thread_id, src_buggy, src_fixed, pred_fixed, chunk_size):\n nums_buggy = len(src_buggy)\n buggy_best = []\n predt_best = []\n fixed_best = []\n cnt_0 = 0\n cnt_1 = 0\n cnt_2 = 0\n cnt_3 = 0\n cnt_4 = 0\n cnt_other = 0\n cnt_error = 0\n\n for i in range(nums_buggy):\n buggy = src_buggy[i]\n fixed = src_fixed[i]\n preds = pred_fixed[i * self.n_best:(i + 1) * self.n_best]\n\n # Reture the best score of similarity with a tuple of (index, similarity_score).\n fixed_preds_score = [(index, self.get_score(fixed, tgt)) for index, tgt in enumerate(preds)]\n fixed_max_match = max(fixed_preds_score, key=itemgetter(1))\n match_index = fixed_max_match[0]\n match_score = fixed_max_match[1]\n\n if match_score >= 1.0:\n prefix = f\"#{thread_id * chunk_size + i}#0#\\t\"\n cnt_0 = cnt_0 + 1\n elif 0.95 <= match_score < 1.0:\n prefix = f\"#{thread_id * chunk_size + i}#1#\\t\"\n cnt_1 = cnt_1 + 1\n elif 0.9 <= match_score < 0.95:\n prefix = f\"#{thread_id * chunk_size + i}#2#\\t\"\n cnt_2 = cnt_2 + 1\n elif 0.85 <= match_score < 0.9:\n prefix = f\"#{thread_id * chunk_size + i}#3#\\t\"\n cnt_3 = cnt_3 + 1\n elif 0.80 <= match_score < 0.85:\n prefix = f\"#{thread_id * chunk_size + i}#4#\\t\"\n cnt_4 = cnt_4 + 1\n elif 0.50 <= match_score < 0.8:\n prefix = f\"#{thread_id * chunk_size + i}#5#\\t\"\n cnt_other = cnt_other + 1\n else:\n prefix = f\"#{thread_id * chunk_size + i}#Er#\\t\"\n cnt_error = cnt_error + 1\n\n buggy_best.append(f\"{prefix}{buggy}\")\n fixed_best.append(f\"{prefix}{fixed}\")\n predt_best.append(f\"{prefix}{preds[match_index]}\")\n\n return {thread_id: {\"statistics\": np.array([cnt_0, cnt_1, cnt_2, cnt_4, cnt_other, cnt_error]),\n \"buggy_best\": buggy_best,\n \"fixed_best\": fixed_best,\n \"predt_best\": predt_best}}\n\n def retrieve_java_code(self, path):\n predictions = open(path, \"r\").readlines()\n predictions_asCodeLines = []\n\n for prediction in predictions:\n tmp = self.retrieve_single_java_source(prediction)\n if tmp != \"\":\n predictions_asCodeLines.append(tmp)\n\n if len(predictions_asCodeLines) == 0:\n sys.stderr.write(\"All predictions contains token\")\n sys.exit(1)\n\n predictions_asCodeLines_file = open(os.path.join(self.opt.output, \"predictions_JavaSource.txt\"), \"w\")\n for predictions_asCodeLine in predictions_asCodeLines:\n predictions_asCodeLines_file.write(predictions_asCodeLine + \"\\n\")\n predictions_asCodeLines_file.close()\n sys.exit(0)\n\n def retrieve_single_java_source(self, prediction):\n tokens = prediction.strip().split(\" \")\n codeLine = \"\"\n\n for i in range(len(tokens)):\n # if tokens[i] == \"\":\n # return \"\"\n if i + 1 < len(tokens):\n # DEL = delimiters\n # ... = method_referece\n # STR = token with alphabet in it\n\n if not self.isDelimiter(tokens[i]):\n if not self.isDelimiter(tokens[i + 1]): # STR (i) + STR (i+1)\n codeLine = codeLine + tokens[i] + \" \"\n else: # STR(i) + DEL(i+1)\n codeLine = codeLine + tokens[i]\n else:\n if tokens[i] == self.delimiter.varargs: # ... (i) + ANY (i+1)\n codeLine = codeLine + tokens[i] + \" \"\n elif tokens[i] == self.delimiter.biggerThan: # > (i) + ANY(i+1)\n codeLine = codeLine + tokens[i] + \" \"\n elif tokens[i] == self.delimiter.semicolon:\n codeLine = codeLine + tokens[i] + \" \"\n elif tokens[i] == self.delimiter.comma:\n codeLine = codeLine + tokens[i] + \" \"\n elif tokens[i] == self.delimiter.dot:\n codeLine = codeLine + tokens[i]\n elif tokens[i] == self.delimiter.assign:\n codeLine = codeLine + \" \" + tokens[i] + \" \"\n elif tokens[i] == self.delimiter.leftCurlyBrackets:\n codeLine = codeLine + tokens[i] + \" \"\n elif tokens[i] == self.delimiter.rightBrackets and i > 0:\n if tokens[i - 1] == self.delimiter.leftBrackets: # [ (i-1) + ] (i)\n codeLine = codeLine + tokens[i] + \" \"\n else: # DEL not([) (i-1) + ] (i)\n codeLine = codeLine + tokens[i]\n else: # DEL not(... or ]) (i) + ANY\n codeLine = codeLine + tokens[i]\n else:\n codeLine = codeLine + tokens[i]\n return codeLine\n\n @staticmethod\n def isDelimiter(token):\n return not token.upper().isupper()\n\n def run(self):\n return_value = dict()\n statistics = []\n predt_best = []\n fixed_best = []\n buggy_best = []\n batch_size = math.ceil(self.nums_buggy / self.nums_thread)\n\n buggy_chunks = chunks(self.src_buggy, batch_size)\n fixed_chunks = chunks(self.src_fixed, batch_size)\n pred_chunks = chunks(self.pred_fixed, batch_size * self.n_best)\n\n # Using ThreadPoolExecutor will lead to a GIL issue and cannot run in parallel\n # https://gist.github.com/mangecoeur/9540178\n # https://stackoverflow.com/questions/61149803/threads-is-not-executing-in-parallel-python-with-threadpoolexecutor\n\n with concurrent.futures.ProcessPoolExecutor(max_workers=self.nums_thread) as executor:\n futures = {executor.submit(self.thread_run,\n thread_id,\n buggy,\n fixed,\n pred,\n batch_size): thread_id\n for thread_id, (buggy, fixed, pred) in\n enumerate(zip(buggy_chunks, fixed_chunks, pred_chunks))}\n\n for future in concurrent.futures.as_completed(futures, 60):\n thread_id = futures[future]\n try:\n return_value.update(future.result())\n except Exception as exc:\n self.logging.error(f'Thread {thread_id} generated an exception: {exc}')\n return_value = collections.OrderedDict(sorted(return_value.items()))\n\n for key, value in return_value.items():\n statistics.append(value[\"statistics\"])\n predt_best += value[\"predt_best\"]\n fixed_best += value[\"fixed_best\"]\n buggy_best += value[\"buggy_best\"]\n\n with open(join(self.opt.output, f\"{self.opt.n_best}_{self.opt.measure}_predt_best.txt\"),\n 'w') as output:\n output.writelines(\"%s\\n\" % place for place in predt_best)\n\n with open(join(self.opt.output, f\"{self.opt.n_best}_{self.opt.measure}_fixed_best.txt\"),\n 'w') as output:\n output.writelines(\"%s\\n\" % place for place in fixed_best)\n\n with open(join(self.opt.output, f\"{self.opt.n_best}_{self.opt.measure}_buggy_best.txt\"),\n 'w') as output:\n output.writelines(\"%s\\n\" % place for place in buggy_best)\n\n result = reduce(lambda a, b: a + b, statistics)\n logging.info(f\"[Performance]-[{self.opt.measure}]-[{self.opt.n_best}]-[{self.nums_buggy}]\\tcounting_[0-4, >4, \"\n f\"error]: {result}\")\n\n\n\nif __name__ == \"__main__\":\n start = timeit.default_timer()\n parser = argparse.ArgumentParser(description='Process some integers.')\n\n parser.add_argument('-output', '--output', required=True, type=str, default='')\n parser.add_argument('-src_buggy', '--src_buggy', type=str, required=True)\n parser.add_argument('-src_fixed', '--src_fixed', type=str, required=True)\n parser.add_argument('-pred_fixed', '--pred_fixed', type=str, required=True)\n parser.add_argument('-n_best', '--n_best', type=int, default=1)\n parser.add_argument('-best_ratio', '--best_ratio', type=float, default=1.0)\n parser.add_argument('-measure', '--measure', type=str, default='bleu', choices=['similarity', 'ast', 'bleu'])\n parser.add_argument('-nums_thread', '--nums_thread', type=int, default=16)\n parser.add_argument('-project_log', '--project_log', type=str, default='log.txt')\n\n parser.add_argument('-log4j_config', '--log4j_config', type=str, required=False,\n default='/home/bing/project/OpenNMT-py/examples/learning_fix/config/log4j.properties')\n\n parser.add_argument('-jar', '--jar', type=str, required=False,\n default='/home/bing/project/OpenNMT-py/examples/learning_fix/bin/java_abstract-1.0-jar-with'\n '-dependencies.jar')\n parser.add_argument('-debug', '--debug', type=bool, default=False)\n args = parser.parse_args()\n\n logging = get_logger(save_log=args.project_log, isDebug=args.debug)\n\n for arg in vars(args):\n logging.debug(f\"{arg} -> {getattr(args, arg)}\")\n\n predictor = PredictionSplit(args, logging)\n\n # Debug code\n # predictor.debug_accuarcy()\n\n\n predictor.run()\n\n # predictor.retrieve_java_code(args.src_buggy)\n\n logging.debug(f'Executing Time: {timeit.default_timer() - start}')\n # sys.exit((str(count_perfect) + \" \" + str(count_changed) + \" \" + str(count_bad)))\n","sub_path":"examples/codebert/bin/performance_analysis.py","file_name":"performance_analysis.py","file_ext":"py","file_size_in_byte":14984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"143988160","text":"DEBUG = True\nCSRF_ENABLED = True\nSECRET_KEY = 'you-will-never-guess'\nFILENAME = \"mindcastr_settings.json\"\nUPLOAD_FOLDER = \"\"\nALLOWED_IMAGE_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])\nIMAGE1 = 'ads_1.jpg'\nIMAGE2 = 'ads_2.jpg'\nALLOWED_UPDATEFILE_EXTENSIONS = set(['zip'])\nUPDATE_FILE1 = 'update_win.zip'\nUPDATE_FILE2 = 'update_mac.zip'\n","sub_path":"upwork4/server/admin/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"407881872","text":"from itertools import count\n\n\nclass PaginatedAPIIterator(object):\n page_param = 'page'\n page_size_param = 'page_size'\n page_size = 100\n pagination_type = 'page'\n\n def __init__(self, service_method, args=(), kwargs=None):\n self.service_method = service_method\n self.args = args\n self.kwargs = (kwargs or {}).copy()\n\n def __iter__(self):\n for page in self.page_ids():\n kwargs = self.kwargs\n kwargs[self.page_param] = page\n kwargs[self.page_size_param] = self.page_size\n\n batch = self.service_method(*self.args, **kwargs)\n for result in batch:\n yield result\n if len(batch) < self.page_size:\n return\n\n def page_ids(self):\n if self.pagination_type == 'page':\n return count()\n if self.pagination_type == 'item':\n return count(0, self.page_size)\n raise ValueError('Unknown pagination_type')\n","sub_path":"pycloudflare/pagination.py","file_name":"pagination.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"124423161","text":"import json\nimport uuid\nimport os\nfrom os.path import join as pj\nimport sys\nsys.path.append(\"../../../horizon-pool/scripts\")\nimport util\n\ntmpl = json.loads(\"\"\"\n{\n \"MPN\": [\n false,\n \"RC0603DR-071K05L\"\n ],\n \"base\": \"9954497f-10af-4158-934b-3b53068f6de4\",\n \"datasheet\": [\n true,\n \"\"\n ],\n \"description\": [\n false,\n \"SMD Resistor General Purpose 1.05 kΩ 0.5% 0.1W\"\n ],\n \"inherit_model\": true,\n \"inherit_tags\": true,\n \"manufacturer\": [\n true,\n \"\"\n ],\n \"model\": \"96c366ee-a963-41a0-9cc8-54c646979695\",\n \"parametric\": {\n \"pmax\": \"0.1\",\n \"table\": \"resistors\",\n \"tolerance\": \"0.5\",\n \"value\": \"1050\"\n },\n \"tags\": [],\n \"type\": \"part\",\n \"uuid\": \"9cb3c59c-1e26-45e3-a77d-1aecf23802b4\",\n \"value\": [\n false,\n \"1.05 kΩ\"\n ]\n}\n\"\"\")\n\n\nwith open(\"ru.txt\") as fi:\n\tl = [x.strip().split(\"\\t\") for x in fi.readlines()]\n\nbases = {\n\"1206\": \"18abe45f-715b-4d6c-b6fb-53c8cb4104ac\",\n\"0603\": \"7e7a7e7e-4697-48a7-9bc9-36190b557ac9\",\n\"0402\": \"3f5268a0-f33b-4443-bec7-aa7e3b285c6a\",\n\"0805\": \"bf3fe998-9412-4076-b25c-e12d8d712527\"\n}\n\npool_path = os.getenv(\"HORIZON_POOL\")\nif pool_path is None :\n\traise IOError(\"need HORIOZN_POOL\")\n\nbase_path = pj(pool_path, \"parts\", \"ru\")\n\ngen = util.UUIDGenerator(\"uu.txt\")\n\nfor mpn, a, value, pmax, b, pkg, c, tol, *_ in l :\n\tpkg = pkg.split(\"(\")[1][:-1]\n\ttol = int(tol[1])\n\tpmax = float(pmax.split(\"(\")[1][:-2])\n\tvalue = int(value[:-2])/1e3\n\tprint(mpn, value, pmax, pkg, tol)\n\tif pkg in bases :\n\t\ttmpl[\"base\"] = bases[pkg]\n\t\ttmpl[\"MPN\"] = [False, mpn]\n\t\ttmpl[\"value\"] = [False, str(int(value*1e3)) + \" mΩ\"]\n\t\ttmpl[\"description\"] = [False, \"SMD Resistor Current Sensing %d mΩ %d%% %sW\"%(value*1e3, tol, str(pmax))]\n\t\ttmpl[\"uuid\"] = str(gen.get(mpn))\n\t\ttmpl[\"parametric\"][\"pmax\"] = str(pmax)\n\t\ttmpl[\"parametric\"][\"value\"] = str(value)\n\t\ttmpl[\"parametric\"][\"tolerance\"] = str(tol)\n\t\tpath = pj(base_path, pkg)\n\t\tos.makedirs(path, exist_ok = True)\n\t\twith open(pj(path, mpn+\".json\"), \"w\") as fi:\n\t\t\tjson.dump(tmpl, fi, sort_keys=True, indent=4)\n","sub_path":"scripts/samsung-ru/gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"168195358","text":"# -*- coding: utf-8 -*-\n# You have built two quadrotors guarding your house. \n# From earlier experiments with a single quadrotor, \n# we observed that the probability mass function describing \n# the presence of a quadrotor is P(X)=(0.2,0.2,0.6) where X∈{house,street,backyard}. \n# For this exercise, we assume the locations of both quadrotors are independent of each other.\n\n# What is the probability both quadrotors are in the backyard at the same time:\n\n#Quadrotor 1: P(Xa)=(0.2,0.2,0.6)\n#Quadrotor 2: P(Xb)=(0.2,0.2,0.6)\n\n# Probability Mass Function\np_Xa = [0.2,0.2,0.6]\np_Xb = [0.2,0.2,0.6]\n\n#Probability that both quadrotors are in the backyard at the same time\np_XaXb = p_Xa[2] * p_Xb[2]\nprint('Probability that both quadrotors are in the BACKYARD is :\\n' + str(p_XaXb))\n\n","sub_path":"ANFR-Week5-Ques1.py","file_name":"ANFR-Week5-Ques1.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"416628970","text":"def checkio(text: str) -> str:\n new_text = ''.join(filter(str.isalpha,text)).lower()\n addlist = []\n my_d = {x:new_text.count(x) for x in new_text}\n maxim = max(my_d.values())\n if list(my_d.values()).count(maxim) == 1 :\n for k, v in my_d.items():\n if v == maxim:\n return k\n else:\n for k,v in my_d.items():\n if v==maxim:\n addlist.append(k)\n return sorted(addlist)[0]\n\n\n\nif __name__ == '__main__':\n print(\"Example:\")\n print(checkio(\"One\"))\n\n #These \"asserts\" using only for self-checking and not necessary for auto-testing\n assert checkio(\"Hello World!\") == \"l\", \"Hello test\"\n assert checkio(\"How do you do?\") == \"o\", \"O is most wanted\"\n assert checkio(\"One\") == \"e\", \"All letter only once.\"\n assert checkio(\"Oops!\") == \"o\", \"Don't forget about lower case.\"\n assert checkio(\"AAaooo!!!!\") == \"a\", \"Only letters.\"\n assert checkio(\"abe\") == \"a\", \"The First.\"\n print(\"Start the long test\")\n assert checkio(\"a\" * 9000 + \"b\" * 1000) == \"a\", \"Long.\"\n print(\"The local tests are done.\")\n","sub_path":"Home/03.The Most Wanted Letter.py","file_name":"03.The Most Wanted Letter.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"66708263","text":"import time\r\nimport tkinter\r\nimport tkinter.messagebox\r\nfrom threading import Thread\r\n\r\ndef main():\r\n\r\n class DownloadTaskHandle(Thread):\r\n\r\n def run(self):\r\n # 模拟下载任务花费10s时间\r\n time.sleep(10)\r\n tkinter.messagebox.showinfo('提示', '下载完成!')\r\n # 启用下载按钮\r\n button1.config(state = tkinter.NORMAL)\r\n \r\n def download(): \r\n button1.config(state = tkinter.DISABLED)\r\n # 通过daemon函数将线程设置为守护线程(主程序退出就不再保留执行)\r\n # 在线程中处理耗时间的下载任务\r\n DownloadTaskHandle(daemon = True).start()\r\n \r\n def show_about():\r\n tkinter.messagebox.showinfo('关于', '作者:Clyde Wang(v1.0)')\r\n\r\n top = tkinter.Tk()\r\n top.title('单线程')\r\n top.geometry('200x150')\r\n top.wm_attributes('-topmost', 1)\r\n\r\n panel = tkinter.Frame(top)\r\n button1 = tkinter.Button(panel, text = '下载', command = download)\r\n button1.pack(side = 'left')\r\n button2 = tkinter.Button(panel, text = '关于', command = show_about)\r\n button2.pack(side = 'right')\r\n panel.pack(side = 'bottom')\r\n \r\n tkinter.mainloop()\r\n \r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"python_study/进程与线程/分线程.py","file_name":"分线程.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"370850638","text":"from subprocess import Popen, PIPE\nimport os\nimport platform\n\nfirefly_pbi_path = \"/usr/pbi/firefly-\" + platform.machine()\nfirefly_etc_path = os.path.join(firefly_pbi_path, \"etc\")\nfirefly_mnt_path = os.path.join(firefly_pbi_path, \"mnt\")\nfirefly_fcgi_pidfile = \"/var/run/firefly_fcgi_server.pid\"\nfirefly_fcgi_wwwdir = os.path.join(firefly_pbi_path, \"www\")\nfirefly_control = \"/usr/local/etc/rc.d/mt-daapd\"\nfirefly_config = os.path.join(firefly_etc_path, \"mt-daapd.conf\")\nfirefly_icon = os.path.join(firefly_pbi_path, \"default.png\")\nfirefly_oauth_file = os.path.join(firefly_pbi_path, \".oauth\")\n\n\ndef get_rpc_url(request):\n addr = request.META.get(\"SERVER_ADDR\")\n # IPv6\n if ':' in addr:\n addr = '[%s]' % addr\n return 'http%s://%s:%s/plugins/json-rpc/v1/' % (\n 's' if request.is_secure() else '',\n addr,\n request.META.get(\"SERVER_PORT\"),\n )\n\n\ndef get_firefly_oauth_creds():\n f = open(firefly_oauth_file)\n lines = f.readlines()\n f.close()\n\n key = secret = None\n for l in lines:\n l = l.strip()\n\n if l.startswith(\"key\"):\n pair = l.split(\"=\")\n if len(pair) > 1:\n key = pair[1].strip()\n\n elif l.startswith(\"secret\"):\n pair = l.split(\"=\")\n if len(pair) > 1:\n secret = pair[1].strip()\n\n return key, secret\n\n\nfirefly_advanced_vars = {\n \"set_cwd\": {\n \"type\": \"checkbox\",\n \"on\": \"-a\",\n },\n \"debuglevel\": {\n \"type\": \"textbox\",\n \"opt\": \"-d\",\n },\n \"debug_modules\": {\n \"type\": \"textbox\",\n \"opt\": \"-D\",\n },\n \"disable_mdns\": {\n \"type\": \"checkbox\",\n \"on\": \"-m\",\n },\n \"non_root_user\": {\n \"type\": \"checkbox\",\n \"on\": \"-y\",\n },\n \"ffid\": {\n \"type\": \"textbox\",\n \"opt\": \"-b\",\n },\n}\n","sub_path":"plugins/firefly/resources/fireflyUI/freenas/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"463195942","text":"\nnumbers = []\nimport random\n\nfor i in range(0,11):\n numbers.append(int(random.randint(1,100)))\n \nprint(\"Numbers...\")\n\noutput = \"\"\nfor i in numbers:\n output += str(i) + \" \"\nprint(output)\n\nprint(\"\\n\")\n\navg = 0\nsum = 0\n\ndef average(numbers):\n global avg, sum\n for i in numbers:\n sum += int(i)\n avg =(sum/10)\n return avg\n \nprint(\"The average of the above numbers is....\" , average(numbers))\n\n","sub_path":"PyLesson_09/AvgNumbers.py","file_name":"AvgNumbers.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"418189010","text":"import os\nfrom optparse import OptionParser\n\ndef PerformTests(options):\n\tgraphsFile = open(options.graphsPath, 'r')\n\n\tfor line in graphsFile:\n\t\tline = line.strip()\n\n\t\tif line == \"\" or line[0] == '#':\n\t\t\tcontinue\n\n\t\tgraphPath = line;\n\t\tgraphName = line.split('/')[-1].split('.')[0]\n\t\tclusterFile = options.iters + \"/\" + graphName + \".clst\"\n\t\tlogFile = options.iters + \"/\" + graphName + \".log\"\n\n\t\tcommand = \"exclusive \" if options.exclusive else \"nonexclusive \"\n\t\tcommand += options.binary + ((\" --hierarchy_levels \" + options.levels) if options.levels > 0 else \"\")\n\t\tcommand += \" --blocks \" + options.blocks + \" --iters \" + options.iters + \" --graph \" + line + \" --out \" + clusterFile + \" > \" + logFile\n\n\t\tprint(\"Executing \" + command)\t\t\n\t\tos.system(command)\n\ndef main():\n\tparser = OptionParser()\n\tparser.add_option(\"--binary\", dest = \"binary\", help = \"path to binary for executing\")\n\tparser.add_option(\"-b\", \"--blocks\", dest = \"blocks\", help = \"number of blocks for size constraint\")\n\tparser.add_option(\"-i\", \"--iters\", dest = \"iters\", help = \"number of iterations of algorithm\")\n\tparser.add_option(\"-g\", \"--graphs\", dest = \"graphsPath\", help = \"file with pathes to graphs\")\n\tparser.add_option(\"-e\", \"--exclusive\", action = \"store_true\", dest = \"exclusive\", default = False, help = \"perform tests in exlusive mode\")\n\tparser.add_option(\"-l\", \"--levels\", dest = \"levels\", default = 0, help = \"number of hierarchy levels, provide only if need hierarchy building\")\n\n\t(options, args) = parser.parse_args()\n\t\n\tPerformTests(options)\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"util/make_tests.py","file_name":"make_tests.py","file_ext":"py","file_size_in_byte":1562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"245728841","text":"__author__ = 'Administrator'\n\n\nimport cv2\nimport numpy as np\nimport cv2.cv as cv\nimport mlpy\n\n\nprint(\"loading...\")\nOPCV_PATH=r\"F:/science_cal/opencv\"\ndef get_EuclideanDistance(x,y):\n myx=np.array(x)\n myy=np.array(y)\n return np.sqrt(np.sum((myx-myy)*(myx-myy)))/(np.var(myx-myy))/abs(np.mean(myx-myy))\n # return np.sqrt(np.sum((myx-myy)*(myx*myy)))\n\n\ndef get_disttance(img,findimg):\n newsize = (15,15)\n find = cv2.resize(findimg,newsize)\n ori_img = cv2.resize(img,newsize)\n my_img = cv2.cvtColor(ori_img,cv2.COLOR_BGR2GRAY)\n my_find = cv2.cvtColor(find,cv2.COLOR_BGR2GRAY)\n pcaimg = mlpy.PCA()\n pcaimg.learn(my_img)\n pca_img = pcaimg.transform(my_img,k=1)\n pca_img = pcaimg.transform_inv(pca_img)\n pcaimg = mlpy.PCA()\n pcaimg.learn(my_find)\n pca_find = pcaimg.transform(my_find,k=1)\n pca_find = pcaimg.transform_inv(pca_find)\n return get_EuclideanDistance(pca_img,pca_find)\n\n\ndef findface(image):\n grayscale = cv.CreateImage((image.width,image.height),8,1)\n cv.CvtColor(image,grayscale,cv.CV_BGR2GRAY)\n cascade = cv.Load(OPCV_PATH+\"/sources/data/haarcascades/haarcascade_frontalface_default.xml\")\n rect = cv.HaarDetectObjects(grayscale,cascade,cv.CreateMemStorage(),1.1,2,cv.CV_HAAR_DO_CANNY_PRUNING,(10,10))\n result = []\n for r in rect:\n result.append([(r[0][0],r[0][1]),(r[0][0]+r[0][2],r[0][1]+r[0][3])])\n return result\n\n\nfn1 = 'benren.jpg'\nfn2 = 'duoren.jpg'\n# fn1 = \"buer.jpg\"\n# fn2 = \"liushishi.jpg\"\nface_test = cv.LoadImage(fn1)\nfacet_result = findface(face_test)\nmyimgt = cv2.imread(fn1)\nmy_img = cv.LoadImage(fn2)\nmyimg = cv2.imread(fn2)\nfaceresut = findface(my_img)\n\nisface1 = get_disttance(myimg[faceresut[0][0][0]:faceresut[0][1][0],faceresut[0][0][1]:faceresut[0][1][1],:],\\\n myimgt[facet_result[0][0][0]:facet_result[0][1][0],facet_result[0][0][1]:facet_result[0][1][1],\\\n :])\n\nisface2 = get_disttance(myimg[faceresut[1][0][0]:faceresut[1][1][0],faceresut[1][0][1]:faceresut[1][1][1],:],\\\n myimgt[facet_result[0][0][0]:facet_result[0][1][0],facet_result[0][0][1]:facet_result[0][1][1],\\\n :])\n\nisface3 = get_disttance(myimg[faceresut[2][0][0]:faceresut[2][1][0],faceresut[2][0][1]:faceresut[2][1][1],:],\\\n myimgt[facet_result[0][0][0]:facet_result[0][1][0],facet_result[0][0][1]:facet_result[0][1][1],\\\n :])\n\n# cv2.rectangle(myimg,faceresut[0][0],faceresut[0][1],(255,0,255))\n# cv2.rectangle(myimgt,facet_result[0][0],faceresut[0][1],(255,0,255))\n\n\n\nif isface1 500:\n actualY += 45\n if score > 700:\n actualY += 15\n if score > 800:\n actualY += 20\n if score > 900:\n actualY += 20\n if score > 1100:\n actualY += 20\n if score > 1200:\n actualY += 30\n if score > 1350:\n actualY += 25\n if score > 1600:\n actualY += 30\n if score > 1700:\n actualY += 35\n if score > 1800:\n actualY += 55\n if score > 1900:\n actualY += 65\n if score > 2000:\n actualY += 65\n for k in range(1900, 2500):\n if score > k:\n actualY += 20\n else:\n break\n click(actualX, actualY)\n previousLane = i\n return\n\n\ndef safeguard():\n mousePos = queryMousePosition()\n return mousePos.x > gameCoords[0]\n\n\ndef start_the_game():\n for x in [2720, 2860, 3000, 3140]:\n click(x, 600)\n\n\ndef play_the_game():\n\n startTime = time.time()\n # print(startTime)\n screen = np.array(ImageGrab.grab(bbox=gameCoords))\n screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)\n clickOnFirstBlock(screen)\n # print(\"Frame took {} seconds. Up to frame no {}\".format(\n # (time.time() - startTime), \"FUCK YOU\"))\n # else:\n # if mousePos.x < 0:\n # score = 0\n # while True:\n # mousePos = queryMousePosition()\n # if gameCoords[2] < mousePos.x:\n # break\n\n\nif __name__ == '__main__':\n start_the_game()\n while safeguard() is True:\n startTime = time.time()\n screen = np.array(ImageGrab.grab(bbox=gameCoords))\n screen = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)\n clickOnFirstBlock(screen)\n # print(\"Frame took {} seconds. Up to frame no {}\".format(\n # (time.time() - startTime), \"FUCK YOU\"))\n","sub_path":"main4.py","file_name":"main4.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"335583514","text":"create_request_schema = {\n \"title\": \"JSON Schema for models request\",\n \"type\": \"object\",\n \"properties\": {\n \"name\": {\n \"description\": \"The name of the model\",\n \"type\": \"string\",\n \"minLength\": 1,\n },\n \"version\": {\n \"description\": \"The version of the model\",\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"id\": {\n \"description\": \"The ID of the Google Drive file\",\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"async_request\": {\n \"description\": \"If the request should be asynchrony (true) or synchrony (false)\",\n \"type\": \"boolean\",\n }\n },\n \"required\": [\"name\", \"version\", \"id\"],\n \"additionalProperties\": False\n}\n","sub_path":"src/services/file_manager/schemas/create_request_schema.py","file_name":"create_request_schema.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"69274112","text":"# -*- coding: utf-8 -*-\n\nfrom flask import Blueprint\nfrom flask import redirect\nfrom flask import render_template\nfrom flask import request\nfrom flask import session\n\nfrom outils.outils import utilisateur_connecte\n\nmodule = Blueprint('routes', __name__, template_folder=\"gabarits\")\n\n@module.route('/', methods=['GET'])\ndef affiche_page_acceuil():\n return render_template('squelette.html',\n url_a_obtenir=\"acceuil/\",\n titre=\"Accueil - Nippongo\",\n description=\"Apprenez le japonais en ligne avec Nippongo !\")\n\n\n@module.route('/api/acceuil/', methods=['GET'])\ndef affiche_page_acceuil_api():\n return render_template('accueil.html')\n\n\n@module.route('/apprendre/', methods=['GET'])\ndef affiche_page_apprendre():\n if not utilisateur_connecte():\n return redirect('/')\n\n return render_template('squelette.html',\n url_a_obtenir=\"apprendre/\",\n titre=\"Apprendre - Nippongo\",\n description=\"Apprenez le japonais en ligne avec Nippongo !\")\n\n\n@module.route('/apprendre/hiragana/', methods=['GET'])\ndef affiche_page_apprendre_hiragana():\n if not utilisateur_connecte():\n return redirect('/')\n\n return render_template('squelette.html',\n url_a_obtenir=\"apprendre/hiragana/\",\n titre=\"Apprendre Hiragana - Nippongo\",\n description=\"Apprenez les hiraganas en ligne avec Nippongo !\")\n\n\n@module.route('/apprendre/katakana/', methods=['GET'])\ndef affiche_page_apprendre_katakana():\n if not utilisateur_connecte():\n return redirect('/')\n\n return render_template('squelette.html',\n url_a_obtenir=\"apprendre/katakana/\",\n titre=\"Apprendre Katakana - Nippongo\",\n description=\"Apprenez les katakanas en ligne avec Nippongo !\")\n\n\n@module.route('/apprendre/kanji/', methods=['GET'])\ndef affiche_page_apprendre_kanji():\n if not utilisateur_connecte():\n return redirect('/')\n\n return render_template('squelette.html',\n url_a_obtenir=\"apprendre/kanji/?niveau=\"+request.args.get('niveau'),\n titre=\"Apprendre Kanji - Nippongo\",\n description=\"Apprenez les kanjis en ligne avec Nippongo !\")\n\n\n@module.route('/explorer/', methods=['GET'])\ndef affiche_page_acceuil_explorer():\n url_a_obtenir = \"explorer/\"\n lettre = request.args.get('l')\n\n if lettre:\n url_a_obtenir += \"?l=\" + lettre\n\n return render_template('squelette.html',\n url_a_obtenir=url_a_obtenir,\n titre=\"Exploration Kanji/Kana - Nippongo\",\n description=\"Explorer les kanjis et kanas en ligne avec Nippongo.\")\n\n\n@module.route('/dessiner//', methods=['GET'])\ndef affiche_page_dessine(valeur=None):\n return render_template('squelette.html',\n url_a_obtenir=\"dessiner/\"+valeur+\"/\",\n titre=u\"Dessiner {} - Nippongo\".format(valeur),\n description=u\"Dessiner {} en ligne avec Nippongo.\".format(valeur))\n\n#### Compte utilisateur\n\n\n@module.route('/connexion/', methods=['GET'])\ndef affiche_page_connexion():\n return render_template('squelette.html',\n url_a_obtenir=\"connexion/\",\n titre=u\"Connexion - Nippongo\",\n description=u\"Page de connection au compte Nippongo.\")\n\n\n@module.route('/deconnexion/', methods=['GET'])\ndef affiche_page_deconnexion():\n session.pop('utilisateur', None)\n return redirect('/')\n\n\n@module.route('/creer_compte/', methods=['GET'])\ndef affiche_page_creer_compte():\n return render_template('squelette.html',\n url_a_obtenir=\"creer_compte/\",\n titre=u\"Créer un compte utilisateur - Nippongo\",\n description=u\"Création d'un compte utilisateur sur Nippongo.\")\n\n\n@module.route('/confirmer_compte//', methods=['GET'])\ndef affiche_page_confirme_creation_compte(empreinte):\n return render_template('squelette.html',\n url_a_obtenir=\"confirmer_compte/\"+empreinte+\"/\",\n titre=u\"Confirmation du compte utilisateur - Nippongo\",\n description=u\"Confirmation d'un compte utilisateur sur Nippongo.\")\n\n\n@module.route('/compte/', methods=['GET'])\ndef affiche_page_compte():\n if not utilisateur_connecte():\n return render_template(\"message.html\",\n entete=u\"Compte utilisateur\",\n message=u\"Vous devez être connecté pour avoir accès à cette page !\")\n\n return render_template('squelette.html',\n url_a_obtenir=\"compte/\",\n titre=u\"Compte utilisateur - Nippongo\",\n description=u\"Les informations de votre compte.\")\n","sub_path":"npng/routes/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"287418705","text":"from Datos import Datos\nfrom EstrategiaParticionado import ValidacionSimple\nfrom Clasificador import ClasificadorAdaline\nfrom Clasificador import ClasificadorPerceptron\nimport pylab as pl\n\n############################################################################\n## CLASIFICACION DE PROBLEMA 2 NO ETIQUETADOS\n############################################################################\ndat1 = Datos(\"problema_real2.txt\", True)\ndat2 = Datos(\"problema_real2_no_etiquetados.txt\", True)\ndatos_train = dat1.datos\ndatos_test = dat2.datos\n############################################################################\n## PERCEPTRON\n############################################################################\n\nclas1 = ClasificadorPerceptron()\nclas1.entrenamiento(datos_train)\npred = clas1.clasifica(datos_test)\n\nfile = open('predicciones_perceptron_no_clasificados.txt', 'w')\nfile.write(\"PrediccionNoEtiquetada\")\nfor i in range(0, pred.__len__()):\n file.write(str(pred[i]))\nfile.close()\n\n############################################################################\n## ADALINE\n############################################################################\n\nclas2 = ClasificadorAdaline()\nclas2.entrenamiento(datos_train)\npred = clas2.clasifica(datos_test)\n\nfile = open('predicciones_adaline_no_clasificados.txt', 'w')\nfile.write(\"PrediccionNoEtiquetada\")\nfor i in range(0, pred.__len__()):\n file.write(str(pred[i]))\nfile.close()\n\n","sub_path":"Classification Engines/MultiLayer-Perceptron/no_etiquetados.py","file_name":"no_etiquetados.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"544051097","text":"\n\nfrom xai.brain.wordbase.nouns._vagina import _VAGINA\n\n#calss header\nclass _VAGINAE(_VAGINA, ):\n\tdef __init__(self,): \n\t\t_VAGINA.__init__(self)\n\t\tself.name = \"VAGINAE\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"vagina\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_vaginae.py","file_name":"_vaginae.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"129576201","text":"import os\n\nfrom js9 import j\n\napps_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nif __name__ == '__main__':\n server = j.servers.gedis2.configure(\n instance=\"{{instance}}\",\n port={{config.port}},\n host=\"{{config.host}}\",\n secret=\"{{config.secret_}}\",\n apps_dir=apps_dir\n )\n\n server.start()\n\n cl = j.clients.gedis2.configure(\n instance=\"{{instance}}\",\n host=\"{{config.host}}\",\n port={{config.port}},\n secret=\"{{config.secret_}}\",\n apps_dir=apps_dir,\n ssl=True,\n ssl_cert_file=\"\"\n )\n\n\n o=cl.models.test_gedis2_cmd1.new()\n o.cmd.name=\"aname\"\n o.cmd2.name=\"aname2\"\n o2=cl.models.test_gedis2_cmd1.set(o)\n o3=cl.models.test_gedis2_cmd1.set(o2) #make sure id stays same, id should be 1 & stay 1\n\n assert o2.id==o3.id\n\n o4=cl.models.test_gedis2_cmd1.get(o3.id)\n\n assert o3.ddict==o4.ddict\n\n res = cl.system.test_nontyped(\"name\", 10)\n assert j.data.serializer.json.loads(res) == ['name', 10]\n\n s = j.data.schema.schema_from_url('{{instance}}.system.test.in')\n o = s.new()\n o.name = \"aname\"\n o.nr = 1\n\n res = cl.system.test(\"aname\", 1)\n\n s = j.data.schema.schema_from_url('{{instance}}.system.test.out')\n\n o2 = s.get(capnpbin=res.data)\n\n assert o.name == o2.name\n assert cl.system.ping() == b'PONG'\n assert cl.system.ping_bool() == 1\n\n print('\\n\\n***************')\n print(' OK')\n print('***************\\n\\n')","sub_path":"JumpScale9RecordChain/servers/gedis2/templates/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"70600877","text":"import numpy as np\nfrom acl_model import Model\nimport matplotlib.pyplot as plt\nimport pickle\n\n# open .om CNN model\ndevice_id = 1\nmodel_path = \"UTI_to_STFT_CNN_aipp.om\"\nmodel = Model(device_id, model_path, 64, 128)\n\n# load input ultrasound data (grayscale images)\nn_lines = 64\nn_pixels_reduced = 128\nult_data = np.fromfile('20180223_spkr048_1432.ult128', dtype='uint8')\nult_data = np.reshape(ult_data, (-1, n_lines, n_pixels_reduced))\n\n# restructure input data to 3 channels\nult_data_3d = np.empty((len(ult_data), n_lines, n_pixels_reduced, 3), dtype='uint8')\nult_data_3d[:, :, :, 0] = ult_data\nult_data_3d[:, :, :, 1] = ult_data\nult_data_3d[:, :, :, 2] = ult_data\n\n# predict UTI-to-STFT\nmelspec_pred_all = np.empty((len(ult_data), 80))\nfor i in range(len(ult_data)):\n melspec_pred = model.run(ult_data_3d[i])\n melspec_pred_all[i] = melspec_pred[0]\n\n# save predicted mel-spectrogram\nplt.figure(figsize=(10,5))\nplt.imshow(np.rot90(melspec_pred_all))\nplt.gray()\nplt.savefig('melspec_pred_all_1432.png')\nplt.close()\n\n\n\n\n","sub_path":"UTI_to_STFT_huawei.py","file_name":"UTI_to_STFT_huawei.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"553111655","text":"\"\"\"Test CoM admittance control as described in paper.\"\"\"\nfrom time import sleep\n\nfrom dynamic_graph.sot_talos_balance.utils.run_test_utils import (\n ask_for_confirmation,\n run_ft_calibration,\n run_test,\n runCommandClient,\n)\n\ntry:\n # Python 2\n input = raw_input # noqa\nexcept NameError:\n pass\n\nrun_test(\"appli_dcmZmpCopControl.py\")\n\nrun_ft_calibration(\"robot.ftc\")\ninput(\"Wait before running the test\")\n\n# Connect ZMP reference and reset controllers\nprint(\"Set controller\")\nrunCommandClient(\"plug(robot.zmp_estimator.emergencyStop,robot.cm.emergencyStop_zmp)\")\nrunCommandClient(\n \"plug(robot.distribute.emergencyStop,robot.cm.emergencyStop_distribute)\"\n)\nrunCommandClient(\"plug(robot.distribute.zmpRef,robot.com_admittance_control.zmpDes)\")\nrunCommandClient(\n \"robot.com_admittance_control.setState(robot.wp.comDes.value,[0.0,0.0,0.0])\"\n)\nrunCommandClient(\"robot.com_admittance_control.Kp.value = Kp_adm\")\nrunCommandClient(\"robot.rightAnkleController.gainsXY.value = Kp_ankles\")\nrunCommandClient(\"robot.leftAnkleController.gainsXY.value = Kp_ankles\")\nrunCommandClient(\"robot.dcm_control.resetDcmIntegralError()\")\nrunCommandClient(\"robot.dcm_control.Ki.value = Ki_dcm\")\n\nc = ask_for_confirmation(\"Execute a sinusoid?\")\nif c:\n print(\"Putting the robot in position...\")\n runCommandClient(\"robot.comTrajGen.move(1,-0.025,1.0)\")\n sleep(1.0)\n print(\"Robot is in position!\")\n\n c2 = ask_for_confirmation(\"Confirm executing the sinusoid?\")\n if c2:\n print(\"Executing the sinusoid...\")\n runCommandClient(\"robot.comTrajGen.startSinusoid(1,0.025,2.0)\")\n print(\"Sinusoid started!\")\n else:\n print(\"Not executing the sinusoid\")\n\n c3 = ask_for_confirmation(\"Put the robot back?\")\n if c3:\n print(\"Stopping the robot...\")\n runCommandClient(\"robot.comTrajGen.stop(1)\")\n sleep(5.0)\n print(\"Putting the robot back...\")\n runCommandClient(\"robot.comTrajGen.move(1,0.0,1.0)\")\n sleep(1.0)\n print(\"The robot is back in position!\")\n else:\n print(\"Not putting the robot back\")\nelse:\n print(\"Not executing the sinusoid\")\n\nc = ask_for_confirmation(\"Raise the foot?\")\nif c:\n print(\"Putting the robot in position...\")\n runCommandClient(\"robot.comTrajGen.move(1,-0.08,10.0)\")\n runCommandClient(\"robot.rhoTrajGen.move(0,0.4,10.0)\")\n sleep(10.0)\n print(\"Robot is in position!\")\n\n c2 = ask_for_confirmation(\"Confirm raising the foot?\")\n if c2:\n print(\"Raising the foot...\")\n runCommandClient(\"robot.distribute.phase.value = -1\")\n runCommandClient(\"h = robot.dynamic.LF.value[2][3]\")\n runCommandClient(\"robot.lfTrajGen.move(2,h+0.05,10.0)\")\n sleep(10.0)\n print(\"Foot has been raised!\")\n c3 = ask_for_confirmation(\"Put the foot back?\")\n else:\n print(\"Not raising the foot\")\n c3 = False\n\n if c3:\n print(\"Putting the foot back...\")\n runCommandClient(\"robot.lfTrajGen.move(2,h,10.0)\")\n sleep(10.0)\n runCommandClient(\"robot.distribute.phase.value = 0\")\n print(\"The foot is back in position!\")\n else:\n print(\"Not putting the foot back\")\n\n if c3 or not c2:\n c4 = ask_for_confirmation(\"Put the robot back?\")\n else:\n c4 = False\n\n if c4:\n print(\"Putting the robot back...\")\n runCommandClient(\"robot.comTrajGen.move(1,0.0,10.0)\")\n runCommandClient(\"robot.rhoTrajGen.move(0,0.5,10.0)\")\n sleep(10.0)\n print(\"The robot is back in position!\")\nelse:\n print(\"Not raising the foot\")\n\n# raw_input(\"Wait before dumping the data\")\n\n# runCommandClient('dump_tracer(robot.tracer)')\n","sub_path":"src/dynamic_graph/sot_talos_balance/test/test_dcmZmpCopControl.py","file_name":"test_dcmZmpCopControl.py","file_ext":"py","file_size_in_byte":3661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"439360574","text":"#text='... «наивный» - <есть> натуральный, природный, не обработанный искусственными условностями цивилизации. Так что если наша культура есть продолжение природы, её язык (по распространенному мнению философов), её заявление о себе, то в наивном человеке и его слове - это прямейше, спонтанно, без опосредованных звеньев... — Георгий Гачев, «Плюсы и минусы наивного философствования»'\r\n\r\ndef clear_text(text, trash_tokens):\r\n #while len(text) > 0 and text[0] in trash_tokens:\r\n #text=text[1:]\r\n text=text.strip(trash_tokens)\r\n return text\r\n\r\n\r\n\r\ndef get_words(text):\r\n\r\n trash_tokens='?/,.;:-_=+!*«»<>'\r\n tokens=text.split()\r\n good_tokens=[]\r\n for token in tokens:\r\n clean_token=clear_text(token, trash_tokens)\r\n if clean_token != '':\r\n clean_token=clean_token.lower()\r\n good_tokens.append(clean_token)\r\n return good_tokens\r\n\r\ndef main():\r\n filename='C:\\\\Users\\\\student\\\\Desktop\\\\book.txt'\r\n DASH='—'\r\n list_of_authors=[]\r\n \r\n with open(filename, encoding='utf-8') as fid:\r\n for line in fid:\r\n line=line.strip()\r\n parts=line.split(DASH)\r\n quote=parts[0]\r\n author=parts[1]\r\n\r\n quote_words=get_words(quote)\r\n\r\n if 'разум' in quote_words:\r\n list_of_authors.append(author)\r\n print('word разум appears ', len(list_of_authors), 'times')\r\n print(', ' .join(list_of_authors))\r\n \r\n\r\n_name_=input('input command: ')\r\nif _name_=='_main_':\r\n main()\r\n","sub_path":"чемодан2.py","file_name":"чемодан2.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"333808872","text":"import traceback\n\nfrom flask import current_app, request\nfrom flask_webapi.utils.mimetypes import MimeType\nfrom werkzeug.exceptions import HTTPException\nfrom . import filters, results, status\nfrom .exceptions import APIException\nfrom .utils import collections, reflect\n\n\nclass ActionContext:\n \"\"\"\n Represents a func in the View that should be\n treated as a Flask view.\n\n :param WebAPI api: The Flask WebAPI instance.\n :param ActionDescriptor descriptor: The action descriptor.\n :param tuple args: The list of arguments provided by Flask.\n :param dict kwargs: The dict of arguments provided by Flask.\n \"\"\"\n\n def __init__(self, api, descriptor, args, kwargs):\n self.api = api\n self.app = api.app\n self.descriptor = descriptor\n\n self.object_result_factory = api.object_result_factory\n self.object_result_executor = api.object_result_executor\n\n self.filters = list(descriptor.filters)\n self.input_formatters = list(api.input_formatters)\n self.output_formatters = list(api.output_formatters)\n self.value_providers = dict(api.value_providers)\n\n self.args = args\n self.kwargs = kwargs\n self.result = None\n self.exception = None\n self.exception_handled = False\n self.response = self.app.response_class()\n\n\nclass ActionDescriptor:\n \"\"\"\n Represents an action.\n \"\"\"\n def __init__(self):\n self.func = None\n self.view_class = None\n self.filters = []\n\n\nclass ActionDescriptorBuilder:\n \"\"\"\n Creates instances of `ActionDescriptor`.\n \"\"\"\n\n def build(self, func, view_class, api):\n \"\"\"\n Creates a instance of `ActionDescriptor`\n from the given parameters.\n :param func: The function.\n :param view_class: The class which the `func` belongs to.\n :param WebAPI api: The Flask WebAPI.\n :return: The instance of `ActionDescriptor`.\n \"\"\"\n if not reflect.has_self_parameter(func):\n func = reflect.func_to_method(func)\n\n descriptor = ActionDescriptor()\n descriptor.func = func\n descriptor.view_class = view_class\n\n descriptor.filters = self._get_filters(getattr(func, 'filters', []),\n getattr(view_class, 'filters', []),\n api.filters)\n\n return descriptor\n\n def _get_filters(self, action_filters, view_filters, api_filters):\n \"\"\"\n Gets a list of filters ordered by order of execution.\n :param action_filters: The filters from action.\n :param view_filters: The filters from view.\n :param api_filters: The filters from `WebAPI`.\n :return: The list of filters.\n \"\"\"\n filters = sorted(action_filters + view_filters + api_filters, key=lambda x: x.order)\n\n filter_matched = []\n\n for filter in filters:\n if filter.allow_multiple or not [f for f in filter_matched if type(f) == type(filter)]:\n filter_matched.insert(0, filter)\n\n return filter_matched\n\n\nclass ActionExecutor:\n \"\"\"\n Responsible to execute an action and its filters.\n \"\"\"\n\n def execute(self, context):\n \"\"\"\n Executes an action with all its filters.\n :param context: The action context.\n :return: A `flask.Response` instance.\n \"\"\"\n\n try:\n context.cursor = _FilterCursor(context.filters)\n self._execute_authentication_filters(context)\n\n context.cursor.reset()\n self._execute_authorization_filters(context)\n\n context.cursor.reset()\n self._execute_resource_filters(context)\n except Exception as e:\n context.exception = e\n self._handle_exception(context)\n\n def _handle_exception(self, context):\n \"\"\"\n Handles any unhandled error that occurs\n and creates a proper response for it.\n :param ActionContext context: The action context.\n \"\"\"\n if isinstance(context.exception, APIException):\n message = context.exception\n elif isinstance(context.exception, HTTPException):\n message = APIException(context.exception.description)\n message.status_code = context.exception.code\n else:\n debug = current_app.config.get('DEBUG')\n message = APIException(traceback.format_exc()) if debug else APIException()\n context.app.logger.error(traceback.format_exc())\n\n result = results.ObjectResult({'errors': message.denormalize()}, status_code=message.status_code)\n result.execute(context)\n\n def _execute_authentication_filters(self, context):\n \"\"\"\n Executes all authentication filters for the given action.\n :param context: The action context.\n \"\"\"\n if context.result is not None:\n self._execute_action_result(context)\n return\n\n cursor = context.cursor\n\n filter = cursor.get_next(filters.AuthenticationFilter)\n\n if filter:\n filter.on_authentication(context)\n self._execute_authentication_filters(context)\n\n def _execute_authorization_filters(self, context):\n \"\"\"\n Executes all authorization filters for the given action.\n :param context: The action context.\n \"\"\"\n if context.result is not None:\n self._execute_action_result(context)\n return\n\n cursor = context.cursor\n\n filter = cursor.get_next(filters.AuthorizationFilter)\n\n if filter:\n filter.on_authorization(context)\n self._execute_authorization_filters(context)\n\n def _execute_resource_filters(self, context):\n \"\"\"\n Executes all resource filters for the given action.\n :param context: The action context.\n \"\"\"\n if context.result is not None:\n self._execute_action_result(context)\n return\n\n cursor = context.cursor\n\n filter = cursor.get_next(filters.ResourceFilter)\n\n if filter:\n filter.on_resource_execution(context, self._execute_resource_filters)\n else:\n cursor.reset()\n\n # >> ExceptionFilters >> ActionFilters >> Action\n self._execute_exception_filters(context)\n\n if context.exception and not context.exception_handled:\n raise context.exception\n\n cursor.reset()\n self._execute_result_filters(context)\n\n def _execute_exception_filters(self, context):\n \"\"\"\n Executes all exception filters for the given action.\n :param context: The action context.\n \"\"\"\n if context.result is not None:\n return\n\n cursor = context.cursor\n\n filter = cursor.get_next(filters.ExceptionFilter)\n\n if filter:\n self._execute_exception_filters(context)\n\n if context.exception and not context.exception_handled:\n filter.on_exception(context)\n else:\n cursor.reset()\n\n try:\n self._execute_action_filters(context)\n except Exception as e:\n context.exception = e\n\n def _execute_action_filters(self, context):\n \"\"\"\n Executes all action filters for the given action.\n :param context: The action context.\n \"\"\"\n if context.result is not None:\n return\n\n cursor = context.cursor\n\n filter = cursor.get_next(filters.ActionFilter)\n\n if filter:\n filter.on_action_execution(context, self._execute_action_filters)\n else:\n descriptor = context.descriptor\n view = descriptor.view_class()\n result = descriptor.func(view, *context.args, **context.kwargs)\n\n if isinstance(result, context.app.response_class):\n context.response = result\n elif isinstance(result, results.ActionResult):\n context.result = result\n else:\n object_result_factory = context.object_result_factory\n context.result = object_result_factory.create(result, context)\n\n def _execute_result_filters(self, context):\n \"\"\"\n Executes all result filters for the given action.\n :param context: The action context.\n \"\"\"\n if context.result is None:\n return\n\n cursor = context.cursor\n\n filter = cursor.get_next(filters.ResultFilter)\n\n if filter:\n filter.on_result_execution(context, self._execute_result_filters)\n else:\n self._execute_action_result(context)\n\n def _execute_action_result(self, context):\n context.result.execute(context)\n\n\nclass ObjectResultExecutor:\n def execute(self, context, result):\n value = result.value\n\n if result.status_code is None:\n context.response.status_code = 204 if value is None else 200\n else:\n context.response.status_code = result.status_code\n\n if value is None:\n return\n\n if result.schema:\n if collections.is_collection(value):\n value = result.schema.dumps(value)\n else:\n value = result.schema.dump(value)\n\n formatter_pair = self._select_output_formatter(context)\n\n if formatter_pair is None:\n context.response.status_code = status.HTTP_406_NOT_ACCEPTABLE\n else:\n formatter, mimetype = formatter_pair\n formatter.write(context.response, value, mimetype)\n\n def _select_output_formatter(self, context, force=False):\n \"\"\"\n Selects the appropriated formatter that matches to the request accept header.\n :param context: The action context.\n :param force: If set to `True` selects the first formatter when the appropriated is not found.\n :return: A tuple with renderer and the mimetype.\n \"\"\"\n formatters = context.output_formatters\n\n for mimetype in self._get_accept_list():\n accept_mimetype = MimeType.parse(mimetype)\n for formatter in formatters:\n if accept_mimetype.match(formatter.mimetype):\n return formatter, formatter.mimetype.replace(params=accept_mimetype.params)\n\n if force:\n return formatters[0], formatters[0].mimetype\n\n return None\n\n def _get_accept_list(self):\n \"\"\"\n Given the incoming request, return a list of accepted media type strings.\n \"\"\"\n header = request.environ.get('HTTP_ACCEPT') or '*/*'\n return [token.strip() for token in header.split(',')]\n\n\nclass ObjectResultFactory:\n def create(self, value, context):\n object_result_filter = None\n\n for f in context.filters:\n if isinstance(f, filters.ObjectResultFilter):\n object_result_filter = f\n break\n\n schema = None\n status_code = None\n\n if object_result_filter:\n schema = object_result_filter.schema\n status_code = object_result_filter.status_code\n\n return results.ObjectResult(value, schema=schema, status_code=status_code)\n\n\nclass _FilterCursor:\n \"\"\"\n Internal class to move across the filters.\n \"\"\"\n def __init__(self, filters):\n self._index = 0\n self._filters = filters\n\n def get_next(self, filter_type):\n while self._index < len(self._filters):\n filter = self._filters[self._index]\n\n self._index += 1\n\n if isinstance(filter, filter_type):\n return filter\n\n return None\n\n def reset(self):\n self._index = 0\n","sub_path":"flask_webapi/internal.py","file_name":"internal.py","file_ext":"py","file_size_in_byte":11696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"236281637","text":"import pytest\n\nfrom plenum.common.event_bus import ExternalBus\nfrom plenum.test.greek import genNodeNames\nfrom plenum.test.helper import MockTimer\nfrom plenum.test.simulation.sim_network import SimNetwork\nfrom plenum.test.simulation.sim_random import DefaultSimRandom\nfrom plenum.test.test_event_bus import SomeMessage, create_some_message\n\n\nNODE_COUNT = 5\n\n\nclass TestNode:\n def __init__(self, name: str, network: ExternalBus):\n self.name = name\n self.network = network\n self.received = []\n\n network.subscribe(SomeMessage, self.process_some_message)\n\n def process_some_message(self, message: SomeMessage, frm: str):\n self.received.append((message, frm))\n\n\n@pytest.fixture\ndef mock_timer():\n return MockTimer()\n\n\n@pytest.fixture\ndef test_nodes(mock_timer):\n random = DefaultSimRandom()\n net = SimNetwork(mock_timer, random)\n return [TestNode(name, net.create_peer(name)) for name in genNodeNames(NODE_COUNT)]\n\n\n@pytest.fixture(params=range(NODE_COUNT))\ndef some_node(request, test_nodes):\n return test_nodes[request.param]\n\n\n@pytest.fixture(params=range(NODE_COUNT-1))\ndef other_node(request, test_nodes, some_node):\n available_nodes = [node for node in test_nodes\n if node != some_node]\n return available_nodes[request.param]\n\n\n@pytest.fixture(params=range(NODE_COUNT-2))\ndef another_node(request, test_nodes, some_node, other_node):\n available_nodes = [node for node in test_nodes\n if node not in [some_node, other_node]]\n return available_nodes[request.param]\n\n\ndef test_sim_network_broadcast(mock_timer, test_nodes, some_node):\n should_receive = [node for node in test_nodes if node != some_node]\n\n message = create_some_message()\n some_node.network.send(message)\n\n # Make sure messages are not delivered immediately\n for node in test_nodes:\n assert not node.received\n\n # Make sure messages are delivered eventually, but not to sending node\n mock_timer.run_to_completion()\n assert not some_node.received\n for node in should_receive:\n assert node.received == [(message, some_node.name)]\n\n\ndef test_sim_network_unicast(mock_timer, test_nodes, some_node, other_node):\n should_not_receive = [node for node in test_nodes if node != other_node]\n\n message = create_some_message()\n some_node.network.send(message, other_node.name)\n\n # Make sure messages are not delivered immediately\n for node in test_nodes:\n assert not node.received\n\n # Make sure message is delivered only to recipient\n mock_timer.run_to_completion()\n assert other_node.received == [(message, some_node.name)]\n for node in should_not_receive:\n assert not node.received\n\n\ndef test_sim_network_multicast(mock_timer, test_nodes, some_node, other_node, another_node):\n should_not_receive = [node for node in test_nodes\n if node not in [other_node, another_node]]\n\n message = create_some_message()\n some_node.network.send(message, [other_node.name, another_node.name])\n\n # Make sure messages are not delivered immediately\n for node in test_nodes:\n assert not node.received\n\n # Make sure message is delivered only to recipient\n mock_timer.run_to_completion()\n assert other_node.received == [(message, some_node.name)]\n assert another_node.received == [(message, some_node.name)]\n for node in should_not_receive:\n assert not node.received\n","sub_path":"plenum/test/simulation/test_sim_network.py","file_name":"test_sim_network.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"413264154","text":"#Given a two list of numbers create a new list such that new list should contain only odd numbers from the first list and even numbers from the second list.\r\nlist1=[1,2,3,4]\r\nlist2=[6,7,8,9]\r\nlist3=[]\r\nfor number in list1: #Adding odd numbers from list1 to list3\r\n if (number%2)!=0 :\r\n list3.append(number)\r\nfor number in list2:\r\n if (number%2)==0 : #Adding even numbers to list3 from list2 \r\n list3.append(number)\r\nprint(list3) #Printing list3","sub_path":"Python/Activities/Activity9.py","file_name":"Activity9.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"49925678","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nfrom django.conf import settings\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom beers import views, models\nfrom beers import models\nfrom beers.forms import RegistrationForm\nfrom registration.backends.default.views import RegistrationView\n\nadmin.autodiscover()\nurlpatterns = patterns(\n '',\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', views.ListBeerView.as_view(),\n {'object_list': settings.MEDIA_ROOT}, ),\n url(r'^edit/(?P\\d+)/$', views.UpdateBeerView.as_view(),\n name='beer-edit', ),\n url(r'^new$', views.CreateBeerView.as_view(),\n name='beer-new', ),\n url(r'^delete/(?P\\d+)/$', views.DeleteBeerView.as_view(),\n name='beer-delete', ),\n url(r'^beer/(?P\\d+)/$', views.BeerView.as_view(),\n name='beer-view', ),\n url(r'^beers/', views.ListBeerView.as_view(), {'object_list': models.Beer.objects.all()}),\n (r'^accounts/', include('registration.backends.simple.urls')),\n)\n\nurlpatterns += staticfiles_urlpatterns()\n\nif settings.DEBUG:\n urlpatterns += patterns(\n 'django.views.static',\n (r'^media/(?P.*)',\n 'serve',\n {'document_root': settings.MEDIA_ROOT}), )","sub_path":"koneser/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"500125580","text":"def instToPrgNum(inst):\n\tmidi_programs = dict((b.lower(), a) for a,b in midi_inst.iteritems())\n\treturn midi_programs[inst.lower()]\n\ndef prgNumToInst(num, p):\n\tif ((p==1 and num==32) or (p==2 and num==0) or (p==3 and num==128)):\n\t\treturn midi_inst[num]+' (default)'\n\treturn midi_inst[num]\n\ndef genreToPrgNum(genre):\n\tgenres_list = dict((b.lower(), a) for a,b in genres_programs.iteritems())\n\treturn genres_list[genre.lower()]\n\ndef prgNumToGenre(num):\n\tif (num==0):\n\t\treturn genres_programs[num]+' (default)'\n\treturn genres_programs[num]\n\ndef getBusy(num):\n\tif (num==9):\n\t\treturn busy_list[num]+ ' (default)'\n\treturn busy_list[num]\n\ndef getDyn(num):\n\tif (num==7):\n\t\treturn dyn_list[num]+ ' (default)'\n\treturn dyn_list[num]\n\ndef getWindow(num):\n\tif (num==3):\n\t\treturn window_list[num]+ ' (default)'\n\treturn window_list[num]\n\ndef getStyle(num, p):\n\tif (num==0 and p==0):\n\t\treturn style_list[num][p]+' (default)'\n\treturn style_list[num][p]\n\ndef getTimeSig(num):\n\tif (num==4):\n\t\treturn timesig_list[num]+' (default)'\n\treturn timesig_list[num]\n\ndef speedToPrgNum(speed):\n\treturn scale_tempo[speed]\n\ndef getInstruments():\n\treturn midi_inst.values()\n\ndef getGenres():\n\treturn genres_programs.values()\n\nscale_tempo = {\n\t\t\t\t\t\t'half':0.5,\n\t\t\t\t\t\t'regular':1.0, \n\t\t\t\t\t\t'double':2.0,\n\t\t\t\t\t\t'quadruple':3.0,\n}\n\ngenres_programs = {\n\t\t\t\t\t\t0:'2-beat',\n\t\t\t\t\t\t1:'rock 1',\n\t\t\t\t\t\t2:'rock 2',\n\t\t\t\t\t\t3:'rock 3',\n\t\t\t\t\t\t4:'punk',\n\t\t\t\t\t\t5:'reggae'\n}\n\nbusy_list = {\t\t\t9:'-the busiest!-',\n\t\t\t\t\t\t8:'-damn busy-',\n\t\t\t\t\t\t7:'-officially busy-',\n\t\t\t\t\t\t6:'-gettin\\' busy-',\n\t\t\t\t\t\t5:'-in the middle-',\n\t\t\t\t\t\t4:'-chillin out-',\n\t\t\t\t\t\t3:'-gettin\\' lazy-',\n\t\t\t\t\t\t2:'-probably missed a few-',\n\t\t\t\t\t\t1:'-so NOT busy!-'\n}\n\ndyn_list = {\t\t\t1:'-completely flat!-',\n\t\t\t\t\t\t2:'-almost gone-',\n\t\t\t\t\t\t3:'-gettin\\' flat-',\n\t\t\t\t\t\t4:'-a lot of compression-',\n\t\t\t\t\t\t5:'-in the middle-',\n\t\t\t\t\t\t6:'-good compression-',\n\t\t\t\t\t\t7:'-balanced compression-',\n\t\t\t\t\t\t8:'-a bit of compression-',\n\t\t\t\t\t\t9:'-the slightest compression-',\n\t\t\t\t\t\t10:'-full dynamic range-'\n}\n\nwindow_list = {\t\t\t1:'-the tiniest!-',\n\t\t\t\t\t\t2:'-very small-',\n\t\t\t\t\t\t3:'-small-',\n\t\t\t\t\t\t4:'-medium/small-',\n\t\t\t\t\t\t5:'-medium-',\n\t\t\t\t\t\t6:'-medium/large-',\n\t\t\t\t\t\t7:'-large-',\n\t\t\t\t\t\t8:'-very large-',\n\t\t\t\t\t\t9:'-so huge!-'\n}\n\nstyle_list = {\t\t\t0:['closed', '-in various inversions-'],\n\t\t\t\t\t\t1:['open', '-nicely spread chord-']\n}\n\ntimesig_list = {\t\t3:'-triple-',\n\t\t\t\t\t\t4:'-quadruple-'\n}\n\nmidi_inst = {\t\t\t0:'Acoustic Grand Piano',\n\t\t\t\t\t 1:'Bright Acoustic Piano',\n\t\t\t\t\t 2:'Electric Grand Piano',\n\t\t\t\t\t 3:'Honky-tonk Piano',\n\t\t\t\t\t 4:'Electric Piano 1',\n\t\t\t\t\t 5:'Electric Piano 2',\n\t\t\t\t\t 6:'Harpsichord',\n\t\t\t\t\t 7:'Clavinet',\n\t\t\t\t\t 8:'Celesta',\n\t\t\t\t\t 9:'Glockenspiel',\n\t\t\t\t\t 10:'Music Box',\n\t\t\t\t\t 11:'Vibraphone',\n\t\t\t\t\t 12:'Marimba',\n\t\t\t\t\t 13:'Xylophone',\n\t\t\t\t\t 14:'Tubular Bells',\n\t\t\t\t\t 15:'Dulcimer',\n\t\t\t\t\t 16:'Drawbar Organ',\n\t\t\t\t\t 17:'Percussive Organ',\n\t\t\t\t\t 18:'Rock Organ',\n\t\t\t\t\t 19:'Church Organ',\n\t\t\t\t\t 20:'Reed Organ',\n\t\t\t\t\t 21:'Accordion',\n\t\t\t\t\t 22:'Harmonica',\n\t\t\t\t\t 23:'Tango Accordion',\n\t\t\t\t\t 24:'Acoustic Guitar (nylon)',\n\t\t\t\t\t 25:'Acoustic Guitar (steel)',\n\t\t\t\t\t 26:'Electric Guitar (jazz)',\n\t\t\t\t\t 27:'Electric Guitar (clean)',\n\t\t\t\t\t 28:'Electric Guitar (muted)',\n\t\t\t\t\t 29:'Overdriven Guitar',\n\t\t\t\t\t 30:'Distortion Guitar',\n\t\t\t\t\t 31:'Guitar Harmonics',\n\t\t\t\t\t 32:'Acoustic Bass',\n\t\t\t\t\t 33:'Electric Bass (finger)',\n\t\t\t\t\t 34:'Electric Bass (pick)',\n\t\t\t\t\t 35:'Fretless Bass',\n\t\t\t\t\t 36:'Slap Bass 1',\n\t\t\t\t\t 37:'Slap Bass 2',\n\t\t\t\t\t 38:'Synth Bass 1',\n\t\t\t\t\t 39:'Synth Bass 2',\n\t\t\t\t\t 40:'Violin',\n\t\t\t\t\t 41:'Viola',\n\t\t\t\t\t 42:'Cello',\n\t\t\t\t\t 43:'Contrabass',\n\t\t\t\t\t 44:'Tremolo Strings',\n\t\t\t\t\t 45:'Pizzicato Strings',\n\t\t\t\t\t 46:'Orchestral Harp',\n\t\t\t\t\t 47:'Timpani',\n\t\t\t\t\t 48:'String Ensemble 1',\n\t\t\t\t\t 49:'String Ensemble 2',\n\t\t\t\t\t 50:'Synth Strings 1',\n\t\t\t\t\t 51:'Synth Strings 2',\n\t\t\t\t\t 52:'Choir Aahs',\n\t\t\t\t\t 53:'Voice Oohs',\n\t\t\t\t\t 54:'Synth Choir',\n\t\t\t\t\t 55:'Orchestra Hit',\n\t\t\t\t\t 56:'Trumpet',\n\t\t\t\t\t 57:'Trombone',\n\t\t\t\t\t 58:'Tuba',\n\t\t\t\t\t 59:'Muted Trumpet',\n\t\t\t\t\t 60:'French Horn',\n\t\t\t\t\t 61:'Brass Section',\n\t\t\t\t\t 62:'Synth Brass 1',\n\t\t\t\t\t 63:'Synth Brass 2',\n\t\t\t\t\t 64:'Soprano Sax',\n\t\t\t\t\t 65:'Alto Sax',\n\t\t\t\t\t 66:'Tenor Sax',\n\t\t\t\t\t 67:'Baritone Sax',\n\t\t\t\t\t 68:'Oboe',\n\t\t\t\t\t 69:'English Horn',\n\t\t\t\t\t 70:'Bassoon',\n\t\t\t\t\t 71:'Clarinet',\n\t\t\t\t\t 72:'Piccolo',\n\t\t\t\t\t 73:'Flute',\n\t\t\t\t\t 74:'Recorder',\n\t\t\t\t\t 75:'Pan Flute',\n\t\t\t\t\t 76:'Blown bottle',\n\t\t\t\t\t 77:'Shakuhachi',\n\t\t\t\t\t 78:'Whistle',\n\t\t\t\t\t 79:'Ocarina',\n\t\t\t\t\t 80:'Lead 1 (square)',\n\t\t\t\t\t 81:'Lead 2 (sawtooth)',\n\t\t\t\t\t 82:'Lead 3 (calliope)',\n\t\t\t\t\t 83:'Lead 4 (chiff)',\n\t\t\t\t\t 84:'Lead 5 (charang)',\n\t\t\t\t\t 85:'Lead 6 (voice)',\n\t\t\t\t\t 86:'Lead 7 (fifths)',\n\t\t\t\t\t 87:'Lead 8 (bass + lead)',\n\t\t\t\t\t 88:'Pad 1 (new age)',\n\t\t\t\t\t 89:'Pad 2 (warm)',\n\t\t\t\t\t 90:'Pad 3 (polysynth)',\n\t\t\t\t\t 91:'Pad 4 (choir)',\n\t\t\t\t\t 92:'Pad 5 (bowed)',\n\t\t\t\t\t 93:'Pad 6 (metallic)',\n\t\t\t\t\t 94:'Pad 7 (halo)',\n\t\t\t\t\t 95:'Pad 8 (sweep)',\n\t\t\t\t\t 96:'FX 1 (rain)',\n\t\t\t\t\t 97:'FX 2 (soundtrack)',\n\t\t\t\t\t 98:'FX 3 (crystal)',\n\t\t\t\t\t 99:'FX 4 (atmosphere)',\n\t\t\t\t\t 100:'FX 5 (brightness)',\n\t\t\t\t\t 101:'FX 6 (goblins)',\n\t\t\t\t\t 102:'FX 7 (echoes)',\n\t\t\t\t\t 103:'FX 8 (sci-fi)',\n\t\t\t\t\t 104:'Sitar',\n\t\t\t\t\t 105:'Banjo',\n\t\t\t\t\t 106:'Shamisen',\n\t\t\t\t\t 107:'Koto',\n\t\t\t\t\t 108:'Kalimba',\n\t\t\t\t\t 109:'Bagpipe',\n\t\t\t\t\t 110:'Fiddle',\n\t\t\t\t\t 111:'Shanai',\n\t\t\t\t\t 112:'Tinkle Bell',\n\t\t\t\t\t 113:'Agogo',\n\t\t\t\t\t 114:'Steel Drums',\n\t\t\t\t\t 115:'Woodblock',\n\t\t\t\t\t 116:'Taiko Drum',\n\t\t\t\t\t 117:'Melodic Tom',\n\t\t\t\t\t 118:'Synth Drum',\n\t\t\t\t\t 119:'Reverse Cymbal',\n\t\t\t\t\t 120:'Guitar Fret Noise',\n\t\t\t\t\t 121:'Breath Noise',\n\t\t\t\t\t 122:'Seashore',\n\t\t\t\t\t 123:'Bird Tweet',\n\t\t\t\t\t 124:'Telephone Ring',\n\t\t\t\t\t 125:'Helicopter',\n\t\t\t\t\t 126:'Applause',\n\t\t\t\t\t 127:'Gunshot',\n\t\t\t\t\t 128:'Drum Set'\n}\n\n'''\n \n 'Piano\\n'\n '\\tAcoustic Grand Piano\\n'\n '\\tBright Acoustic Piano\\n'\n '\\tElectric Grand Piano\\n'\n '\\tHonky-tonk Piano\\n'\n '\\tElectric Piano 1\\n'\n '\\tElectric Piano 2\\n'\n '\\tHarpsichord\\n'\n '\\tClavinet\\n'\n 'Chromatic Percussion\\n'\n '\\tCelesta\\n'\n '\\tGlockenspiel\\n'\n '\\tMusic Box\\n'\n '\\tVibraphone\\n'\n '\\tMarimba\\n'\n '\\tXylophone\\n'\n '\\tTubular Bells\\n'\n '\\tDulcimer\\n'\n 'Organ\\n'\n '\\tDrawbar Organ\\n'\n '\\tPercussive Organ\\n'\n '\\tRock Organ\\n'\n '\\tChurch Organ\\n'\n '\\tReed Organ\\n'\n '\\tAccordion\\n'\n '\\tHarmonica\\n'\n '\\tTango Accordion\\n'\n 'Guitar\\n'\n '\\tAcoustic Guitar (nylon)\\n'\n '\\tAcoustic Guitar (steel)\\n'\n '\\tElectric Guitar (jazz)\\n'\n '\\tElectric Guitar (clean)\\n'\n '\\tElectric Guitar (muted)\\n'\n '\\tOverdriven Guitar\\n'\n '\\tDistortion Guitar\\n'\n '\\tGuitar Harmonics\\n'\n 'Bass\\n'\n '\\tAcoustic Bass\\n'\n '\\tElectric Bass (finger)\\n'\n '\\tElectric Bass (pick)\\n'\n '\\tFretless Bass\\n'\n '\\tSlap Bass 1\\n'\n '\\tSlap Bass 2\\n'\n '\\tSynth Bass 1\\n'\n '\\tSynth Bass 2\\n'\n 'Strings\\n'\n '\\tViolin\\n'\n '\\tViola\\n'\n '\\tCello\\n'\n '\\tContrabass\\n'\n '\\tTremolo Strings\\n'\n '\\tPizzicato Strings\\n'\n '\\tOrchestral Harp\\n'\n '\\tTimpani\\n'\n 'Ensemble\\n'\n '\\tString Ensemble 1\\n'\n '\\tString Ensemble 2\\n'\n '\\tSynth Strings 1\\n'\n '\\tSynth Strings 2\\n'\n '\\tChoir Aahs\\n'\n '\\tVoice Oohs\\n'\n '\\tSynth Choir\\n'\n '\\tOrchestra Hit\\n'\n 'Brass\\n'\n '\\tTrumpet\\n'\n '\\tTrombone\\n'\n '\\tTuba\\n'\n '\\tMuted Trumpet\\n'\n '\\tFrench Horn\\n'\n '\\tBrass Section\\n'\n '\\tSynth Brass 1\\n'\n '\\tSynth Brass 2\\n'\n 'Reed\\n'\n '\\tSoprano Sax\\n'\n '\\tAlto Sax\\n'\n '\\tTenor Sax\\n'\n '\\tBaritone Sax\\n'\n '\\tOboe\\n'\n '\\tEnglish Horn\\n'\n '\\tBassoon\\n'\n '\\tClarinet\\n'\n 'Pipe\\n'\n '\\tPiccolo\\n'\n '\\tFlute\\n'\n '\\tRecorder\\n'\n '\\tPan Flute\\n'\n '\\tBlown bottle\\n'\n '\\tShakuhachi\\n'\n '\\tWhistle\\n'\n '\\tOcarina\\n'\n 'Synth Lead\\n'\n '\\tLead 1 (square)\\n'\n '\\tLead 2 (sawtooth)\\n'\n '\\tLead 3 (calliope)\\n'\n '\\tLead 4 (chiff)\\n'\n '\\tLead 5 (charang)\\n'\n '\\tLead 6 (voice)\\n'\n '\\tLead 7 (fifths)\\n'\n '\\tLead 8 (bass + lead)\\n'\n 'Synth Pad\\n'\n '\\tPad 1 (new age)\\n'\n '\\tPad 2 (warm[disambiguation needed])\\n'\n '\\tPad 3 (polysynth)\\n'\n '\\tPad 4 (choir)\\n'\n '\\tPad 5 (bowed)\\n'\n '\\tPad 6 (metallic)\\n'\n '\\tPad 7 (halo)\\n'\n '\\tPad 8 (sweep)\\n'\n 'Synth Effects\\n'\n '\\tFX 1 (rain)\\n'\n '\\tFX 2 (soundtrack)\\n'\n '\\tFX 3 (crystal)\\n'\n '\\tFX 4 (atmosphere)\\n'\n '\\tFX 5 (brightness)\\n'\n '\\tFX 6 (goblins)\\n'\n '\\tFX 7 (echoes)\\n'\n '\\tFX 8 (sci-fi)\\n'\n 'Ethnic\\n'\n '\\tSitar\\n'\n '\\tBanjo\\n'\n '\\tShamisen\\n'\n '\\tKoto\\n'\n '\\tKalimba\\n'\n '\\tBagpipe\\n'\n '\\tFiddle\\n'\n '\\tShanai\\n'\n 'Sound Effects\\n'\n '\\tGuitar Fret Noise\\n'\n '\\tBreath Noise\\n'\n '\\tSeashore\\n'\n '\\tBird Tweet\\n'\n '\\tTelephone Ring\\n'\n '\\tHelicopter\\n'\n '\\tApplause\\n'\n '\\tGunshot\\n')\n \n print (\"\\nThe valid MIDI PERCUSSION INSTRUMENTS are:\\n\"\n 'Drum-set\\n'\n 'Tinkle Bell\\n'\n 'Agogo\\n'\n 'Steel Drums\\n'\n 'Woodblock\\n'\n 'Taiko Drum\\n'\n 'Melodic Tom\\n'\n 'Synth Drum\\n'\n 'Reverse Cymbal\\n')\n'''\n","sub_path":"CLI/src/functions/dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":10984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"417490695","text":"#pylint: disable=too-many-branches, too-many-statements, too-many-nested-blocks, bare-except, line-too-long\n\"\"\"\n Interface to refl1d\n\"\"\"\nimport logging\nimport re\nimport json\nfrom .refl1d_err_model import parse_single_param\n\ndef update_with_results(fit_problem, par_name, value, error):\n \"\"\"\n Update a mode with a parameter value.\n\n :param FitProblem fit_problem: fit problem object to update\n :param str par_name: parameter name\n :param float value: parameter value\n :param float error: parameter error\n \"\"\"\n toks = par_name.split(' ')\n # The first token is the layer name or top-level parameter name\n if toks[0] == 'intensity':\n fit_problem.reflectivity_model.scale = value\n fit_problem.reflectivity_model.scale_error = error\n elif toks[0] == 'background':\n fit_problem.reflectivity_model.background = value\n fit_problem.reflectivity_model.background_error = error\n elif toks[1] == 'rho':\n if toks[0] == fit_problem.reflectivity_model.front_name:\n fit_problem.reflectivity_model.front_sld = value\n fit_problem.reflectivity_model.front_sld_error = error\n elif toks[0] == fit_problem.reflectivity_model.back_name:\n fit_problem.reflectivity_model.back_sld = value\n fit_problem.reflectivity_model.back_sld_error = error\n else:\n for layer in fit_problem.layers.all():\n if toks[0] == layer.name:\n layer.sld = value\n layer.sld_error = error\n layer.save()\n elif toks[1] == 'thickness':\n for layer in fit_problem.layers.all():\n if toks[0] == layer.name:\n layer.thickness = value\n layer.thickness_error = error\n layer.save()\n elif toks[1] == 'irho':\n for layer in fit_problem.layers.all():\n if toks[0] == layer.name:\n layer.i_sld = value\n layer.i_sld_error = error\n layer.save()\n elif toks[1] == 'interface':\n if toks[0] == fit_problem.reflectivity_model.back_name:\n fit_problem.reflectivity_model.back_roughness = value\n fit_problem.reflectivity_model.back_roughness_error = error\n else:\n for layer in fit_problem.layers.all():\n if toks[0] == layer.name:\n layer.roughness = value\n layer.roughness_error = error\n layer.save()\n fit_problem.save()\n\ndef update_model(content, fit_problem):\n \"\"\"\n Update a model described by a FitProblem object according to the contents\n of a REFL1D log.\n\n :param str content: log contents\n :param FitProblem fit_problem: fit problem object to update\n\n .. note::\n [chisq=23.426(15), nllf=1850.62]\n\n Parameter mean median best [ 68% interval] [ 95% interval]\n\n 1 intensity 1.084(31) 1.0991 1.1000 [ 1.062 1.100] [ 1.000 1.100]\n\n 2 air rho 0.91(91)e-3 0.00062 0.00006 [ 0.0001 0.0017] [ 0.0000 0.0031]\n\n \"\"\"\n start_err_file = False\n start_par_file = False\n found_errors = False\n for line in content.split('\\n'):\n if start_err_file:\n try:\n par_name, value, error = parse_single_param(line)\n if par_name is not None:\n found_errors = True\n update_with_results(fit_problem, par_name, value, error)\n except:\n logging.error(\"Could not parse line %s\", line)\n\n if start_par_file and not found_errors:\n try:\n par_name, value = parse_par_file_line(line)\n if par_name is not None:\n update_with_results(fit_problem, par_name, value, error=0.0)\n except:\n logging.error(\"Could not parse line %s\", line)\n\n # Find chi^2, which comes just before the list of parameters\n if line.startswith('[chi'):\n try:\n result = re.search(r'chisq=([\\d.]*)', line)\n chi2 = result.group(1)\n except:\n chi2 = \"unknown\"\n\n if line.startswith('MODEL_PARAMS_START'):\n start_err_file = True\n if line.startswith('MODEL_PARAMS_END'):\n start_err_file = False\n if line.startswith('MODEL_BEST_VALUES_START'):\n start_par_file = True\n if line.startswith('MODEL_BEST_VALUES_END'):\n start_par_file = False\n\n try:\n chi2_value = float(chi2)\n except:\n chi2_value = None\n return chi2_value\n\ndef extract_data_from_log(log_content):\n \"\"\"\n Extract data from log.\n\n :param log_content: string buffer of the job log\n \"\"\"\n data_block_list = extract_multi_data_from_log(log_content)\n if data_block_list is not None and len(data_block_list) > 0:\n return data_block_list[0][1]\n return None\n\ndef extract_multi_data_from_log(log_content):\n \"\"\"\n Extract data block from a log. For simultaneous fits, an EXPT_START tag\n precedes every block:\n\n EXPT_START 0\n REFL_START\n\n :param str log_content: string buffer of the job log\n \"\"\"\n # Parse out the portion we need\n data_started = False\n data_content = []\n data_block_list = []\n model_names = []\n\n for line in log_content.split('\\n'):\n if line.startswith(\"SIMULTANEOUS\"):\n clean_str = line.replace(\"SIMULTANEOUS \", \"\")\n model_names = json.loads(clean_str)\n if line.startswith(\"REFL_START\"):\n data_started = True\n elif line.startswith(\"REFL_END\"):\n data_started = False\n if len(data_content) > 0:\n data_path = ''\n if len(model_names) > len(data_block_list):\n data_path = model_names[len(data_block_list)]\n data_block_list.append([data_path, '\\n'.join(data_content)])\n data_content = []\n elif data_started is True:\n data_content.append(line)\n return data_block_list\n\ndef extract_sld_from_log(log_content):\n \"\"\"\n Extract a single SLD profile from a REFL1D log.\n\n :param str log_content: string buffer of the job log\n \"\"\"\n data_block_list = extract_multi_sld_from_log(log_content)\n if data_block_list is not None and len(data_block_list) > 0:\n return data_block_list[0][1]\n return None\n\ndef extract_multi_sld_from_log(log_content):\n \"\"\"\n Extract multiple SLD profiles from a simultaneous REFL1D fit.\n\n :param str log_content: string buffer of the job log\n \"\"\"\n # Parse out the portion we need\n data_started = False\n data_content = []\n data_block_list = []\n model_names = []\n\n for line in log_content.split('\\n'):\n if line.startswith(\"SIMULTANEOUS\"):\n clean_str = line.replace(\"SIMULTANEOUS \", \"\")\n model_names = json.loads(clean_str)\n if line.startswith(\"SLD_START\"):\n data_started = True\n elif line.startswith(\"SLD_END\"):\n data_started = False\n if len(data_content) > 0:\n data_path = ''\n if len(model_names) > len(data_block_list):\n data_path = model_names[len(data_block_list)]\n data_block_list.append([data_path, '\\n'.join(data_content)])\n data_content = []\n elif data_started is True:\n data_content.append(line)\n return data_block_list\n\ndef parse_par_file_line(line):\n \"\"\"\n Parse a line from the __model.par file\n\n :param str line: string to be parsed\n \"\"\"\n result = re.search(r'^(.*) ([\\d.-]+)(e?[\\d-]*)', line.strip())\n value_float = None\n par_name = None\n if result is not None:\n par_name = result.group(1).strip()\n value = \"%s%s\" % (result.group(2), result.group(3))\n value_float = float(value)\n value_float = float(\"%g\" % value_float)\n return par_name, value_float\n","sub_path":"web_reflectivity/fitting/parsing/refl1d.py","file_name":"refl1d.py","file_ext":"py","file_size_in_byte":8088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"593731598","text":"# -*- coding: utf8 -*-\n# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Accesses the google.cloud.dialogflow.v2beta1 Intents API.\"\"\"\n\nimport functools\nimport pkg_resources\n\nimport google.api_core.gapic_v1.client_info\nimport google.api_core.gapic_v1.config\nimport google.api_core.gapic_v1.method\nimport google.api_core.grpc_helpers\nimport google.api_core.operation\nimport google.api_core.operations_v1\nimport google.api_core.page_iterator\nimport google.api_core.path_template\nimport google.api_core.protobuf_helpers\n\nfrom dialogflow_v2beta1.gapic import enums\nfrom dialogflow_v2beta1.gapic import intents_client_config\nfrom dialogflow_v2beta1.proto import agent_pb2\nfrom dialogflow_v2beta1.proto import context_pb2\nfrom dialogflow_v2beta1.proto import entity_type_pb2\nfrom dialogflow_v2beta1.proto import intent_pb2\nfrom dialogflow_v2beta1.proto import intent_pb2_grpc\n\nfrom google.longrunning import operations_pb2\nfrom google.protobuf import empty_pb2\nfrom google.protobuf import field_mask_pb2\nfrom google.protobuf import struct_pb2\n\n_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution('dialogflow',\n ).version\n\n\nclass IntentsClient(object):\n \"\"\"\n An intent represents a mapping between input from a user and an action to\n be taken by your application. When you pass user input to the\n ``DetectIntent`` (or\n ``StreamingDetectIntent``) method, the\n Dialogflow API analyzes the input and searches\n for a matching intent. If no match is found, the Dialogflow API returns a\n fallback intent (``is_fallback`` = true).\n\n You can provide additional information for the Dialogflow API to use to\n match user input to an intent by adding the following to your intent.\n\n * **Contexts** - provide additional context for intent analysis. For\n example, if an intent is related to an object in your application that\n plays music, you can provide a context to determine when to match the\n intent if the user input is “turn it off”. You can include a context\n that matches the intent when there is previous user input of\n \\\"play music\\\", and not when there is previous user input of\n \\\"turn on the light\\\".\n * **Events** - allow for matching an intent by using an event name\n instead of user input. Your application can provide an event name and\n related parameters to the Dialogflow API to match an intent. For\n example, when your application starts, you can send a welcome event\n with a user name parameter to the Dialogflow API to match an intent with\n a personalized welcome message for the user.\n * **Training phrases** - provide examples of user input to train the\n Dialogflow API agent to better match intents.\n\n For more information about intents, see the\n `Dialogflow documentation `__.\n \"\"\"\n\n SERVICE_ADDRESS = 'dialogflow.googleapis.com:443'\n \"\"\"The default address of the service.\"\"\"\n\n # The scopes needed to make gRPC calls to all of the methods defined in\n # this service\n _DEFAULT_SCOPES = ('https://www.googleapis.com/auth/cloud-platform', )\n\n # The name of the interface for this client. This is the key used to find\n # method configuration in the client_config dictionary.\n _INTERFACE_NAME = 'google.cloud.dialogflow.v2beta1.Intents'\n\n @classmethod\n def project_agent_path(cls, project):\n \"\"\"Return a fully-qualified project_agent string.\"\"\"\n return google.api_core.path_template.expand(\n 'projects/{project}/agent',\n project=project,\n )\n\n @classmethod\n def intent_path(cls, project, intent):\n \"\"\"Return a fully-qualified intent string.\"\"\"\n return google.api_core.path_template.expand(\n 'projects/{project}/agent/intents/{intent}',\n project=project,\n intent=intent,\n )\n\n @classmethod\n def agent_path(cls, project, agent):\n \"\"\"Return a fully-qualified agent string.\"\"\"\n return google.api_core.path_template.expand(\n 'projects/{project}/agents/{agent}',\n project=project,\n agent=agent,\n )\n\n @classmethod\n def project_path(cls, project):\n \"\"\"Return a fully-qualified project string.\"\"\"\n return google.api_core.path_template.expand(\n 'projects/{project}',\n project=project,\n )\n\n def __init__(self,\n channel=None,\n credentials=None,\n client_config=intents_client_config.config,\n client_info=None):\n \"\"\"Constructor.\n\n Args:\n channel (grpc.Channel): A ``Channel`` instance through\n which to make calls. This argument is mutually exclusive\n with ``credentials``; providing both will raise an exception.\n credentials (google.auth.credentials.Credentials): The\n authorization credentials to attach to requests. These\n credentials identify this application to the service. If none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n client_config (dict): A dictionary of call options for each\n method. If not specified, the default configuration is used.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n \"\"\"\n # If both `channel` and `credentials` are specified, raise an\n # exception (channels come with credentials baked in already).\n if channel is not None and credentials is not None:\n raise ValueError(\n 'The `channel` and `credentials` arguments to {} are mutually '\n 'exclusive.'.format(self.__class__.__name__), )\n\n # Create the channel.\n if channel is None:\n channel = google.api_core.grpc_helpers.create_channel(\n self.SERVICE_ADDRESS,\n credentials=credentials,\n scopes=self._DEFAULT_SCOPES,\n )\n\n # Create the gRPC stubs.\n self.intents_stub = (intent_pb2_grpc.IntentsStub(channel))\n\n # Operations client for methods that return long-running operations\n # futures.\n self.operations_client = (\n google.api_core.operations_v1.OperationsClient(channel))\n\n if client_info is None:\n client_info = (\n google.api_core.gapic_v1.client_info.DEFAULT_CLIENT_INFO)\n client_info.gapic_version = _GAPIC_LIBRARY_VERSION\n\n # Parse out the default settings for retry and timeout for each RPC\n # from the client configuration.\n # (Ordinarily, these are the defaults specified in the `*_config.py`\n # file next to this one.)\n method_configs = google.api_core.gapic_v1.config.parse_method_configs(\n client_config['interfaces'][self._INTERFACE_NAME], )\n\n # Write the \"inner API call\" methods to the class.\n # These are wrapped versions of the gRPC stub methods, with retry and\n # timeout configuration applied, called by the public methods on\n # this class.\n self._list_intents = google.api_core.gapic_v1.method.wrap_method(\n self.intents_stub.ListIntents,\n default_retry=method_configs['ListIntents'].retry,\n default_timeout=method_configs['ListIntents'].timeout,\n client_info=client_info,\n )\n self._get_intent = google.api_core.gapic_v1.method.wrap_method(\n self.intents_stub.GetIntent,\n default_retry=method_configs['GetIntent'].retry,\n default_timeout=method_configs['GetIntent'].timeout,\n client_info=client_info,\n )\n self._create_intent = google.api_core.gapic_v1.method.wrap_method(\n self.intents_stub.CreateIntent,\n default_retry=method_configs['CreateIntent'].retry,\n default_timeout=method_configs['CreateIntent'].timeout,\n client_info=client_info,\n )\n self._update_intent = google.api_core.gapic_v1.method.wrap_method(\n self.intents_stub.UpdateIntent,\n default_retry=method_configs['UpdateIntent'].retry,\n default_timeout=method_configs['UpdateIntent'].timeout,\n client_info=client_info,\n )\n self._delete_intent = google.api_core.gapic_v1.method.wrap_method(\n self.intents_stub.DeleteIntent,\n default_retry=method_configs['DeleteIntent'].retry,\n default_timeout=method_configs['DeleteIntent'].timeout,\n client_info=client_info,\n )\n self._batch_update_intents = google.api_core.gapic_v1.method.wrap_method(\n self.intents_stub.BatchUpdateIntents,\n default_retry=method_configs['BatchUpdateIntents'].retry,\n default_timeout=method_configs['BatchUpdateIntents'].timeout,\n client_info=client_info,\n )\n self._batch_delete_intents = google.api_core.gapic_v1.method.wrap_method(\n self.intents_stub.BatchDeleteIntents,\n default_retry=method_configs['BatchDeleteIntents'].retry,\n default_timeout=method_configs['BatchDeleteIntents'].timeout,\n client_info=client_info,\n )\n\n # Service calls\n def list_intents(self,\n parent,\n language_code=None,\n intent_view=None,\n page_size=None,\n retry=google.api_core.gapic_v1.method.DEFAULT,\n timeout=google.api_core.gapic_v1.method.DEFAULT,\n metadata=None):\n \"\"\"\n Returns the list of all intents in the specified agent.\n\n Example:\n >>> import dialogflow_v2beta1\n >>>\n >>> client = dialogflow_v2beta1.IntentsClient()\n >>>\n >>> parent = client.project_agent_path('[PROJECT]')\n >>>\n >>>\n >>> # Iterate over all results\n >>> for element in client.list_intents(parent):\n ... # process element\n ... pass\n >>>\n >>> # Or iterate over results one page at a time\n >>> for page in client.list_intents(parent, options=CallOptions(page_token=INITIAL_PAGE)):\n ... for element in page:\n ... # process element\n ... pass\n\n Args:\n parent (str): Required. The agent to list all intents from.\n Format: ``projects//agent``.\n language_code (str): Optional. The language to list training phrases, parameters and rich\n messages for. If not specified, the agent's default language is used.\n [More than a dozen\n languages](https://dialogflow.com/docs/reference/language) are supported.\n Note: languages must be enabled in the agent before they can be used.\n intent_view (~dialogflow_v2beta1.types.IntentView): Optional. The resource view to apply to the returned intent.\n page_size (int): The maximum number of resources contained in the\n underlying API response. If page streaming is performed per-\n resource, this parameter does not affect the return value. If page\n streaming is performed per-page, this determines the maximum number\n of resources in a page.\n retry (Optional[google.api_core.retry.Retry]): A retry object used\n to retry requests. If ``None`` is specified, requests will not\n be retried.\n timeout (Optional[float]): The amount of time, in seconds, to wait\n for the request to complete. Note that if ``retry`` is\n specified, the timeout applies to each individual attempt.\n metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n that is provided to the method.\n\n Returns:\n A :class:`~google.gax.PageIterator` instance. By default, this\n is an iterable of :class:`~dialogflow_v2beta1.types.Intent` instances.\n This object can also be configured to iterate over the pages\n of the response through the `options` parameter.\n\n Raises:\n google.api_core.exceptions.GoogleAPICallError: If the request\n failed for any reason.\n google.api_core.exceptions.RetryError: If the request failed due\n to a retryable error and retry attempts failed.\n ValueError: If the parameters are invalid.\n \"\"\"\n if metadata is None:\n metadata = []\n metadata = list(metadata)\n request = intent_pb2.ListIntentsRequest(\n parent=parent,\n language_code=language_code,\n intent_view=intent_view,\n page_size=page_size,\n )\n iterator = google.api_core.page_iterator.GRPCIterator(\n client=None,\n method=functools.partial(\n self._list_intents,\n retry=retry,\n timeout=timeout,\n metadata=metadata),\n request=request,\n items_field='intents',\n request_token_field='page_token',\n response_token_field='next_page_token',\n )\n return iterator\n\n def get_intent(self,\n name,\n language_code=None,\n intent_view=None,\n retry=google.api_core.gapic_v1.method.DEFAULT,\n timeout=google.api_core.gapic_v1.method.DEFAULT,\n metadata=None):\n \"\"\"\n Retrieves the specified intent.\n\n Example:\n >>> import dialogflow_v2beta1\n >>>\n >>> client = dialogflow_v2beta1.IntentsClient()\n >>>\n >>> name = client.intent_path('[PROJECT]', '[INTENT]')\n >>>\n >>> response = client.get_intent(name)\n\n Args:\n name (str): Required. The name of the intent.\n Format: ``projects//agent/intents/``.\n language_code (str): Optional. The language to retrieve training phrases, parameters and rich\n messages for. If not specified, the agent's default language is used.\n [More than a dozen\n languages](https://dialogflow.com/docs/reference/language) are supported.\n Note: languages must be enabled in the agent, before they can be used.\n intent_view (~dialogflow_v2beta1.types.IntentView): Optional. The resource view to apply to the returned intent.\n retry (Optional[google.api_core.retry.Retry]): A retry object used\n to retry requests. If ``None`` is specified, requests will not\n be retried.\n timeout (Optional[float]): The amount of time, in seconds, to wait\n for the request to complete. Note that if ``retry`` is\n specified, the timeout applies to each individual attempt.\n metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n that is provided to the method.\n\n Returns:\n A :class:`~dialogflow_v2beta1.types.Intent` instance.\n\n Raises:\n google.api_core.exceptions.GoogleAPICallError: If the request\n failed for any reason.\n google.api_core.exceptions.RetryError: If the request failed due\n to a retryable error and retry attempts failed.\n ValueError: If the parameters are invalid.\n \"\"\"\n if metadata is None:\n metadata = []\n metadata = list(metadata)\n request = intent_pb2.GetIntentRequest(\n name=name,\n language_code=language_code,\n intent_view=intent_view,\n )\n return self._get_intent(\n request, retry=retry, timeout=timeout, metadata=metadata)\n\n def create_intent(self,\n parent,\n intent,\n language_code=None,\n intent_view=None,\n retry=google.api_core.gapic_v1.method.DEFAULT,\n timeout=google.api_core.gapic_v1.method.DEFAULT,\n metadata=None):\n \"\"\"\n Creates an intent in the specified agent.\n\n Example:\n >>> import dialogflow_v2beta1\n >>>\n >>> client = dialogflow_v2beta1.IntentsClient()\n >>>\n >>> parent = client.project_agent_path('[PROJECT]')\n >>>\n >>> # TODO: Initialize ``intent``:\n >>> intent = {}\n >>>\n >>> response = client.create_intent(parent, intent)\n\n Args:\n parent (str): Required. The agent to create a intent for.\n Format: ``projects//agent``.\n intent (Union[dict, ~dialogflow_v2beta1.types.Intent]): Required. The intent to create.\n If a dict is provided, it must be of the same form as the protobuf\n message :class:`~dialogflow_v2beta1.types.Intent`\n language_code (str): Optional. The language of training phrases, parameters and rich messages\n defined in ``intent``. If not specified, the agent's default language is\n used. [More than a dozen\n languages](https://dialogflow.com/docs/reference/language) are supported.\n Note: languages must be enabled in the agent, before they can be used.\n intent_view (~dialogflow_v2beta1.types.IntentView): Optional. The resource view to apply to the returned intent.\n retry (Optional[google.api_core.retry.Retry]): A retry object used\n to retry requests. If ``None`` is specified, requests will not\n be retried.\n timeout (Optional[float]): The amount of time, in seconds, to wait\n for the request to complete. Note that if ``retry`` is\n specified, the timeout applies to each individual attempt.\n metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n that is provided to the method.\n\n Returns:\n A :class:`~dialogflow_v2beta1.types.Intent` instance.\n\n Raises:\n google.api_core.exceptions.GoogleAPICallError: If the request\n failed for any reason.\n google.api_core.exceptions.RetryError: If the request failed due\n to a retryable error and retry attempts failed.\n ValueError: If the parameters are invalid.\n \"\"\"\n if metadata is None:\n metadata = []\n metadata = list(metadata)\n request = intent_pb2.CreateIntentRequest(\n parent=parent,\n intent=intent,\n language_code=language_code,\n intent_view=intent_view,\n )\n return self._create_intent(\n request, retry=retry, timeout=timeout, metadata=metadata)\n\n def update_intent(self,\n intent,\n language_code,\n update_mask=None,\n intent_view=None,\n retry=google.api_core.gapic_v1.method.DEFAULT,\n timeout=google.api_core.gapic_v1.method.DEFAULT,\n metadata=None):\n \"\"\"\n Updates the specified intent.\n\n Example:\n >>> import dialogflow_v2beta1\n >>>\n >>> client = dialogflow_v2beta1.IntentsClient()\n >>>\n >>> # TODO: Initialize ``intent``:\n >>> intent = {}\n >>>\n >>> # TODO: Initialize ``language_code``:\n >>> language_code = ''\n >>>\n >>> response = client.update_intent(intent, language_code)\n\n Args:\n intent (Union[dict, ~dialogflow_v2beta1.types.Intent]): Required. The intent to update.\n Format: ``projects//agent/intents/``.\n If a dict is provided, it must be of the same form as the protobuf\n message :class:`~dialogflow_v2beta1.types.Intent`\n language_code (str): Optional. The language of training phrases, parameters and rich messages\n defined in ``intent``. If not specified, the agent's default language is\n used. [More than a dozen\n languages](https://dialogflow.com/docs/reference/language) are supported.\n Note: languages must be enabled in the agent, before they can be used.\n update_mask (Union[dict, ~dialogflow_v2beta1.types.FieldMask]): Optional. The mask to control which fields get updated.\n If a dict is provided, it must be of the same form as the protobuf\n message :class:`~dialogflow_v2beta1.types.FieldMask`\n intent_view (~dialogflow_v2beta1.types.IntentView): Optional. The resource view to apply to the returned intent.\n retry (Optional[google.api_core.retry.Retry]): A retry object used\n to retry requests. If ``None`` is specified, requests will not\n be retried.\n timeout (Optional[float]): The amount of time, in seconds, to wait\n for the request to complete. Note that if ``retry`` is\n specified, the timeout applies to each individual attempt.\n metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n that is provided to the method.\n\n Returns:\n A :class:`~dialogflow_v2beta1.types.Intent` instance.\n\n Raises:\n google.api_core.exceptions.GoogleAPICallError: If the request\n failed for any reason.\n google.api_core.exceptions.RetryError: If the request failed due\n to a retryable error and retry attempts failed.\n ValueError: If the parameters are invalid.\n \"\"\"\n if metadata is None:\n metadata = []\n metadata = list(metadata)\n request = intent_pb2.UpdateIntentRequest(\n intent=intent,\n language_code=language_code,\n update_mask=update_mask,\n intent_view=intent_view,\n )\n return self._update_intent(\n request, retry=retry, timeout=timeout, metadata=metadata)\n\n def delete_intent(self,\n name,\n retry=google.api_core.gapic_v1.method.DEFAULT,\n timeout=google.api_core.gapic_v1.method.DEFAULT,\n metadata=None):\n \"\"\"\n Deletes the specified intent.\n\n Example:\n >>> import dialogflow_v2beta1\n >>>\n >>> client = dialogflow_v2beta1.IntentsClient()\n >>>\n >>> name = client.intent_path('[PROJECT]', '[INTENT]')\n >>>\n >>> client.delete_intent(name)\n\n Args:\n name (str): Required. The name of the intent to delete.\n Format: ``projects//agent/intents/``.\n retry (Optional[google.api_core.retry.Retry]): A retry object used\n to retry requests. If ``None`` is specified, requests will not\n be retried.\n timeout (Optional[float]): The amount of time, in seconds, to wait\n for the request to complete. Note that if ``retry`` is\n specified, the timeout applies to each individual attempt.\n metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n that is provided to the method.\n\n Raises:\n google.api_core.exceptions.GoogleAPICallError: If the request\n failed for any reason.\n google.api_core.exceptions.RetryError: If the request failed due\n to a retryable error and retry attempts failed.\n ValueError: If the parameters are invalid.\n \"\"\"\n if metadata is None:\n metadata = []\n metadata = list(metadata)\n request = intent_pb2.DeleteIntentRequest(name=name, )\n self._delete_intent(\n request, retry=retry, timeout=timeout, metadata=metadata)\n\n def batch_update_intents(self,\n parent,\n language_code,\n intent_batch_uri=None,\n intent_batch_inline=None,\n update_mask=None,\n intent_view=None,\n retry=google.api_core.gapic_v1.method.DEFAULT,\n timeout=google.api_core.gapic_v1.method.DEFAULT,\n metadata=None):\n \"\"\"\n Updates/Creates multiple intents in the specified agent.\n\n Operation \n\n Example:\n >>> import dialogflow_v2beta1\n >>>\n >>> client = dialogflow_v2beta1.IntentsClient()\n >>>\n >>> parent = client.agent_path('[PROJECT]', '[AGENT]')\n >>>\n >>> # TODO: Initialize ``language_code``:\n >>> language_code = ''\n >>>\n >>> response = client.batch_update_intents(parent, language_code)\n >>>\n >>> def callback(operation_future):\n ... # Handle result.\n ... result = operation_future.result()\n >>>\n >>> response.add_done_callback(callback)\n >>>\n >>> # Handle metadata.\n >>> metadata = response.metadata()\n\n Args:\n parent (str): Required. The name of the agent to update or create intents in.\n Format: ``projects//agent``.\n language_code (str): Optional. The language of training phrases, parameters and rich messages\n defined in ``intents``. If not specified, the agent's default language is\n used. [More than a dozen\n languages](https://dialogflow.com/docs/reference/language) are supported.\n Note: languages must be enabled in the agent, before they can be used.\n intent_batch_uri (str): The URI to a Google Cloud Storage file containing intents to update or\n create. The file format can either be a serialized proto (of IntentBatch\n type) or JSON object. Note: The URI must start with \\\"gs://\\\".\n intent_batch_inline (Union[dict, ~dialogflow_v2beta1.types.IntentBatch]): The collection of intents to update or create.\n If a dict is provided, it must be of the same form as the protobuf\n message :class:`~dialogflow_v2beta1.types.IntentBatch`\n update_mask (Union[dict, ~dialogflow_v2beta1.types.FieldMask]): Optional. The mask to control which fields get updated.\n If a dict is provided, it must be of the same form as the protobuf\n message :class:`~dialogflow_v2beta1.types.FieldMask`\n intent_view (~dialogflow_v2beta1.types.IntentView): Optional. The resource view to apply to the returned intent.\n retry (Optional[google.api_core.retry.Retry]): A retry object used\n to retry requests. If ``None`` is specified, requests will not\n be retried.\n timeout (Optional[float]): The amount of time, in seconds, to wait\n for the request to complete. Note that if ``retry`` is\n specified, the timeout applies to each individual attempt.\n metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n that is provided to the method.\n\n Returns:\n A :class:`~dialogflow_v2beta1.types._OperationFuture` instance.\n\n Raises:\n google.api_core.exceptions.GoogleAPICallError: If the request\n failed for any reason.\n google.api_core.exceptions.RetryError: If the request failed due\n to a retryable error and retry attempts failed.\n ValueError: If the parameters are invalid.\n \"\"\"\n if metadata is None:\n metadata = []\n metadata = list(metadata)\n # Sanity check: We have some fields which are mutually exclusive;\n # raise ValueError if more than one is sent.\n google.api_core.protobuf_helpers.check_oneof(\n intent_batch_uri=intent_batch_uri,\n intent_batch_inline=intent_batch_inline,\n )\n\n request = intent_pb2.BatchUpdateIntentsRequest(\n parent=parent,\n language_code=language_code,\n intent_batch_uri=intent_batch_uri,\n intent_batch_inline=intent_batch_inline,\n update_mask=update_mask,\n intent_view=intent_view,\n )\n operation = self._batch_update_intents(\n request, retry=retry, timeout=timeout, metadata=metadata)\n return google.api_core.operation.from_gapic(\n operation,\n self.operations_client,\n intent_pb2.BatchUpdateIntentsResponse,\n metadata_type=struct_pb2.Struct,\n )\n\n def batch_delete_intents(self,\n parent,\n intents,\n retry=google.api_core.gapic_v1.method.DEFAULT,\n timeout=google.api_core.gapic_v1.method.DEFAULT,\n metadata=None):\n \"\"\"\n Deletes intents in the specified agent.\n\n Operation \n\n Example:\n >>> import dialogflow_v2beta1\n >>>\n >>> client = dialogflow_v2beta1.IntentsClient()\n >>>\n >>> parent = client.project_path('[PROJECT]')\n >>>\n >>> # TODO: Initialize ``intents``:\n >>> intents = []\n >>>\n >>> response = client.batch_delete_intents(parent, intents)\n >>>\n >>> def callback(operation_future):\n ... # Handle result.\n ... result = operation_future.result()\n >>>\n >>> response.add_done_callback(callback)\n >>>\n >>> # Handle metadata.\n >>> metadata = response.metadata()\n\n Args:\n parent (str): Required. The name of the agent to delete all entities types for. Format:\n ``projects//agent``.\n intents (list[Union[dict, ~dialogflow_v2beta1.types.Intent]]): Required. The collection of intents to delete. Only intent ``name`` must be\n filled in.\n If a dict is provided, it must be of the same form as the protobuf\n message :class:`~dialogflow_v2beta1.types.Intent`\n retry (Optional[google.api_core.retry.Retry]): A retry object used\n to retry requests. If ``None`` is specified, requests will not\n be retried.\n timeout (Optional[float]): The amount of time, in seconds, to wait\n for the request to complete. Note that if ``retry`` is\n specified, the timeout applies to each individual attempt.\n metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n that is provided to the method.\n\n Returns:\n A :class:`~dialogflow_v2beta1.types._OperationFuture` instance.\n\n Raises:\n google.api_core.exceptions.GoogleAPICallError: If the request\n failed for any reason.\n google.api_core.exceptions.RetryError: If the request failed due\n to a retryable error and retry attempts failed.\n ValueError: If the parameters are invalid.\n \"\"\"\n if metadata is None:\n metadata = []\n metadata = list(metadata)\n request = intent_pb2.BatchDeleteIntentsRequest(\n parent=parent,\n intents=intents,\n )\n operation = self._batch_delete_intents(\n request, retry=retry, timeout=timeout, metadata=metadata)\n return google.api_core.operation.from_gapic(\n operation,\n self.operations_client,\n empty_pb2.Empty,\n metadata_type=struct_pb2.Struct,\n )\n","sub_path":"env/lib/python3.6/site-packages/dialogflow_v2beta1/gapic/intents_client.py","file_name":"intents_client.py","file_ext":"py","file_size_in_byte":33264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"174942673","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu May 2 11:25:45 2019\r\n\r\n@author: samrat.pyaraka\r\n\"\"\"\r\n\r\nimport re\r\nimport csv\r\nimport os\r\nimport regexs\r\nimport pandas as pd\r\n\r\n\r\n'''\r\n Load a csv file using csv.reader method.\r\n'''\r\n\r\nwith open(os.path.join(r\"C:\\Users\\samrat.pyaraka\\Desktop\\iQreate\\public_data\", \"re1.csv\"), 'rU') as file:\r\n target_doc = csv.reader(file, delimiter=\",\", quotechar='|')\r\n ncol=len(next(target_doc)) # Read first line and count columns\r\n print(ncol)\r\n \r\n i = 1 #need to count the rows and also helpful in debugging if the regex fails.\r\n \r\n # for loop for iterating through all rows\r\n for line in target_doc:\r\n print(\"-------------start of row------------=\", i)\r\n \r\n # iterating through all the columns one after another to get each text separately.\r\n for col in range(0, ncol):\r\n \r\n # checking if the text in the row is null\r\n if line[col] != \"\":\r\n \r\n # creating object of the Class Regex and also passing text of that\r\n # particular column so that it can be assign and can be used in all\r\n # functions / methods.\r\n IsRegexFound = regexs.regexs(line[col], ncol)\r\n \r\n # Calling method and getting the regex results\r\n result = IsRegexFound.checknAssignRegex()\r\n print(result)\r\n else:\r\n print(\"NULL\")\r\n \r\n print(\"-------------end of row------------\")\r\n i += 1\r\n \r\n\r\n\r\n#with open(os.path.join(r\"C:\\Users\\samrat.pyaraka\\Desktop\\iQreate\\public_data\", \"nre2.csv\"), 'rU') as file:\r\n# target_doc = csv.reader(file, delimiter=\",\", quotechar='|')\r\n# ncol=len(next(target_doc)) # Read first line and count columns\r\n# print(ncol)\r\n# \r\n# i = 1\r\n# for line in target_doc:\r\n# \r\n# print(\"-------------start of row------------=\", i)\r\n# for col in range(0, ncol):\r\n# line[col] = line[col].replace(',', '')\r\n# line[col] = line[col].strip()\r\n# if line[col] != \"\":\r\n# IsRegexFound = regexs.regexs(line[col], ncol)\r\n# result = IsRegexFound.CheckNRERegex()\r\n# print(result)\r\n# else:\r\n# print(\"NULL\")\r\n# \r\n# print(\"-------------end of row------------\")\r\n# i += 1\r\n \r\n \r\n#dataframe = pd.read_csv(os.path.join(r\"C:\\Users\\samrat.pyaraka\\Desktop\\iQreate\\public_data\", \"nre2.csv\"), error_bad_lines=False, skipinitialspace=True)\r\n#\r\n#i =1\r\n#for index, row in dataframe.iterrows():\r\n# print(\"-------------start of row------------=\", i)\r\n# #print(row[0], row[1], row[2])\r\n# for col in range(0,len(dataframe.columns)):\r\n# if row[col] != \"\":\r\n# IsRegexFound = regexs.regexs(str(row[col]), 0)\r\n# result = IsRegexFound.CheckNRERegex()\r\n# \r\n# print(result)\r\n# else:\r\n# print(\"NULL\")\r\n# print(\"-------------end of row------------\")\r\n# i += 1\r\n","sub_path":"assignmentForRe.py","file_name":"assignmentForRe.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"241262952","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\n\n\n# makes a new list containing only floats, not lists that \n# contain lists with only one element/value\ndef removeListComplexity(currentList, rangeNum, maxValue):\n\tnewList = list()\n\n\tfor x in range(rangeNum):\n\t\tvalue = currentList[x]\n\t\tvalue = value[0]\n\t\tif (value < maxValue):\n\t\t\tnewList.insert(x, value)\n\n\treturn newList\n\n\n\nprices = pd.read_csv('airbnb-sep-2017/listings.csv', usecols=[60])\n# removes dollar sign and commas from price\nprices = prices.replace('[\\$,]', '',regex=True).astype(float) \npriceList = prices.values.tolist()\npriceList = removeListComplexity(priceList, 1000, 2000.0)\n\n# style and font for the graphs\nstyle.use('fivethirtyeight')\ncsfont = {'fontname':'Fantasy'}\n\n\n# Frequency of prices graph\nplt.hist(priceList, bins = 1000)\nplt.title('Frequency of Prices in San Francisco', **csfont)\nplt.ylabel('Frequency', **csfont)\nplt.xlabel('Prices', **csfont)\nplt.show()\n\n# need to make price list again because some listings do not have \n#reviews\nprices = pd.read_csv('airbnb-sep-2017/listings.csv', usecols=[60])\n# removes dollar sign and commas from price\nprices = prices.replace('[\\$,]', '',regex=True).astype(float) \npriceList = prices.values.tolist()\n\n# reviews are out of 100\nreviews = pd.read_csv('airbnb-sep-2017/listings.csv', usecols=[79])\nreviewList = reviews.values.tolist()\n# reviewList = removeListComplexity(reviewList, 1000, 101)\n\npriceList2 = list()\nreviewList2 = list()\n\nfor x in range(1000):\n\tpriceValue = priceList[x]\n\tpriceValue = priceValue[0]\n\treviewValue = reviewList[x]\n\treviewValue = reviewValue[0]\n\n\tif (reviewValue != \"None\"):\n\t\tpriceList2.insert(x, priceValue)\n\t\treviewList2.insert(x, reviewValue)\n\n# Price and review corelation\nplt.plot(priceList2, reviewList2, '.')\nplt.title('Price and Review Correlation in San Francisco', **csfont)\nplt.ylabel('Review (out of 100)', **csfont)\nplt.xlabel('Prices', **csfont)\nplt.show()\n\n","sub_path":"data-visualizer.py","file_name":"data-visualizer.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"442013001","text":"\"\"\"\nCalculate trajectory MPE between two files\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfile1 = \"dump_atom.xyz\" # Calculate MPE wrt this file\n#file2 = \"dump_mode.xyz\" # Calculate MPE of this file\n#file2 = \"dump_atom_integrate0.xyz\" # Calculate MPE of this file\nfile2 = \"dump_atom_harmonic.xyz\"\nnatoms = 8\nndat = 10000 # number timesteps that data was dumped\n\nfh1 = open(file1, \"r\")\nfh2 = open(file2, \"r\")\n\nx1 = []\ntimestep = []\nfor t in range(0,ndat):\n line = fh1.readline()\n line = fh1.readline()\n line_split = line.split()\n timestep.append(int(line_split[2]))\n x1t = []\n for i in range(0,natoms):\n line = fh1.readline()\n nums = [float(x) for x in line.split()]\n x1t.append([nums[1],nums[2],nums[3]])\n x1.append(x1t)\ntimestep = np.array(timestep)\ntimestep = 0.5*timestep\ntimestep = timestep/1000.\nx1 = np.array(x1)\n\nx2 = []\nfor t in range(0,ndat):\n line = fh2.readline()\n line = fh2.readline()\n x2t = []\n for i in range(0,natoms):\n line = fh2.readline()\n nums = [float(x) for x in line.split()]\n x2t.append([nums[1],nums[2],nums[3]])\n x2.append(x2t)\nx2 = np.array(x2)\n\n# Calculate MPE per timestep\nmpe = []\nfor t in range(0,ndat):\n mpet = 0.0\n for n in range(0,natoms):\n diff = x2[t][n]-x1[t][n]\n diffnorm = np.linalg.norm(diff)\n norm = np.linalg.norm(x1[t][n])\n mpet = mpet + diffnorm/norm\n mpet = mpet/natoms\n mpe.append(mpet)\nmpe = np.array(mpe)\nmpe = mpe*100.\n\n# print MPE data\nfh = open(\"MPE \" + file2, \"w\")\nfor t in range(0,ndat):\n fh.write(\"%f\\n\" % (mpe[t]))\n\ntimestep = np.array([timestep]).T\nmpe = np.array([mpe]).T\ndat = np.concatenate((timestep,mpe),axis=1)\nprint(np.shape(dat))\n\nnp.savetxt(\"traj_err.dat\", dat)\n\n#plt.plot(timestep,mpe, '-')\n#plt.show()\n\n\nfh1.close()\nfh2.close()\n","sub_path":"nmd/trajectory/calc_traj_mpe.py","file_name":"calc_traj_mpe.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"379822423","text":"import pytest\n\nfrom asynctest import mock as async_mock, TestCase as AsyncTestCase\n\nfrom ...core.in_memory import InMemoryProfile\nfrom ...ledger.base import BaseLedger\nfrom ...ledger.multiple_ledger.ledger_requests_executor import (\n IndyLedgerRequestsExecutor,\n)\nfrom ...multitenant.base import BaseMultitenantManager\nfrom ...multitenant.manager import MultitenantManager\nfrom ...storage.error import StorageNotFoundError\n\nfrom ..error import (\n RevocationNotSupportedError,\n RevocationRegistryBadSizeError,\n)\nfrom ..indy import IndyRevocation\nfrom ..models.issuer_rev_reg_record import DEFAULT_REGISTRY_SIZE, IssuerRevRegRecord\nfrom ..models.revocation_registry import RevocationRegistry\n\n\nclass TestIndyRevocation(AsyncTestCase):\n def setUp(self):\n self.profile = InMemoryProfile.test_profile()\n self.context = self.profile.context\n\n Ledger = async_mock.MagicMock(BaseLedger, autospec=True)\n self.ledger = Ledger()\n self.ledger.get_credential_definition = async_mock.CoroutineMock(\n return_value={\"value\": {\"revocation\": True}}\n )\n self.ledger.get_revoc_reg_def = async_mock.CoroutineMock()\n self.context.injector.bind_instance(BaseLedger, self.ledger)\n self.context.injector.bind_instance(\n IndyLedgerRequestsExecutor,\n async_mock.MagicMock(\n get_ledger_for_identifier=async_mock.CoroutineMock(\n return_value=(None, self.ledger)\n )\n ),\n )\n self.revoc = IndyRevocation(self.profile)\n\n self.test_did = \"sample-did\"\n\n async def test_init_issuer_registry(self):\n CRED_DEF_ID = f\"{self.test_did}:3:CL:1234:default\"\n\n result = await self.revoc.init_issuer_registry(CRED_DEF_ID)\n\n assert result.cred_def_id == CRED_DEF_ID\n assert result.issuer_did == self.test_did\n assert result.max_cred_num == DEFAULT_REGISTRY_SIZE\n assert result.revoc_def_type == IssuerRevRegRecord.REVOC_DEF_TYPE_CL\n assert result.tag is None\n\n self.context.injector.bind_instance(\n BaseMultitenantManager,\n async_mock.MagicMock(MultitenantManager, autospec=True),\n )\n with async_mock.patch.object(\n IndyLedgerRequestsExecutor,\n \"get_ledger_for_identifier\",\n async_mock.CoroutineMock(return_value=(None, self.ledger)),\n ):\n result = await self.revoc.init_issuer_registry(CRED_DEF_ID)\n assert result.cred_def_id == CRED_DEF_ID\n assert result.issuer_did == self.test_did\n assert result.max_cred_num == DEFAULT_REGISTRY_SIZE\n assert result.revoc_def_type == IssuerRevRegRecord.REVOC_DEF_TYPE_CL\n assert result.tag is None\n\n async def test_init_issuer_registry_no_cred_def(self):\n CRED_DEF_ID = f\"{self.test_did}:3:CL:1234:default\"\n\n self.profile.context.injector.clear_binding(BaseLedger)\n self.ledger.get_credential_definition = async_mock.CoroutineMock(\n return_value=None\n )\n self.profile.context.injector.bind_instance(BaseLedger, self.ledger)\n\n with self.assertRaises(RevocationNotSupportedError) as x_revo:\n await self.revoc.init_issuer_registry(CRED_DEF_ID)\n assert x_revo.message == \"Credential definition not found\"\n\n async def test_init_issuer_registry_bad_size(self):\n CRED_DEF_ID = f\"{self.test_did}:3:CL:1234:default\"\n\n self.profile.context.injector.clear_binding(BaseLedger)\n self.ledger.get_credential_definition = async_mock.CoroutineMock(\n return_value={\"value\": {\"revocation\": \"...\"}}\n )\n self.profile.context.injector.bind_instance(BaseLedger, self.ledger)\n\n with self.assertRaises(RevocationRegistryBadSizeError) as x_revo:\n await self.revoc.init_issuer_registry(\n CRED_DEF_ID,\n max_cred_num=1,\n )\n assert \"Bad revocation registry size\" in x_revo.message\n\n async def test_get_active_issuer_rev_reg_record(self):\n CRED_DEF_ID = f\"{self.test_did}:3:CL:1234:default\"\n rec = await self.revoc.init_issuer_registry(CRED_DEF_ID)\n rec.revoc_reg_id = \"dummy\"\n rec.state = IssuerRevRegRecord.STATE_ACTIVE\n\n async with self.profile.session() as session:\n await rec.save(session)\n\n result = await self.revoc.get_active_issuer_rev_reg_record(CRED_DEF_ID)\n assert rec == result\n\n async def test_get_active_issuer_rev_reg_record_none(self):\n CRED_DEF_ID = f\"{self.test_did}:3:CL:1234:default\"\n with self.assertRaises(StorageNotFoundError) as x_init:\n await self.revoc.get_active_issuer_rev_reg_record(CRED_DEF_ID)\n\n async def test_init_issuer_registry_no_revocation(self):\n CRED_DEF_ID = f\"{self.test_did}:3:CL:1234:default\"\n\n self.profile.context.injector.clear_binding(BaseLedger)\n self.ledger.get_credential_definition = async_mock.CoroutineMock(\n return_value={\"value\": {}}\n )\n self.profile.context.injector.bind_instance(BaseLedger, self.ledger)\n\n with self.assertRaises(RevocationNotSupportedError) as x_revo:\n await self.revoc.init_issuer_registry(CRED_DEF_ID)\n assert x_revo.message == \"Credential definition does not support revocation\"\n\n async def test_get_issuer_rev_reg_record(self):\n CRED_DEF_ID = f\"{self.test_did}:3:CL:1234:default\"\n\n rec = await self.revoc.init_issuer_registry(CRED_DEF_ID)\n rec.revoc_reg_id = \"dummy\"\n rec.generate_registry = async_mock.CoroutineMock()\n\n with async_mock.patch.object(\n IssuerRevRegRecord, \"retrieve_by_revoc_reg_id\", async_mock.CoroutineMock()\n ) as mock_retrieve_by_rr_id:\n mock_retrieve_by_rr_id.return_value = rec\n await rec.generate_registry(self.profile, None)\n\n result = await self.revoc.get_issuer_rev_reg_record(rec.revoc_reg_id)\n assert result.revoc_reg_id == \"dummy\"\n\n async def test_list_issuer_registries(self):\n CRED_DEF_ID = [f\"{self.test_did}:3:CL:{i}:default\" for i in (1234, 5678)]\n\n for cd_id in CRED_DEF_ID:\n rec = await self.revoc.init_issuer_registry(cd_id)\n\n assert len(await self.revoc.list_issuer_registries()) == 2\n\n async def test_get_ledger_registry(self):\n CRED_DEF_ID = \"{self.test_did}:3:CL:1234:default\"\n\n with async_mock.patch.object(\n RevocationRegistry, \"from_definition\", async_mock.MagicMock()\n ) as mock_from_def:\n result = await self.revoc.get_ledger_registry(\"dummy\")\n assert result == mock_from_def.return_value\n assert \"dummy\" in IndyRevocation.REV_REG_CACHE\n\n await self.revoc.get_ledger_registry(\"dummy\")\n\n mock_from_def.assert_called_once_with(\n self.ledger.get_revoc_reg_def.return_value, True\n )\n\n self.context.injector.bind_instance(\n BaseMultitenantManager,\n async_mock.MagicMock(MultitenantManager, autospec=True),\n )\n with async_mock.patch.object(\n IndyLedgerRequestsExecutor,\n \"get_ledger_for_identifier\",\n async_mock.CoroutineMock(return_value=(None, self.ledger)),\n ), async_mock.patch.object(\n RevocationRegistry, \"from_definition\", async_mock.MagicMock()\n ) as mock_from_def:\n result = await self.revoc.get_ledger_registry(\"dummy2\")\n assert result == mock_from_def.return_value\n assert \"dummy2\" in IndyRevocation.REV_REG_CACHE\n\n await self.revoc.get_ledger_registry(\"dummy2\")\n\n mock_from_def.assert_called_once_with(\n self.ledger.get_revoc_reg_def.return_value, True\n )\n","sub_path":"aries_cloudagent/revocation/tests/test_indy.py","file_name":"test_indy.py","file_ext":"py","file_size_in_byte":7792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"425409510","text":"\nimport django\nfrom lxml import etree\nimport os\nimport pytest\nimport shutil\nimport sys\nimport time\nimport uuid\n\n# logging\nimport logging\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n# setup django environment\n# init django settings file to retrieve settings\nos.environ['DJANGO_SETTINGS_MODULE'] = 'combine.settings'\nsys.path.append('/opt/combine')\ndjango.setup()\nfrom django.conf import settings\n\n# import core\nfrom core.models import *\n\n\n\n# global variables object \"VO\"\nclass Vars(object):\n\n\t'''\n\tObject to capture and store variables used across tests\n\t'''\n\n\tdef __init__(self):\n\n\t\t# combine user\n\t\tself.user = User.objects.filter(username='combine').first()\n\nVO = Vars()\n\n\n#############################################################################\n# Tests Setup\n#############################################################################\ndef test_livy_start_session(use_active_livy):\n\n\t'''\n\tTest Livy session can be started\n\t'''\n\n\t# if use active livy\n\tif use_active_livy:\n\t\tVO.livy_session = LivySession.get_active_session()\n\t\tVO.livy_session.refresh_from_livy()\n\n\t# create livy session\n\telse:\n\t\t# start livy session\n\t\tVO.livy_session = LivySession()\n\t\tVO.livy_session.start_session()\n\n\t\t# poll until session idle, limit to 60 seconds\n\t\tfor x in range(0,240):\n\n\t\t\t# pause\n\t\t\ttime.sleep(1)\n\t\t\t\n\t\t\t# refresh session\n\t\t\tVO.livy_session.refresh_from_livy()\n\t\t\tlogger.info(VO.livy_session.status)\n\t\t\t\n\t\t\t# check status\n\t\t\tif VO.livy_session.status != 'idle':\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tbreak\n\n\t# assert\n\tassert VO.livy_session.status == 'idle'\n\n\ndef test_organization_create():\n\n\t'''\n\tTest creation of organization\n\t'''\n\n\t# instantiate and save\n\tVO.org = Organization(\n\t\tname='test_org_%s' % uuid.uuid4().hex,\n\t\tdescription=''\n\t)\n\tVO.org.save()\n\tassert type(VO.org.id) == int\n\n\ndef test_record_group_create():\n\n\t'''\n\tTest creation of record group\n\t'''\n\n\t# instantiate and save\n\tVO.rg = RecordGroup(\n\t\torganization=VO.org,\n\t\tname='test_record_group_%s' % uuid.uuid4().hex,\n\t\tdescription='',\n\t\tpublish_set_id='test_record_group_pub_id'\n\t)\n\tVO.rg.save()\n\tassert type(VO.rg.id) == int\n\n\n\n#############################################################################\n# Test Harvest\n#############################################################################\ndef prepare_records():\n\n\t'''\n\tUnzip 250 MODS records to temp location, feed to test_static_harvest()\n\t'''\n\n\t# parse file\n\txml_tree = etree.parse('tests/data/mods_250.xml')\n\txml_root = xml_tree.getroot()\n\t\n\t# get namespaces\n\tnsmap = {}\n\tfor ns in xml_root.xpath('//namespace::*'):\n\t\tif ns[0]:\n\t\t\tnsmap[ns[0]] = ns[1]\n\n\t# find mods records\n\tmods_roots = xml_root.xpath('//mods:mods', namespaces=nsmap)\n\n\t# create temp dir\n\tpayload_dir = '/tmp/%s' % uuid.uuid4().hex\n\tos.makedirs(payload_dir)\n\n\t# write MODS to temp dir\n\tfor mods in mods_roots:\n\t\twith open(os.path.join(payload_dir, '%s.xml' % uuid.uuid4().hex), 'w') as f:\n\t\t\tf.write(etree.tostring(mods).decode('utf-8'))\n\n\t# return payload dir\n\treturn payload_dir\n\n\ndef test_static_harvest():\n\n\t'''\n\tTest static harvest of XML records from disk\n\t'''\n\n\t# prepare test data\n\tpayload_dir = prepare_records()\n\n\t# build payload dictionary\n\tpayload_dict = {\n\t\t'type':'location',\n\t\t'payload_dir':payload_dir,\n\t\t'xpath_document_root':'/mods:mods',\n\t\t'xpath_record_id':''\n\t}\n\n\t# initiate job\n\tcjob = HarvestStaticXMLJob(\t\t\t\n\t\tjob_name='test_static_harvest',\n\t\tjob_note='',\n\t\tuser=VO.user,\n\t\trecord_group=VO.rg,\n\t\tindex_mapper='GenericMapper',\n\t\tpayload_dict=payload_dict\n\t)\n\n\t# start job and update status\n\tjob_status = cjob.start_job()\n\n\t# if job_status is absent, report job status as failed\n\tif job_status == False:\n\t\tcjob.job.status = 'failed'\n\t\tcjob.job.save()\n\n\t# poll until complete\n\tfor x in range(0,240):\n\n\t\t# pause\n\t\ttime.sleep(1)\n\t\t\n\t\t# refresh session\n\t\tcjob.job.update_status()\n\t\t\n\t\t# check status\n\t\tif cjob.job.status != 'available':\n\t\t\tcontinue\n\t\telse:\n\t\t\tbreak\n\n\t# save static harvest job to VO\n\tVO.static_harvest_cjob = cjob\n\n\t# remove payload_dir\n\tshutil.rmtree(payload_dir)\n\n\t# assert job is done and available via livy\n\tassert VO.static_harvest_cjob.job.status == 'available'\n\n\t# assert record count is 250\n\tdcount = VO.static_harvest_cjob.get_detailed_job_record_count()\n\tassert dcount['records'] == 250\n\tassert dcount['errors'] == 0\n\n\t# assert no indexing failures\n\tassert len(VO.static_harvest_cjob.get_indexing_failures()) == 0\n\n\n\n#############################################################################\n# Test Transform\n#############################################################################\ndef prepare_transform():\n\n\t'''\n\tCreate temporary transformation scenario based on tests/data/mods_transform.xsl\n\t'''\n\n\twith open('tests/data/mods_transform.xsl','r') as f:\n\t\txsl_string = f.read()\n\ttrans = Transformation(\n\t\tname='temp_mods_transformation',\n\t\tpayload=xsl_string,\n\t\ttransformation_type='xslt',\n\t\tfilepath='will_be_updated'\n\t)\t\n\ttrans.save()\n\n\t# return transformation\n\treturn trans\n\n\ndef test_static_transform():\n\n\t'''\n\tTest static harvest of XML records from disk\n\t'''\n\n\t# prepare and capture temporary transformation scenario\n\tVO.transformation_scenario = prepare_transform()\n\n\t# initiate job\n\tcjob = TransformJob(\n\t\tjob_name='test_static_transform_job',\n\t\tjob_note='',\n\t\tuser=VO.user,\n\t\trecord_group=VO.rg,\n\t\tinput_job=VO.static_harvest_cjob.job,\n\t\ttransformation=VO.transformation_scenario,\n\t\tindex_mapper='GenericMapper'\n\t)\n\t\n\t# start job and update status\n\tjob_status = cjob.start_job()\n\n\t# if job_status is absent, report job status as failed\n\tif job_status == False:\n\t\tcjob.job.status = 'failed'\n\t\tcjob.job.save()\n\n\t# poll until complete\n\tfor x in range(0,240):\n\n\t\t# pause\n\t\ttime.sleep(1)\n\t\t\n\t\t# refresh session\n\t\tcjob.job.update_status()\n\t\t\n\t\t# check status\n\t\tif cjob.job.status != 'available':\n\t\t\tcontinue\n\t\telse:\n\t\t\tbreak\n\n\t# save static harvest job to VO\n\tVO.static_transform_cjob = cjob\n\n\t# assert job is done and available via livy\n\tassert VO.static_transform_cjob.job.status == 'available'\n\n\t# assert record count is 250\n\tdcount = VO.static_transform_cjob.get_detailed_job_record_count()\n\tassert dcount['records'] == 250\n\tassert dcount['errors'] == 0\n\n\t# assert no indexing failures\n\tassert len(VO.static_transform_cjob.get_indexing_failures()) == 0\n\n\t# remove transformation\n\tassert VO.transformation_scenario.delete()[0] > 0\n\n\n\n#############################################################################\n# Test Validation Scenarios\n#############################################################################\ndef test_add_schematron_validation_scenario():\n\n\t'''\n\tAdd schematron validation\n\t'''\n\n\t# get schematron validation from test data\n\twith open('tests/data/schematron_validation.sch','r') as f:\n\t\tsch_payload = f.read()\n\n\t# init new validation scenario\n\tschematron_validation_scenario = ValidationScenario(\n\t\tname='temp_vs_%s' % str(uuid.uuid4()),\n\t\tpayload=sch_payload,\n\t\tvalidation_type='sch',\n\t\tdefault_run=False\n\t)\n\tschematron_validation_scenario.save()\n\n\t# pin to VO\n\tVO.schematron_validation_scenario = schematron_validation_scenario\n\n\t# assert creation\n\tassert type(VO.schematron_validation_scenario.id) == int\n\n\ndef test_add_python_validation_scenario():\n\n\t'''\n\tAdd python code snippet validation\n\t'''\n\n\t# get python validation from test data\n\twith open('tests/data/python_validation.py','r') as f:\n\t\tpy_payload = f.read()\n\n\t# init new validation scenario\n\tpython_validation_scenario = ValidationScenario(\n\t\tname='temp_vs_%s' % str(uuid.uuid4()),\n\t\tpayload=py_payload,\n\t\tvalidation_type='python',\n\t\tdefault_run=False\n\t)\n\tpython_validation_scenario.save()\n\n\t# pin to VO\n\tVO.python_validation_scenario = python_validation_scenario\n\n\t# assert creation\n\tassert type(VO.python_validation_scenario.id) == int\n\n\ndef test_schematron_validation():\n\n\t# get target records\n\tVO.harvest_record = VO.static_harvest_cjob.job.get_records().first()\n\tVO.transform_record = VO.static_transform_cjob.job.get_records().first()\n\n\t# validate harvest record with schematron\n\t'''\n\texpecting failure count of 2\n\t'''\n\tvs_results = VO.schematron_validation_scenario.validate_record(VO.harvest_record)\n\tassert vs_results['parsed']['fail_count'] == 2\n\n\t# validate transform record with schematron\n\t'''\n\texpecting failure count of 1\n\t'''\n\tvs_results = VO.schematron_validation_scenario.validate_record(VO.transform_record)\n\tassert vs_results['parsed']['fail_count'] == 1\n\n\ndef test_python_validation():\n\n\t# validate harvest record with python\n\t'''\n\texpecting failure count of 1\n\t'''\n\tvs_results = VO.python_validation_scenario.validate_record(VO.harvest_record)\n\tprint(vs_results)\n\tassert vs_results['parsed']['fail_count'] == 1\n\n\t# validate transform record with python\n\t'''\n\texpecting failure count of 1\n\t'''\n\tvs_results = VO.python_validation_scenario.validate_record(VO.transform_record)\n\tprint(vs_results)\n\tassert vs_results['parsed']['fail_count'] == 1\n\n\n\n#############################################################################\n# Test Duplicate/Merge Job\n#############################################################################\ndef test_duplicate():\n\n\t'''\n\tDuplicate Transform job, applying newly created validation scenarios\n\t'''\n\n\t# initiate job\n\tcjob = MergeJob(\n\t\tjob_name='test_merge_job_with_validation',\n\t\tjob_note='',\n\t\tuser=VO.user,\n\t\trecord_group=VO.rg,\n\t\tinput_jobs=[VO.static_transform_cjob.job],\n\t\tindex_mapper='GenericMapper',\n\t\tvalidation_scenarios=[VO.schematron_validation_scenario.id, VO.python_validation_scenario.id]\n\t)\n\t\n\t# start job and update status\n\tjob_status = cjob.start_job()\n\n\t# if job_status is absent, report job status as failed\n\tif job_status == False:\n\t\tcjob.job.status = 'failed'\n\t\tcjob.job.save()\n\n\t# poll until complete\n\tfor x in range(0,240):\n\n\t\t# pause\n\t\ttime.sleep(1)\n\t\t\n\t\t# refresh session\n\t\tcjob.job.update_status()\n\t\t\n\t\t# check status\n\t\tif cjob.job.status != 'available':\n\t\t\tcontinue\n\t\telse:\n\t\t\tbreak\n\n\t# save static harvest job to VO\n\tVO.merge_cjob = cjob\n\n\t# assert job is done and available via livy\n\tassert VO.merge_cjob.job.status == 'available'\n\n\t# assert record count is 250\n\tdcount = VO.merge_cjob.get_detailed_job_record_count()\n\tassert dcount['records'] == 250\n\tassert dcount['errors'] == 0\n\n\t# assert validation scenarios applied\n\tjob_validation_scenarios = VO.merge_cjob.job.jobvalidation_set.all()\n\tassert job_validation_scenarios.count() == 2\n\n\t# loop through validation scenarios and confirm that both show 250 failures\n\tfor jv in job_validation_scenarios:\n\t\tassert jv.get_record_validation_failures().count() == 250\n\n\t# assert no indexing failures\n\tassert len(VO.merge_cjob.get_indexing_failures()) == 0\n\n\n\n#############################################################################\n# Tests Teardown\n#############################################################################\ndef test_org_delete(keep_records):\n\n\t'''\n\tTest removal of organization with cascading deletes\n\t'''\n\n\t# assert delete of org and children\n\tif not keep_records:\n\t\tassert VO.org.delete()[0] > 0\n\telse:\n\t\tassert True\n\n\ndef test_validation_scenario_teardown():\n\n\tassert VO.schematron_validation_scenario.delete()[0] > 0\n\tassert VO.python_validation_scenario.delete()[0] > 0\n\n\ndef test_livy_stop_session(use_active_livy):\n\n\t'''\n\tTest Livy session can be stopped\n\t'''\n\n\tif use_active_livy:\n\t\tassert True\n\t\n\t# stop livy session used for testing\n\telse:\n\t\t# attempt stop\n\t\tVO.livy_session.stop_session()\n\n\t\t# poll until session idle, limit to 60 seconds\n\t\tfor x in range(0,240):\n\n\t\t\t# pause\n\t\t\ttime.sleep(1)\n\t\t\t\n\t\t\t# refresh session\n\t\t\tVO.livy_session.refresh_from_livy()\n\t\t\tlogger.info(VO.livy_session.status)\n\t\t\t\n\t\t\t# check status\n\t\t\tif VO.livy_session.status != 'gone':\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tVO.livy_session.delete()\n\t\t\t\tbreak\n\n\t\t# assert\n\t\tassert VO.livy_session.status == 'gone'\n\n\n\n\n\n\n","sub_path":"tests/test_basic.py","file_name":"test_basic.py","file_ext":"py","file_size_in_byte":11704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"255204444","text":"import unittest\nfrom selenium import webdriver\n#waits for the page to load\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver import FirefoxOptions\nimport time\n\n\nclass LoginTest(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.Firefox()\n\n #self.driver = webdriver.Firefox(executable_path='D:\\misc\\Installers\\Web_Automation\\geckodriver-v0.19.1-win64\\geckodriver.exe')\n #self.driver = webdriver.Firefox()\n #opts = FirefoxOptions()\n #opts.add_argument(\"security.sandbox.content.level\",5)\n #final FirefoxOptions options = new FirefoxOptions()\n #profile.addPreference(\"security.sandbox.content.level\", 5)\n #driver = new\n #FirefoxDriver(options);\n #opts = FirefoxOptions()\n #opts.add_argument(\"--headless\")\n #self = webdriver.Firefox(firefox_options=opts)\n #self.driver.set_page_load_timeout(30)\n self.driver.get(\"https://www.facebook.com/\")\n self.driver.maximize_window()\n\n #test case method\n def test_login(self):\n driver = self.driver\n\n #declare variables\n fbusername = 'jhuanini'\n fbpw = 'mahalpabanyako'\n fbusernameid = 'email'\n fbpwid = 'pass'\n loginbuttonxpath = '//*[@id=\"u_0_2\"]'\n fblogocssselector = 'span._2md'\n\n fbusernameelement = WebDriverWait(driver,5).until(lambda driver: driver.find_element_by_id(fbusernameid))\n fbpwelement = WebDriverWait(driver,5).until(lambda driver: driver.find_element_by_id(fbpwid))\n loginbuttonelement = WebDriverWait(driver,5).until(lambda driver: driver.find_element_by_xpath(loginbuttonxpath))\n fbusernameelement.clear()\n fbusernameelement.send_keys(fbusername)\n fbpwelement.clear()\n fbpwelement.send_keys(fbpw)\n loginbuttonelement.click()\n fblogoclassnameelement = WebDriverWait(driver,10).until(lambda driver: driver.find_element_by_css_selector(fblogocssselector))\n fblogoclassnameelement.click()\n\n def tearDown(self):\n self.driver.quit()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"practice/fb_test.py","file_name":"fb_test.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"641514000","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom my_app.forms import ContactForm, GroupsForm\nfrom my_app.sendgrid.contact import contactMail\nfrom my_app.sendgrid.groups import response_group_mail\nfrom datetime import datetime, timedelta, date\nfrom my_app.google_api.helpers import dateAndHourAvailable, createEvent, isHolliday, eventsDateList\nfrom random import randint\nfrom .models import IndexAlert\n\n\ndef index(request):\n if IndexAlert.objects.filter(active=True):\n alert = IndexAlert.objects.filter(active=True).order_by('-id')[0]\n else:\n alert = []\n context = {\n 'alert': alert,\n }\n return render(request, 'my_app/index.html', context)\n\ndef about(request):\n return render(request, 'my_app/about.html')\n\ndef visiting(request):\n return render(request, 'my_app/visiting.html')\n\ndef visiting_cars(request):\n return render(request, 'my_app/visiting-cars.html')\n\ndef diverse(request):\n return render(request, 'my_app/diverse.html')\n\ndef about_buddhism(request):\n return render(request, 'my_app/about-buddhism.html')\n\ndef visiting_groups(request):\n\n import json\n group_form_class = GroupsForm\n event_list = eventsDateList()\n\n if request.method == 'POST':\n group_form = group_form_class(data=request.POST)\n\n if group_form.is_valid():\n group_name = request.POST.get('group_name', '')\n scheduling_date = request.POST.get('scheduling_date', '')\n hour = request.POST.get('hour', '')\n number_of_people = request.POST.get('number_of_people', '')\n group_type = request.POST.get('group_type', '')\n vehicle = request.POST.get('vehicle', '')\n vehicle_number = request.POST.get('vehicle_number', '')\n scheduling_responsible = request.POST.get('scheduling_responsible', '')\n visiting_day_responsible = request.POST.get('visiting_day_responsible', '')\n phone = request.POST.get('phone', '')\n email = request.POST.get('email', '')\n\n date_today = date.today()\n three_months = date.today() + timedelta(days=90)\n # CONVERTING REQUESTED DATE FROM STRING TO DATETIME.DATE TYPE\n scheduling_date_converted = datetime.strptime(scheduling_date,'%Y-%m-%d').date()\n\n # CHECKING IF THE DATE IS MORE THAN 3 MONTHS AHEAD\n if scheduling_date_converted > three_months or scheduling_date_converted <= date_today:\n invalid_date = True\n return render(request, 'my_app/visiting-groups.html', {\n 'form': group_form_class,\n 'invalid_date': invalid_date,\n 'event_list': event_list,\n })\n\n\n # SEE IF THE DAY SELECTED IS A VISITING DAY\n dt = datetime(int(scheduling_date[0:4]),int(scheduling_date[5:7]),int(scheduling_date[8:10]))\n week_day_number = (dt.isoweekday() % 7) + 1\n\n # MAKING DATE FORMAT BR\n br_scheduling_date = scheduling_date[8:10] + \"/\" + scheduling_date[5:7] + \"/\" + scheduling_date[0:4]\n\n # CHECKING IF THE REQUESTED VISITING DAY IS A WEDNESDAY, THURDAY OR FRIDAY\n if (week_day_number in (4,5,6)):\n # CREATING VISIT CODE\n months = {'01':'JAN',\n '02':'FEV',\n '03':'MAR',\n '04':'ABR',\n '05':'MAI',\n '06':'JUN',\n '07':'JUL',\n '08':'AGO',\n '09':'SET',\n '10':'OUT',\n '11':'NOV',\n '12':'DEZ',\n }\n\n # CHECKING IF THE DATA COMES WITH 4 DIGITS AND GIVIN AN EXTRA 0 TO THE LEFT (LIKE 9:30 INSTEAD OF 09:30)\n if len(hour) == 4:\n hour = '0' + str(hour)\n visit_code = months[scheduling_date[5:7]] + scheduling_date[8:10] + str(randint(100,999)) + hour[:2]\n\n # CHECKING IF THE DAY IS FULL\n if dateAndHourAvailable(scheduling_date, hour) == 4:\n day_full = True\n return render(request, 'my_app/visiting-groups.html', {\n 'dia': br_scheduling_date[:2],\n 'form': group_form_class,\n 'day_full': day_full,\n 'event_list': event_list,\n })\n\n # CHECKING IF THE DAY AN HOUR IS AVAILABLE\n elif dateAndHourAvailable(scheduling_date, hour):\n\n # CHECKING IF IS HOLLIDAY\n if isHolliday(scheduling_date, hour):\n holliday = True\n return render(request, 'my_app/visiting-groups.html', {\n 'form': group_form_class,\n 'holliday': holliday,\n 'event_list': event_list,\n })\n\n\n # CREANTING AN GOOGLE CALENDAR EVENT\n createEvent(visit_code, group_name, scheduling_date, hour, number_of_people, group_type, vehicle, scheduling_responsible, visiting_day_responsible, phone, email)\n\n # MAILING THE INFORMATIONS TO THE GROUP WHO REQUEST THE VISIT\n response_group_mail(scheduling_responsible, visit_code, vehicle, number_of_people, br_scheduling_date, hour, email)\n\n send_success = True\n return render(request, 'my_app/visiting-groups.html', {\n 'form': group_form_class,\n 'send_success': send_success,\n 'event_list': event_list,\n })\n else:\n hour_taken = True\n return render(request, 'my_app/visiting-groups.html', {\n 'form': group_form_class,\n 'hour_taken': hour_taken,\n 'event_list': event_list,\n })\n\n else:\n invalid_day = True\n return render(request, 'my_app/visiting-groups.html', {\n 'form': group_form_class,\n 'invalid_day': invalid_day,\n 'event_list': event_list,\n })\n\n else:\n send_error = True\n return render(request, 'my_app/visiting-groups.html', {\n 'form': group_form_class,\n 'send_error': send_error,\n 'event_list': event_list,\n })\n\n return render(request, 'my_app/visiting-groups.html', {\n 'form': group_form_class,\n 'event_list': event_list,\n })\n\n\ndef press(request):\n return render(request, 'my_app/press.html')\n\ndef contact(request):\n contact_form_class = ContactForm\n\n if request.method == 'POST':\n form = contact_form_class(data=request.POST)\n\n if form.is_valid():\n contact_name = request.POST.get('contact_name', '')\n contact_email = request.POST.get('contact_email', '')\n form_content = request.POST.get('content', '')\n\n contactMail(contact_name,contact_email ,form_content)\n send_success = True\n return render(request, 'my_app/contact.html', {\n 'form': contact_form_class,\n 'send_success': send_success,\n })\n\n else:\n send_error = True\n return render(request, 'my_app/contact.html', {\n 'form': contact_form_class,\n 'send_error': send_error,\n })\n\n return render(request, 'my_app/contact.html', {\n 'form': contact_form_class,\n })\n","sub_path":"my_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"111351851","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport logging\nfrom textwrap import wrap\nfrom .fft_utils import fft, ifft\n\n\nlogging.basicConfig(format='')\nWARN = lambda msg: logging.warning(\"WARNING: %s\" % msg)\nNOTE = lambda msg: logging.warning(\"NOTE: %s\" % msg) # else it's mostly ignored\npi = np.pi\nEPS32 = np.finfo(np.float32).eps # machine epsilon\nEPS64 = np.finfo(np.float64).eps\n\n__all__ = [\n \"WARN\",\n \"NOTE\",\n \"pi\",\n \"EPS32\",\n \"EPS64\",\n \"p2up\",\n \"padsignal\",\n \"trigdiff\",\n \"mad\",\n \"est_riskshrink_thresh\",\n \"find_closest_parallel_is_faster\",\n \"assert_is_one_of\",\n \"_textwrap\",\n]\n\n\ndef p2up(n):\n \"\"\"Calculates next power of 2, and left/right padding to center\n the original `n` locations.\n\n # Arguments:\n n: int\n Length of original (unpadded) signal.\n\n # Returns:\n n_up: int\n Next power of 2.\n n1: int\n Left pad length.\n n2: int\n Right pad length.\n \"\"\"\n eps = np.finfo(np.float64).eps # machine epsilon for float64\n up = 2 ** (1 + np.round(np.log2(n + eps)))\n\n n2 = np.floor((up - n) / 2)\n n1 = n2 + n % 2 # if n is odd, left-pad by (n2 + 1), else n1=n2\n assert n1 + n + n2 == up # [left_pad, original, right_pad]\n return int(up), int(n1), int(n2)\n\n\ndef padsignal(x, padtype='reflect', padlength=None, get_params=False):\n \"\"\"Pads signal and returns trim indices to recover original.\n\n # Arguments:\n x: np.ndarray\n Input vector, 1D or 2D. 2D has time in dim1, e.g. `(n_inputs, time)`.\n\n padtype: str\n Pad scheme to apply on input. One of:\n ('reflect', 'symmetric', 'replicate', 'wrap', 'zero').\n 'zero' is most naive, while 'reflect' (default) partly mitigates\n boundary effects. See [1] & [2].\n\n padlength: int / None\n Number of samples to pad input to (i.e. len(x_padded) == padlength).\n Even: left = right, Odd: left = right + 1.\n Defaults to next highest power of 2 w.r.t. `len(x)`.\n\n # Returns:\n xp: np.ndarray\n Padded signal.\n n_up: int\n Next power of 2, or `padlength` if provided.\n n1: int\n Left pad length.\n n2: int\n Right pad length.\n\n # References:\n 1. Signal extension modes. PyWavelets contributors\n https://pywavelets.readthedocs.io/en/latest/ref/\n signal-extension-modes.html\n\n 2. Wavelet Bases and Lifting Wavelets. H. Xiong.\n http://min.sjtu.edu.cn/files/wavelet/\n 6-lifting%20wavelet%20and%20filterbank.pdf\n \"\"\"\n def _process_args(x, padtype):\n assert_is_one_of(padtype, 'padtype',\n ('reflect', 'symmetric', 'replicate', 'wrap', 'zero'))\n if not isinstance(x, np.ndarray):\n raise TypeError(\"`x` must be a numpy array (got %s)\" % type(x))\n elif x.ndim not in (1, 2):\n raise ValueError(\"`x` must be 1D or 2D (got x.ndim == %s)\" % x.ndim)\n\n _process_args(x, padtype)\n N = x.shape[-1]\n\n if padlength is None:\n # pad up to the nearest power of 2\n n_up, n1, n2 = p2up(N)\n else:\n n_up = padlength\n if abs(padlength - N) % 2 == 0:\n n1 = n2 = (n_up - N) // 2\n else:\n n2 = (n_up - N) // 2\n n1 = n2 + 1\n n_up, n1, n2 = int(n_up), int(n1), int(n2)\n\n if x.ndim == 1:\n pad_width = (n1, n2)\n elif x.ndim == 2:\n pad_width = [(0, 0), (n1, n2)]\n\n # comments use (n=4, n1=4, n2=3) as example, but this combination can't occur\n if padtype == 'zero':\n # [1,2,3,4] -> [0,0,0,0, 1,2,3,4, 0,0,0]\n xp = np.pad(x, pad_width)\n elif padtype == 'reflect':\n # [1,2,3,4] -> [3,4,3,2, 1,2,3,4, 3,2,1]\n xp = np.pad(x, pad_width, mode='reflect')\n elif padtype == 'replicate':\n # [1,2,3,4] -> [1,1,1,1, 1,2,3,4, 4,4,4]\n xp = np.pad(x, pad_width, mode='edge')\n elif padtype == 'wrap':\n # [1,2,3,4] -> [1,2,3,4, 1,2,3,4, 1,2,3]\n xp = np.pad(x, pad_width, mode='wrap')\n elif padtype == 'symmetric':\n # [1,2,3,4] -> [4,3,2,1, 1,2,3,4, 4,3,2]\n if x.ndim == 1:\n xp = np.hstack([x[::-1][-n1:], x, x[::-1][:n2]])\n elif x.ndim == 2:\n xp = np.hstack([x[:, ::-1][:, -n1:], x, x[:, ::-1][:, :n2]])\n\n Npad = xp.shape[-1]\n _ = (Npad, n_up, n1, N, n2)\n assert (Npad == n_up == n1 + N + n2), \"%s ?= %s ?= %s + %s + %s\" % _\n return (xp, n_up, n1, n2) if get_params else xp\n\n\ndef trigdiff(A, fs=1, padtype=None, rpadded=None, N=None, n1=None):\n \"\"\"Trigonometric / frequency-domain differentiation; see `difftype` in\n `help(ssq_cwt)`. Used internally by `ssq_cwt` with `order > 0`.\n \"\"\"\n from ..wavelets import _xifn\n from . import backend as S\n\n assert isinstance(A, np.ndarray) or S.is_tensor(A), type(A)\n assert A.ndim == 2\n\n rpadded = rpadded or False\n padtype = padtype or ('reflect' if not rpadded else None)\n if rpadded and (n1 is None or N is None):\n raise ValueError(\"must pass `n1` and `N` if `rpadded`\")\n\n if padtype is not None:\n A, _, n1, *_ = padsignal(A, padtype, get_params=True)\n\n xi = S.asarray(_xifn(1, A.shape[-1])[None], A.dtype)\n\n A_freqdom = fft(A, axis=-1, astensor=True)\n A_diff = ifft(A_freqdom * 1j * xi * fs, axis=-1, astensor=True)\n\n if rpadded:\n A_diff = A_diff[:, n1:n1+N]\n if S.is_tensor(A_diff):\n A_diff = A_diff.contiguous()\n return A_diff\n\n\ndef est_riskshrink_thresh(Wx, nv):\n \"\"\"Estimate the RiskShrink hard thresholding level, based on [1].\n This has a denoising effect, but risks losing much of the signal; it's larger\n the more high-frequency content there is, even if not noise.\n\n # Arguments:\n Wx: np.ndarray\n CWT of a signal (see `cwt`).\n nv: int\n Number of voices used in CWT (see `cwt`).\n\n # Returns:\n gamma: float\n The RiskShrink hard thresholding estimate.\n\n # References:\n 1. The Synchrosqueezing algorithm for time-varying spectral analysis:\n robustness properties and new paleoclimate applications.\n G. Thakur, E. Brevdo, N.-S. Fučkar, and H.-T. Wu.\n https://arxiv.org/abs/1105.0010\n\n 2. Synchrosqueezing Toolbox, (C) 2014--present. E. Brevdo, G. Thakur.\n https://github.com/ebrevdo/synchrosqueezing/blob/master/synchrosqueezing/\n est_riskshrink_thresh.m\n \"\"\"\n N = Wx.shape[1]\n Wx_fine = np.abs(Wx[:nv])\n gamma = 1.4826 * np.sqrt(2 * np.log(N)) * mad(Wx_fine)\n return gamma\n\n\ndef find_closest_parallel_is_faster(shape, dtype='float32', trials=7, verbose=1):\n \"\"\"Returns True if `find_closest(, parallel=True)` is faster, as averaged\n over `trials` trials on dummy data.\n \"\"\"\n from timeit import timeit\n from ..algos import find_closest\n\n a = np.abs(np.random.randn(*shape).astype(dtype))\n v = np.random.uniform(0, len(a), len(a)).astype(dtype)\n\n t0 = timeit(lambda: find_closest(a, v, parallel=False), number=trials)\n t1 = timeit(lambda: find_closest(a, v, parallel=True), number=trials)\n if verbose:\n print(\"Parallel avg.: {} sec\\nNon-parallel avg.: {} sec\".format(\n t1 / trials, t0 / trials))\n return t1 > t0\n\n\ndef mad(data, axis=None):\n \"\"\"Mean absolute deviation\"\"\"\n return np.mean(np.abs(data - np.mean(data, axis)), axis)\n\n\ndef assert_is_one_of(x, name, supported, e=ValueError):\n if x not in supported:\n raise e(\"`{}` must be one of: {} (got {})\".format(\n name, ', '.join(supported), x))\n\n\ndef _textwrap(txt, wrap_len=50):\n \"\"\"Preserves line breaks and includes `'\\n'.join()` step.\"\"\"\n return '\\n'.join(['\\n'.join(\n wrap(line, wrap_len, break_long_words=False, replace_whitespace=False))\n for line in txt.splitlines() if line.strip() != ''])\n","sub_path":"ssqueezepy/utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":7886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"198541822","text":"from datetime import datetime\nfrom datetime import timedelta\n\nimport pandas as pd\nimport pandas_market_calendars as mcal\n\nclass MarketHours():\n\n def __init__(self) -> None:\n\n \"\"\" \n The code was added below to obtain market hours data from the NYSE\n \n Pip Install: pip install pandas_market_calendars\n Github site: https://github.com/rsheftel/pandas_market_calendars\n Github usage: https://github.com/rsheftel/pandas_market_calendars/blob/master/examples/usage.ipynb\n \n The calendar for the NYSE is obtained \n The calendar only contains actual days the market is open\n The calendar does not include weekends and holidays\n \"\"\"\n self.nyse = mcal.get_calendar('NYSE')\n \n # The market date, which is tested, is for today\n self.market_date = datetime.today().replace(\n hour=0,\n minute=0,\n second=0,\n microsecond=0\n )\n\n # The hours of the market are returned in a Pandas DataFrame\n # The market open and market close are included for today\n self.hours = self.nyse.schedule(start_date=self.market_date, end_date=self.market_date)\n\n self.right_now = datetime.utcnow().timestamp()\n\n if len(self.hours.index) > 0:\n \n # Market open is the value in the market_open column\n self.market_open_column = self.hours['market_open']\n self.market_open = self.market_open_column[0].to_pydatetime()\n self.market_open_time = self.market_open.timestamp()\n \n # Market close is the value in the market_close column\n self.market_close_column = self.hours['market_close']\n self.market_close = self.market_close_column[0].to_pydatetime()\n self.market_close_time = self.market_close.timestamp()\n\n # Pre-Market opens 5 hours 30 minutes prior to the regular market\n self.pre_market_open = self.market_open - timedelta(hours=5, minutes=30)\n self.pre_market_open_time = self.pre_market_open.timestamp()\n\n # Post-Market remaines open 4 hours after the regular market\n self.post_market_close = self.market_close + timedelta(hours=4)\n self.post_market_close_time = self.post_market_close.timestamp()\n\n else:\n # Without a market open and close, the market will not be open at all today\n # All variables are set to the begining of the next day (1 day)\n self.market_open_time = self.market_date + timedelta(days=1)\n self.market_close_time = self.market_open_time\n self.pre_market_open_time = self.market_open_time\n self.post_market_close_time = self.market_open_time\n\n @property\n def regular_market_open(self) -> bool:\n \n market_open_time = self.market_open_time\n market_close_time = self.market_close_time\n right_now = self.right_now\n\n if market_open_time <= right_now <= market_close_time:\n return True\n else:\n return False\n\n @property\n def pre_market_open(self) -> bool:\n \n pre_market_open_time = self.pre_market_open_time\n pre_market_close_time = self.market_open_time\n right_now = self.right_now\n\n if pre_market_open_time <= right_now <= pre_market_close_time:\n return True\n else:\n return False\n\n @property\n def post_market_open(self) -> bool:\n \n post_market_open_time = self.market_close_time\n post_market_close_time = self.post_market_close_time\n right_now = self.right_now\n\n if post_market_open_time <= right_now <= post_market_close_time:\n return True\n else:\n return False\n","sub_path":"pyrobot/market_hours.py","file_name":"market_hours.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"552193455","text":"import datetime as datetime\r\nfrom flask import request\r\nfrom flask_login import login_required\r\nfrom models import Event, Fest, Result\r\nfrom connection import DatabaseHandler\r\nfrom . import event_result\r\n\r\nsession = DatabaseHandler.connect_to_database()\r\n\r\n@event_result.route('/get/', methods=['GET'])\r\ndef get_result(event_id):\r\n # event = request.data['event']\r\n result = Result.query.filter_by(event_id=event_id).first()\r\n result_json = {\r\n 'event_id':result.event_id,\r\n 'first_name':result.first_name,\r\n 'first_institution':result.first_institution,\r\n 'second_name':result.second_name,\r\n 'second_institution':result.second_institution,\r\n 'third_name':result.third_name,\r\n 'third_institution':result.third_institution\r\n }\r\n return {\r\n 'status':'OK',\r\n 'message':'SUCCESS',\r\n 'result':result_json\r\n }, 200\r\n\r\n@event_result.route('/add', methods=['GET','POST'])\r\n@login_required\r\ndef add_result():\r\n if request.method == 'POST':\r\n event = request.data['event']\r\n first_name = request.data['first_name']\r\n first_institution = request.data['first_institution']\r\n second_name = request.data['second_name']\r\n second_institution = request.data['second_institution']\r\n third_name = request.data['third_name']\r\n third_institution = request.data['third_institution']\r\n if not Event.query.filter_by(id=event).first():\r\n return {\r\n 'status':'BAD REQUEST',\r\n 'message':'EVENT DOES NOT EXIST'\r\n }\r\n info = Result(event_id=event, first_name=first_name, first_institution=first_institution, \\\r\n second_name=second_name, second_institution=second_institution, third_name=third_name, \\\r\n third_institution=third_institution)\r\n session.add(info)\r\n session.commit()\r\n return {\r\n 'status':'OK',\r\n 'message':'SUCCESSFULLY ADDED RESULT'\r\n }, 200\r\n else:\r\n return {\r\n 'status':'OK',\r\n 'message':'RUNNING'\r\n }, 200\r\n","sub_path":"my_routes/result.py","file_name":"result.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"626377559","text":"#MBGD小批量梯度下降算法\r\nfrom matplotlib import pyplot as plt\r\nimport random\r\n\r\n\r\n#生成数据\r\ndef data():\r\n x = range(40)\r\n y = [(3 * i + 2) for i in x]\r\n for i in range(len(y)):\r\n y[i] = y[i] + random.randint(-20, 20)\r\n return x, y\r\n\r\n\r\n#用小批量梯度下降算法进行迭代\r\ndef MBGD(x, y):\r\n error0 = 0\r\n error1 = 0\r\n n = 0\r\n m = len(x)\r\n esp = 1e-5\r\n step_size = 0.001 #选择合理的步长\r\n a = random.randint(0, 10) #给a,b赋初始值\r\n b = random.randint(0, 10)\r\n while True:\r\n trainList = []\r\n for i in range(5): #创建随机的批量\r\n trainList.append(random.randint(0, m - 1))\r\n for i in range(5): #对数据进行迭代计算\r\n s = trainList[i]\r\n sum0 = a * x[s] + b - y[s]\r\n sum1 = (a * x[s] + b - y[s]) * x[s]\r\n error1 = error1 + (a * x[s] + b - y[s])**2\r\n a = a - sum1 * step_size / m\r\n b = b - sum0 * step_size / m\r\n print('a=%f,b=%f' % (a, b))\r\n if error1 - error0 < esp:\r\n break\r\n n = n + 1\r\n if n > 2000:\r\n break\r\n return a, b\r\n\r\n\r\nif __name__ == '__main__':\r\n x, y = data()\r\n a, b = MBGD(x, y)\r\n X = range(len(x))\r\n Y = [(a * i + b) for i in X]\r\n plt.scatter(x, y, color='red')\r\n plt.plot(X, Y, color='blue')\r\n plt.show()","sub_path":"E3_MBGD.py","file_name":"E3_MBGD.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"650084150","text":"#==================================================\n#__________________________________________________\n\n# Copyrigth 2016 A. Farchi and M. Bocquet\n# CEREA, joint laboratory Ecole des Ponts ParisTech and EDF R&D\n\n# Code for the paper: Using the Wasserstein distance to compare fields of pollutants:\n# Application to the radionuclide atmospheric dispersion of the Fukushima-Daiichi accident\n# by A. Farchi, M. Bocquet, Y. Roustan, A. Mathieu and A. Querel\n\n#__________________________________________________\n#==================================================\n\n#####################\n# computeOperators.py\n#####################\n#\n# applies the operators defined in operators*.py on the result of a simulation\n#\n\nimport numpy as np\nimport cPickle as pck\n\nfrom operators1 import listOfOperators1 as defineListOfOperators1\nfrom operators2 import listOfOperators2 as defineListOfOperators2\n\ndef extractIterations(outputDir):\n '''\n Extracts the iteration numbers from config file for a simulation\n '''\n fileConfig = outputDir + 'config.bin'\n\n f = open(fileConfig,'rb')\n p = pck.Unpickler(f)\n data = []\n try:\n while True:\n config = p.load()\n data.append( ( config.iterTarget , config.nModWrite ) )\n except:\n f.close()\n \n runs = []\n iStart = 0\n size = 0\n for (iterTarget, nMod) in data:\n sizeRun = 1 + int( np.floor((iterTarget-1.)/nMod) )\n runs.append( np.arange(sizeRun)*nMod + iStart + 2. )\n iStart += iterTarget\n size += sizeRun\n\n iterationNumbers = np.zeros(size)\n i = 0\n for run in runs:\n iterationNumbers[i:i+run.size] = run[:]\n i += run.size\n\n return iterationNumbers\n\ndef applyOperators(listOfOperators1, listOfOperators2, outputDir):\n '''\n Apply operators to all states of a simulation\n '''\n\n print('Starting analyse in '+outputDir+' ...')\n\n iterationNumbers = extractIterations(outputDir)\n size = iterationNumbers.size\n\n iterationTimes = np.zeros(size)\n values = np.zeros(shape=(size,len(listOfOperators1)+len(listOfOperators2)))\n\n i = 0\n\n fileFinalState = outputDir + 'finalState.bin'\n f = open(fileFinalState, 'rb')\n p = pck.Unpickler(f)\n finalState = p.load().convergingStaggeredField()\n f.close()\n\n fileStates = outputDir + 'states.bin'\n f = open(fileStates,'rb')\n p = pck.Unpickler(f)\n\n while i < size :\n state = p.load()\n iterationTimes[i] = p.load()\n for j in xrange(len(listOfOperators1)):\n values[i,j] = listOfOperators1[j][0](state)\n for j in xrange(len(listOfOperators2)):\n values[i,len(listOfOperators1)+j] = listOfOperators2[j][0](state,finalState)\n i += 1\n f.close()\n\n operatorNames = []\n for op in listOfOperators1:\n operatorNames.append(op[1])\n for op in listOfOperators2:\n operatorNames.append(op[1])\n\n iterationTimes = np.cumsum(iterationTimes)\n\n fileAnalyse = outputDir + 'analyse.bin'\n f = open(fileAnalyse, 'wb')\n p = pck.Pickler(f,protocol=-1)\n p.dump(iterationNumbers)\n p.dump(iterationTimes)\n p.dump(operatorNames)\n p.dump(values)\n f.close()\n\n print ('Results written in '+fileAnalyse+' ...')\n return ( iterationNumbers, iterationTimes, values )\n \ndef applyAllOperators(outputDir):\n listOfOperators1 = defineListOfOperators1()\n listOfOperators2 = defineListOfOperators2()\n return applyOperators(listOfOperators1, listOfOperators2, outputDir)\n","sub_path":"OT/OTObjects1D/analyse/computeOperators.py","file_name":"computeOperators.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"407787903","text":"from django.shortcuts import render\nimport datetime\n\n# Create your views here.\ndef index(request):\n dt = datetime.datetime.now()\n context = {\n 'date' : dt.strftime( '%b %d, %Y' ),\n 'time' : dt.strftime( '%I:%M:%S %p' ),\n }\n return render(request, 'TimeDisplay/index.html', context)","sub_path":"TimeDisplay/apps/TimeDisplay/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"322981151","text":"import argparse\nimport json\nimport os\nfrom datetime import datetime\n\nfrom annotation_predictor.util.oid_classcode_reader import OIDClassCodeReader\nfrom settings import annotation_predictor_metadata_dir, \\\n known_class_ids_annotation_predictor\n\nevaluation_record = {}\n\ndef create_evaluation_record(path_to_detection_record: str):\n \"\"\"\n Create and save a record which represents the performance of an object-detector for each class\n of the Open Images Dataset.\n Args:\n path_to_detection_record: detection-record created by create_detection_record.py\n \"\"\"\n oid_classcode_reader = OIDClassCodeReader()\n with open(known_class_ids_annotation_predictor) as f:\n class_ids_oid = json.load(f)\n for cls in class_ids_oid:\n evaluation_record.update({class_ids_oid[cls]: [0, []]})\n\n with open(path_to_detection_record) as file:\n detections = json.load(file)\n\n for image_id in detections:\n for det in detections[image_id]:\n cls = oid_classcode_reader.get_human_readable_label_for_code(det['LabelName'])\n score = det['Confidence']\n if evaluation_record[cls][0] < score:\n evaluation_record[cls][0] = score\n evaluation_record[cls][1].append(score)\n\n for i in evaluation_record:\n record = evaluation_record[i]\n if len(record[1]) == 0:\n record[1] = 0.0\n else:\n record[1] = sum(record[1]) / len(record[1])\n\n timestamp = datetime.now().strftime('%Y_%m_%d_%H%M%S')\n path_to_json = os.path.join(annotation_predictor_metadata_dir,\n '{}_evaluation.json'.format(timestamp))\n with open(path_to_json, 'w') as f:\n json.dump(evaluation_record, f)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='Create and save an evaluation record for the object detection network')\n parser.add_argument('path_to_detection_record', type=str, metavar='path_to_detection_record',\n help='path to detection record')\n args = parser.parse_args()\n\n create_evaluation_record(args.path_to_detection_record)\n","sub_path":"annotation_predictor/create_evaluation_record.py","file_name":"create_evaluation_record.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"240948325","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# License: 3 Clause BSD\n# http://scikit-criteria.org/\n\n\n# =============================================================================\n# DOCS\n# =============================================================================\n\n\"\"\"This file is for distribute scikit-criteria\n\n\"\"\"\n\n\n# =============================================================================\n# IMPORTS\n# =============================================================================\n\nimport sys\n\nfrom ez_setup import use_setuptools\nuse_setuptools()\n\nfrom setuptools import setup, find_packages\n\nimport skcriteria\n\n\n# =============================================================================\n# CONSTANTS\n# =============================================================================\n\nREQUIREMENTS = [\n \"numpy\", \"scipy\", \"six\"\n]\n\n\n# =============================================================================\n# FUNCTIONS\n# =============================================================================\n\ndef do_setup():\n setup(\n name=skcriteria.NAME,\n version=skcriteria.VERSION,\n description=skcriteria.DOC,\n author=skcriteria.AUTHORS,\n author_email=skcriteria.EMAIL,\n url=skcriteria.URL,\n license=skcriteria.LICENSE,\n keywords=skcriteria.KEYWORDS,\n classifiers=(\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Education\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.4\",\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: Implementation :: CPython\",\n \"Topic :: Scientific/Engineering\",\n ),\n packages=[\n pkg for pkg in find_packages() if pkg.startswith(\"skcriteria\")],\n py_modules=[\"ez_setup\"],\n install_requires=REQUIREMENTS,\n )\n\n\ndef do_publish():\n pass\n\n\nif __name__ == \"__main__\":\n if sys.argv[-1] == 'publish':\n do_publish()\n else:\n do_setup()\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"561034244","text":"import json\nimport random\nfrom vqa_model import ADICT_PATH\n\n\ndef get_vqa_data(is_train, sampling_ratio=1):\n\twith open(ADICT_PATH, 'r') as f:\n\t\tanswer_vocab = json.load(f)\n\tif is_train:\n\t\tannotations = json.load(open('Data/mscoco_train2014_annotations.json'))['annotations']\n\t\tquestions = json.load(open('Data/OpenEnded_mscoco_train2014_questions.json'))['questions']\n\t\timages_path = 'Data/train2014/COCO_train2014_'\n\telse:\n\t\tannotations = json.load(open('Data/mscoco_val2014_annotations.json'))['annotations']\n\t\tquestions = json.load(open('Data/OpenEnded_mscoco_val2014_questions.json'))['questions']\n\t\timages_path = 'Data/val2014/COCO_val2014_'\n\tvqa_triplets = list()\n\tfor question, annotation in zip(questions, annotations):\n\t\tanswer = annotation['multiple_choice_answer']\n\t\tif answer not in answer_vocab:\n\t\t\tcontinue\n\t\tif question['question_id'] != annotation['question_id']:\n\t\t\traise AssertionError(\"question id's are not equal\")\n\t\tq = question['question']\n\t\timg_num = str(question['image_id'])\n\t\timg_path = images_path\n\t\tfor i in range(12 - len(img_num)):\n\t\t\timg_path += '0'\n\t\timg_path += img_num + '.jpg'\n\t\tvqa_triplets.append((q, answer, img_path))\n\tif sampling_ratio < 1:\n\t\tvqa_triplets = random.sample(vqa_triplets, int(round(len(vqa_triplets) * sampling_ratio)))\n\treturn vqa_triplets\n","sub_path":"server_tensorflow/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"494541982","text":"# -*- coding: utf-8 -*-\r\nfrom urllib import *\r\n\r\nfrom django.http import HttpResponseRedirect, Http404,HttpResponse\r\nfrom django.shortcuts import render_to_response,redirect\r\nfrom booking.models import *\r\nfrom django.views.decorators.csrf import csrf_exempt\r\nfrom django.template import RequestContext\r\nfrom datetime import timedelta,datetime\r\nfrom django.db.models import Max\r\nfrom django.db import connection\r\nfrom django.template.loader import render_to_string\r\nfrom django.utils.html import strip_tags\r\nfrom django.core.mail import EmailMultiAlternatives\r\nimport time\r\n \r\n \r\n\r\ndef logout(request):\r\n\r\n del request.session['loggedUser']\r\n return HttpResponseRedirect('/booking')\r\n\r\ndef home(request):\r\n action='home'\r\n if 'loggedUser' in request.session:\r\n action='loggedin'\r\n return render_to_response('booking/index.html', {'action':action}, context_instance=RequestContext(request))\r\n\r\n\r\ndef login(request):\r\n \r\n username=request.POST.get('username',False)\r\n password=request.POST.get('password',False)\r\n \r\n if 'loggedUser' in request.session:\r\n return HttpResponseRedirect('/booking')\r\n \r\n try:\r\n user = cliente.objects.get(username__exact=username,password__exact=password)\r\n if user.published:\r\n request.session['loggedUser'] = user.id\r\n action='loggedin'\r\n else:\r\n action='waiting'\r\n \r\n \r\n except Exception: \r\n action='data_error'\r\n\r\n return render_to_response('booking/home.html', {'action':action}, context_instance=RequestContext(request))\r\n \r\n \r\n \r\n\r\n \r\n\r\n\r\ndef register(request):\r\n import hashlib\r\n if request.method == 'POST':\r\n \r\n nome = request.POST.get('nome',False)\r\n cognome = request.POST.get('cognome',False)\r\n mail = request.POST.get('email',False)\r\n telefono = request.POST.get('telefono',False)\r\n username = request.POST.get('username',False)\r\n password = request.POST.get('password',False)\r\n \r\n user, created = cliente.objects.get_or_create(nome=nome,cognome=cognome,mail=mail,telefono=telefono,username=username,password=password)\r\n if created: \r\n m = hashlib.md5()\r\n m.update(mail)\r\n \r\n user.hashkey=m.hexdigest()\r\n user.published=False\r\n user.save();\r\n \r\n subject, from_email, to = 'Conferma creazione account su Chiango.com', 'no-reply@chiango.com', mail\r\n \r\n html_content = render_to_string('booking/confirmation_mail.html', {'hash':user.hashkey}) # ...\r\n text_content = strip_tags(html_content) # this strips the html, so people will have the text as well.\r\n \r\n # create the email, and attach the HTML version as well.\r\n msg = EmailMultiAlternatives(subject, text_content, from_email, [to],bcc=[\"davide.genti@gmail.com\"],)\r\n msg.attach_alternative(html_content, \"text/html\")\r\n msg.send()\r\n return render_to_response('booking/register_2.html', {'action':'email_sent'}, context_instance=RequestContext(request))\r\n else:\r\n return render_to_response('booking/register_2.html', {'action':'already_registered'}, context_instance=RequestContext(request))\r\n else:\r\n return render_to_response('booking/register_2.html', {}, context_instance=RequestContext(request))\r\n \r\n\r\n \r\n \r\n@csrf_exempt\r\ndef activate(request,hashkey):\r\n user = cliente.objects.get(hashkey__exact=hashkey)\r\n action=''\r\n if user.published:\r\n action='fake'\r\n else:\r\n user.published=True\r\n user.save() \r\n return render_to_response('booking/home.html', {'action':'activated'}, context_instance=RequestContext(request)) \r\n\r\n\r\ndef sendReservationEmail(mail,data,ora,servizio): \r\n subject, from_email, to = 'Conferma prenotazione su Chiango.com', 'no-reply@chiango.com', mail\r\n \r\n html_content = render_to_string('booking/reservation_email.html', {'data':data,'ora':ora,'servizio':servizio}) # ...\r\n text_content = strip_tags(html_content) # this strips the html, so people will have the text as well.\r\n \r\n # create the email, and attach the HTML version as well.\r\n msg = EmailMultiAlternatives(subject, text_content, from_email, [to],bcc=[\"davide.genti@gmail.com\"],)\r\n msg.attach_alternative(html_content, \"text/html\")\r\n msg.send() \r\n \r\ndef reservation(request):\r\n postData=False\r\n try:\r\n user=cliente.objects.get(pk__exact=request.session['loggedUser'])\r\n except Exception: \r\n return HttpResponseRedirect('/booking/')\r\n checkData='ok' \r\n if request.method == 'POST':\r\n values=request.POST.get('reservation',False)\r\n \r\n \r\n if values:\r\n postData=True\r\n (data,orario) = values.split('|')\r\n aval_data= availableDates.objects.get(pk__exact=data)\r\n aval_orario = availableTimes.objects.get(pk__exact=orario)\r\n \r\n checkData = prenotazione.objects.filter(cliente=user,data=aval_data)\r\n if not checkData:\r\n obj,created = prenotazione.objects.get_or_create(cliente=user,data=aval_data,orario=aval_orario)\r\n if created:\r\n \r\n sendReservationEmail(user.mail,aval_data.data,aval_orario.orario,aval_orario.get_servizio_display)\r\n checkData='new_reg' \r\n #return HttpResponseRedirect('/booking/reservations/')\r\n else:\r\n checkData='nok' \r\n\r\n all_reservations=prenotazione.objects.filter()\r\n date_res=[]\r\n ore_res=[]\r\n \r\n for item in all_reservations:\r\n date_res.append(item.data)\r\n ore_res.append(item.orario)\r\n \r\n user_reservations=prenotazione.objects.filter(cliente=user)\r\n \r\n date = (time.strftime(\"%Y-%m-%d\"))\r\n disponibilita=availableDates.objects.filter(data__gt=date)\r\n \r\n return render_to_response('booking/reservations_2.html', {'postData':postData,'SERVICE':SERVICE,'checkData':checkData,'ore_res':ore_res,'date_res':date_res,'disponibilita':disponibilita,'user_reservations':user_reservations}, context_instance=RequestContext(request)) \r\n\r\ndef contact(request):\r\n subject, from_email, to = 'Contatto dal sito', request.POST.get('email'), 'davide.genti@gmail.com'\r\n \r\n html_content = render_to_string('booking/contact_email.html', {'subject':request.POST.get('subject'),'name':request.POST.get('name'),'body':request.POST.get('body')}) # ...\r\n text_content = strip_tags(html_content) # this strips the html, so people will have the text as well.\r\n \r\n # create the email, and attach the HTML version as well.\r\n msg = EmailMultiAlternatives(subject, text_content, from_email, [to],bcc=[\"davide.genti@gmail.com\"],)\r\n msg.attach_alternative(html_content, \"text/html\")\r\n msg.send()\r\n\r\n\r\n\r\n\r\ndef sendReminderEmail(item):\r\n subject, from_email, to = 'Reminder prenotazione su Chiango.com', 'no-reply@chiango.com', item.cliente.mail\r\n \r\n html_content = render_to_string('booking/reminder_email.html', {'data':item.data.data,'ora':item.orario.orario}) # ...\r\n text_content = strip_tags(html_content) # this strips the html, so people will have the text as well.\r\n \r\n # create the email, and attach the HTML version as well.\r\n msg = EmailMultiAlternatives(subject, text_content, from_email, [to],bcc=[\"davide.genti@gmail.com\"],)\r\n msg.attach_alternative(html_content, \"text/html\")\r\n msg.send() \r\n \r\ndef crontab(request):\r\n date = (time.strftime(\"%Y-%m-%d\"))\r\n today_obj = availableDates.objects.filter(data=date)\r\n today_reservations=prenotazione.objects.filter(data=today_obj)\r\n \r\n for item in today_reservations:\r\n sendReminderEmail(item) \r\n return HttpResponse(\"\")","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"595195898","text":"from __future__ import print_function\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn import cross_validation as cv\nfrom collections import deque\n\n\ncv = 0\ndef accuracy(predictions, labels):\n return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))\n / predictions.shape[0])\n\nclass ConnectedLayer:\n def __init__(self, graph, layers, activation_functions, dropout = None, input_data = None):\n self.layer_type = 'fc'\n self.graph = graph\n self.weights = [None] * (len(layers)-1)\n self.biases = [None]*(len(layers)-1)\n self.logits = [None]*(len(layers)-1)\n self.predict_tensor = None\n self.input_data = input_data\n with self.graph.as_default():\n \n prev_layer = deque(maxlen=1)\n prev_layer.append(self.input_data)\n for i in range(len(layers)-1):\n #weights and biases for layer i\n print(\"layer {} {}x{}\".format(i, layers[i], layers[i+1]))\n self.weights[i] = tf.Variable(tf.truncated_normal([layers[i], layers[i+1]], stddev = 0.1))\n self.biases[i] = tf.Variable(tf.zeros([layers[i+1]]))\n \n #Now create operations for each layer using appropriate activation functions\n if i < len(activation_functions) and activation_functions[i] == 'relu':\n self.logits[i] = tf.nn.relu((tf.matmul(prev_layer[0], self.weights[i]) + self.biases[i]))\n elif i < len(activation_functions) and activation_functions[i] == 'relu6':\n self.logits[i] = tf.nn.relu6((tf.matmul(prev_layer[0], self.weights[i]) + self.biases[i]))\n elif i < len(activation_functions) and activation_functions[i] == 'softmax':\n self.logits[i] = tf.nn.softmax((tf.matmul(prev_layer[0], self.weights[i]) + self.biases[i]))\n elif i < len(activation_functions) and activation_functions[i] == 'linear':\n self.logits[i] = tf.matmul(prev_layer[0], self.weights[i] + self.biases[i])\n else: #Default is tanh\n self.logits[i] = tf.tanh(tf.matmul(prev_layer[0], self.weights[i] + self.biases[i]))\n\n if dropout != None:\n self.logits[i] = tf.nn.dropout(self.logits[i], dropout)\n \n #push this layer into deque to reference to in the next one\n prev_layer.append(self.logits[i])\n\n self.output = self.logits[-1]\n self.output_size = layers[-1]\n\n def regularize(self, regularization):\n regs = tf.nn.l2_loss(self.weights[0])\n for weight in self.weights[1:]:\n regs += tf.nn.l2_loss(weight)\n regs = regularization * regs\n return regs\n \n","sub_path":"src/deeplayer.py","file_name":"deeplayer.py","file_ext":"py","file_size_in_byte":2872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"160369666","text":"def upend_number(number):\n # Функция принимает число\n # Функция возвращает перевернутое число\n # 1. Предполагается, что никто не будет в эту функцию пихать значение, не типа int.\n # 2. Предполагается, что никто не будет сюда пихать не натуральное число.\n\n # Берем наше число и переводим в строку\n number_str = str(number)\n # Объявляем переменную для результата этой функции\n result_str = \"\"\n # В цикле иттерируемся по символам строки с числом и каждый раз добавляем символ в начало строки с результатом,\n # в конце у нас получится строка с перевернутым числом\n for n in number_str:\n result_str = n + result_str\n # переводим строку с результатом в число и возвращаем из функции\n return int(result_str)\n\n\ndef is_palindrome(number):\n # Функция принимает число\n # Функция возвращает логическое значение:\n # True - значит переданное число, является полиндромом;\n # False - значит переданное число не является полиндромо;\n # 1. Предполагается, что никто не будет в эту функцию пихать значение, не типа int.\n # 2. Предполагается, что никто не будет сюда пихать не натуральное число.\n\n # Если число меньше 10, то возвращаем True, т.к. любая обычная цифра будет полиндромом.\n if number < 10:\n return True\n\n # Берем наше число и переводим в строку.\n number_str = str(number)\n\n # Вытаскиваем половину левую половину нашего числа.\n left_half_number_str = number_str[:len(number_str) // 2]\n # Объявляем переменную под правую половину нашего числа.\n right_half_number_str = \"\"\n\n if len(number_str) % 2 == 1:\n # Если длина строки с нашим числом не четная, то мы вытаскиваем правую часть,\n # без средней цифры в исходном числе.\n right_half_number_str = number_str[len(number_str) // 2 + 1:]\n elif len(number_str) % 2 == 0:\n # Если длина строки с нашим числом четная, то мы вытаскиваем правую часть ровно по половине исходного числа,\n # т.к. средней цифры в нем нет.\n right_half_number_str = number_str[len(number_str) // 2:]\n\n # Далее мы берем левую часть числа и переворачиваем, соответственно, если переврнутая строка с этой половиной\n # будет равна правой половине числа, то значит, что число является полиндромом.\n return str(upend_number(left_half_number_str)) == right_half_number_str\n\n\n# Здесь начинается программа\n\n# Просим пользователя ввести число X\nx = int(input(\"Введите число X: \"))\n# Объявляем переменную для подсчета количества операций\ncount_operation = 0\n\n\nif 0 < x:\n # Если число натуральное, то производим вычисления\n\n # Пока из функции is_polindrome будет возвращаться False, то есть число не полиндром, мы будем\n # производить операции расположенные в теле цикла.\n while is_palindrome(x) is False:\n # Прибавляем к счетчику 1\n count_operation += 1\n # print(x) # При необходимости, убрать символ комментария в начале строки,\n # тогда в процессе выполнения будут выводится числа, которые образуются в момент операций\n\n # Прибавляем к X перевернутое число\n x += upend_number(x)\n\n # Выводим результат\n print(\"Число: \" + str(x))\n print(\"Количество операций: \" + str(count_operation))\n\nelse:\n # Если число не натуральное, то выдаем ошибку\n print(\"Необходимо ввести натуральное число!\")\n","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":5067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"463623520","text":"# Author: Samuel Chin\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\n\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\nfrom constants import *\n\n'''\nReads a TFRecord file and parses the following information. It is \nimportant to ensure that the TFRecord has the following \"dictionary keys\".\n\nIf your images vary in size, the proper way to dynamically reshape it is to use\nimage = tf.reshape(image, tf.pack([height, width, 3]))\n\nHowever, there are many subtleties in doing that as functions like \ntf.image.resize_image_with_crop_or_pad, requires that the shape be known before hand.\nThe TF Team is currently working on such a fix, so we shouldn't trouble ourselves with\ntrying to do this dynamic thing. I raised this on StackOverflow:\n\nhttp://stackoverflow.com/questions/35773898/how-can-i-use-values-read-from-tfrecords-as-arguments-to-tf-set-shape\n\nWith this in mind, the function does only this:\n\nReturns: image, label, height, width, depth, Tensors, all decoded from the TFRecords.\n'''\ndef read_and_decode(filename_queue):\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue)\n features = tf.parse_single_example(\n serialized_example,\n # Defaults are not specified since both keys are required.\n features={\n 'image_raw': tf.FixedLenFeature([], tf.string),\n 'label': tf.FixedLenFeature([], tf.int64),\n 'height': tf.FixedLenFeature([], tf.int64),\n 'width': tf.FixedLenFeature([], tf.int64),\n 'depth': tf.FixedLenFeature([], tf.int64)\n })\n image = tf.decode_raw(features['image_raw'], tf.uint8)\n label = tf.cast(features['label'], tf.int32)\n height = tf.cast(features['height'], tf.int32)\n width = tf.cast(features['width'], tf.int32)\n depth = tf.cast(features['depth'], tf.int32)\n return image, label, height, width, depth\n\n'''\nInputs:\n image: one image tensor\n label: one label tensor\n min_queue_examples: number of examples to maintain the queue\n batch_size: size of batch generated\nOutputs:\n A batch of images and labels\n\n'''\ndef generate_image_and_label_batch(image, label, min_queue_examples,\n batch_size, train):\n if TRAIN or BATCH_EVAL:\n num_preprocess_threads = 16\n images, label_batch = tf.train.shuffle_batch(\n [image, label],\n batch_size=batch_size,\n num_threads=num_preprocess_threads,\n capacity=min_queue_examples + 3 * batch_size,\n min_after_dequeue=min_queue_examples)\n else:\n images, label_batch = tf.train.batch(\n [image, label],\n batch_size=batch_size,\n num_threads=1,\n capacity=min_queue_examples + 3 * batch_size)\n\n # Display the training images in the visualizer.\n tf.image_summary('images', images, max_images=100)\n return images, tf.reshape(label_batch, [batch_size])\n\ndef distortions(image):\n distorted_image = tf.random_crop(image, [NETWORK_IMAGE_SIZE, NETWORK_IMAGE_SIZE, 3])\n distorted_image = tf.image.random_brightness(distorted_image, max_delta=63)\n distorted_image = tf.image.random_contrast(distorted_image, lower=0.2, upper=1.8)\n return distorted_image\n\n\ndef inputs():\n if TRAIN:\n filename = os.path.join(DATA_DIR, TRAIN_FILE)\n else:\n filename = os.path.join(DATA_DIR, TEST_FILE)\n filename_queue = tf.train.string_input_producer([filename])\n image, label, height, width, depth = read_and_decode(filename_queue)\n image = tf.reshape(image, tf.pack([height, width, 3]))\n # image = tf.reshape(image, [INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE, 3])\n image = tf.cast(image, tf.float32)\n\n if TRAIN:\n image = distortions(image)\n else:\n '''\n This is the really retarded part of TensorFlow where the method below\n requires knowing the static shape. I need a fix ASAP.\n '''\n print (\"No Distortions\")\n image.set_shape([INPUT_IMAGE_SIZE, INPUT_IMAGE_SIZE, 3])\n image = tf.image.resize_image_with_crop_or_pad(image, NETWORK_IMAGE_SIZE, NETWORK_IMAGE_SIZE)\n\n # Subtract off the mean and divide by the variance of the pixels.\n float_image = tf.image.per_image_whitening(image)\n\n # Ensure that the random shuffling has good mixing properties.\n min_fraction_of_examples_in_queue = 0.4\n min_queue_examples = int(NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN *\n min_fraction_of_examples_in_queue)\n print ('Filling queue with %d images before starting to train. '\n 'This will take a few minutes.' % min_queue_examples)\n\n # Generate a batch of images and labels by building up a queue of examples.\n return generate_image_and_label_batch(float_image, label,\n min_queue_examples, BATCH_SIZE, TRAIN)","sub_path":"scratch/inputs.py","file_name":"inputs.py","file_ext":"py","file_size_in_byte":5373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"145017177","text":"'''\n\n判断数组中是否存在相同元素\n\nGiven an array of integers, find if the array contains any duplicates.\n\nYour function should return true if any value appears at least twice in the array, \nand it should return false if every element is distinct.\n\nExample 1:\n\nInput: [1,2,3,1]\nOutput: true\nExample 2:\n\nInput: [1,2,3,4]\nOutput: false\nExample 3:\n\nInput: [1,1,1,3,3,4,3,2,4,2]\nOutput: true\n\n'''\n\nclass Solution:\n def containsDuplicate(self, nums):\n n = len(nums)\n\n n_set=set()\n for i in range(0,n):\n if nums[i] in n_set:\n return True\n else:\n n_set.add(nums[i])\n return False\n\n\nif __name__ == '__main__':\n\n nums = [1,2,3,1]\n nums = [1,2,3,4]\n nums = [1,1,1,3,3,4,3,2,4,2]\n\n solution = Solution()\n result = solution.containsDuplicate(nums)\n print(result)\n\n\n","sub_path":"217. Contains Duplicate.py","file_name":"217. Contains Duplicate.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"455535568","text":"\nfrom grandMasters_all.board import Board\nimport random\nfrom grandMasters_all.util import print_board, print_slide, print_swing, reformat_board, part2_to_part1, part1_to_part2\nfrom collections import defaultdict\nimport numpy as np\n\nMOVETYPES = [\"THROWS\", \"SLIDES\", \"SWINGS\"]\n\n\"\"\"\nFEATURES TO CHANGE:\n\n- change opening\n- keep difference between our throws and opponent throws to be <= 1\n\"\"\"\n\n\n\"\"\" Class to represent a node in the MCTS \"statistics tree\" \"\"\"\nclass MCTSNode:\n \"\"\" Initialises a node in the MCTS tree, keeps track of relevant\n statistics used in the algorithm \"\"\"\n def __init__ (self, board, player, parent = None, last_action = None):\n self.board = board\n self.parent = parent\n\n # Move in form of (upper, lower) to get to current board\n self.last_action = last_action\n self.children = []\n\n # Dictionary to keep track values for each possible move for upper/lower\n # Used for DUCT algorithm for simultaneous MCTS\n self.resultsUpper = defaultdict(lambda: 0)\n self.resultsLower = defaultdict(lambda: 0)\n\n self.num_visits = 0\n # this is our player\n self.player = player\n\n # are we throwing too much?\n if player == \"UPPER\":\n self.throwsgap = ((self.board.unthrown_uppers-self.board.unthrown_lowers) >= -1)\n else:\n self.throwsgap = ((self.board.unthrown_lowers-self.board.unthrown_uppers) >= -1)\n\n self.simultaneous_moves = self.get_possible_moves_greedy(self.throwsgap)\n\n \"\"\" Get possible moves from current state \"\"\"\n def get_possible_moves(self):\n upper, lower = self.board.generate_turns()\n moveslist = []\n for uppermove in upper:\n for lowermove in lower:\n moveslist.append((uppermove, lowermove))\n # Moves is a list with all possible moves\n return moveslist\n\n def get_possible_moves_greedy(self, throwsgap):\n upper, lower = self.board.determine_greedy_moves_both(throwsgap)\n moveslist = []\n for uppermove in upper:\n for lowermove in lower:\n moveslist.append((uppermove, lowermove))\n # Moves is a list with all possible moves\n return moveslist\n\n \"\"\" Given a root node, generate children to explore \"\"\"\n def expand(self):\n move = self.simultaneous_moves.pop()\n\n nextboard = self.board.apply_turn2(move[0], move[1])\n\n child = MCTSNode(nextboard, self.switch_player(), parent=self, last_action=move)\n\n self.children.append(child)\n\n return child\n\n \"\"\" returns whether the game is done or not \"\"\"\n def is_terminal_node(self):\n return self.board.is_win(\"UPPER\") or self.board.is_win(\"LOWER\") or self.board.is_draw()\n\n \"\"\" Chooses a random move from a player's moveset. Used for rollout in MCTS.\n Must pass in the correct player's dictionary of moves\n EDIT THIS: USE RANDOM.CHOICE instead of doing random indexes\n \"\"\"\n def choose_random_move(self, moves):\n # Need to determine whether these type of moves are possible, i.e if there are any moves of that type\n possible_moves = [\"THROWS\", \"SLIDES\", \"SWINGS\"]\n\n # Get rid of movetypes with no moves\n for i in range(2, -1, -1):\n if not moves[possible_moves[i]]:\n possible_moves.pop(i)\n\n # Throw, slide or swing\n if len(possible_moves) == 1:\n rand_movetype = possible_moves[0]\n else:\n rand_movetype = random.choice(possible_moves)\n\n\n # Retrieve a random index to a move in the dictionary\n if len(moves[rand_movetype]) - 1 == 0:\n rand_move = moves[rand_movetype][0]\n else:\n rand_move = random.choice(moves[rand_movetype])\n\n # Index the move in the dict\n return moves[rand_movetype][rand_move]\n\n \"\"\" After a move is made, pass in the next player's turn into child nodes \"\"\"\n def switch_player(self):\n if self.player == \"UPPER\":\n return \"LOWER\"\n else:\n return \"UPPER\"\n\n \"\"\" Simulates a random game from given board\n For each iteration, move both player's pieces simultaneously\n \"\"\"\n\n def generate_random_board(self, turns):\n current_board = self.board\n while current_board.turn <= turns:\n upper, lower = current_board.generate_turns()\n rand1 = random.choice(upper)\n rand2 = random.choice(lower)\n\n current_board = current_board.apply_turn2(rand1, rand2)\n\n return current_board\n\n def rollout_random(self):\n current_board = self.board\n #print(\"NEW GAME\")\n while not (current_board.is_win(\"UPPER\") or current_board.is_draw() or current_board.is_win(\"LOWER\")):\n # Do this in order to randomize between movetype, then randomise between move\n #rand_move_p1 = self.choose_random_move(current_board.generate_seq_turn()[self.player])\n #rand_move_p2 = self.choose_random_move(current_board.generate_seq_turn()[self.switch_player()])\n\n # Do this for just random moves altogether\n # CHOOSE NEXT MOVE TO APPLY IN ROLLOUT\n upper, lower = current_board.generate_turns()\n rand_move_p1 = random.choice(upper)\n rand_move_p2 = random.choice(lower)\n\n current_board = current_board.apply_turn2(rand_move_p1, rand_move_p2)\n\n #print(current_board)\n #print_board(part2_to_part1(current_board))\n #print(current_board)\n #print(part1_to_part2(part2_to_part1(current_board)))\n return current_board.game_result(), current_board.turn\n\n \"\"\" Randomly chooses a greedy move \"\"\"\n def rollout_greedy(self):\n current_board = self.board\n #print(\"NEW GAME\")\n while not (current_board.is_win(\"UPPER\") or current_board.is_draw() or current_board.is_win(\"LOWER\")):\n\n # Determine greedy moves then choose random move\n upper, lower = current_board.determine_greedy_moves_both()\n\n rand_move_p1 = random.choice(upper)\n rand_move_p2 = random.choice(lower)\n\n current_board = current_board.apply_turn2(rand_move_p1, rand_move_p2)\n\n\n return current_board.game_result(), current_board.turn\n\n # Back propagates the result using DUCT. Update results in decoupled way\n # and add results for the move\n # Last action for root node is none\n def backpropagate(self, result):\n self.num_visits += 1\n #print(self.last_action)\n #print(self.board.thrown_uppers)\n #print(self.board.thrown_lowers)\n\n if self.parent is not None:\n # DOBULE CHECK THIS PARENT PROPAGATE CALL\n self.parent.resultsUpper[self.last_action[0]] += result\n self.parent.resultsLower[self.last_action[1]] += -result\n if self.parent is not None:\n self.parent.backpropagate(result)\n\n # Stop expanding if no more upper moves or no more lower moves\n def is_fully_expanded(self):\n return len(self.simultaneous_moves) == 0\n\n def best_child(self, c_param = 0.1):\n choices_weights_upper = [(c.q_upper() / c.n()) + c_param * np.sqrt((2 * np.log(self.n()) / c.n())) for c in self.children]\n choices_weights_lower = [(c.q_lower() / c.n()) + c_param * np.sqrt((2 * np.log(self.n()) / c.n())) for c in self.children]\n #print(choices_weights_upper)\n #print(self.children)\n upper_move = self.children[np.argmax(choices_weights_upper)].last_action[0]\n lower_move = self.children[np.argmax(choices_weights_upper)].last_action[1]\n\n # Assume that a node made from upper_move, lower_move exists?\n for child in self.children:\n if (upper_move, lower_move) == child.last_action:\n return child\n\n return None\n\n # Function that selects a node to rollout.\n def tree_policy(self):\n current_node = self\n while not current_node.is_terminal_node():\n if not current_node.is_fully_expanded():\n return current_node.expand()\n else:\n current_node = current_node.best_child()\n return current_node\n\n def q_upper(self):\n utility_value_upper = self.resultsUpper[self.last_action[0]]\n return utility_value_upper\n\n def q_lower(self):\n utility_lower = self.resultsLower[self.last_action[1]]\n return utility_lower\n\n def n(self):\n return self.num_visits\n\n def best_action(self, turns):\n simulation_no = turns\n\n for i in range(simulation_no):\n\n v = self.tree_policy()\n # Because rollout is giving out a tuple rn\n reward = v.rollout_greedy()[0]\n\n # Need to do: update current node -> backpropagate starting from parent since we're using last_action and root has no last_action\n if self.last_action:\n v.resultsUpper[self.last_action[0]] += result\n v.resultsLower[self.last_action[1]] += -result\n v.backpropagate(reward)\n\n return self.best_child(c_param=0.1)\n","sub_path":"skeleton-code-B/grandMasters_all/MCTS.py","file_name":"MCTS.py","file_ext":"py","file_size_in_byte":9099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"282689185","text":"\"\"\" 3D Peg - Copyright 2016 Kenichiro Tanaka \"\"\"\nimport sys\nfrom math import sin, cos, floor, sqrt, degrees\nfrom random import randint\nimport types\nimport pygame\nfrom pygame.locals import QUIT, KEYDOWN,\\\n K_LEFT, K_RIGHT, K_UP, K_DOWN\nfrom tiny_2d import Engine, RectangleEntity, CircleEntity\n\ndef normalize(vec):\n \"\"\" normalize the vector tuple (make the length to 1) \"\"\"\n scale = 1 / sqrt(vec[0]**2 + vec[1]**2 + vec[2]**2)\n return (vec[0]*scale, vec[1]*scale, vec[2]*scale)\n\ndef get_norm_vec(pos1, pos2, pos3):\n \"\"\" get the normal vector from 3 vertices (tuples) \"\"\"\n pvec = (pos1[0] - pos2[0], pos1[1] - pos2[1], pos1[2] - pos2[2])\n qvec = (pos1[0] - pos3[0], pos1[1] - pos3[1], pos1[2] - pos3[2])\n norm = (pvec[1]*qvec[2] - pvec[2]*qvec[1],\n pvec[2]*qvec[0] - pvec[0]*qvec[2],\n pvec[0]*qvec[1] - pvec[1]*qvec[0])\n return normalize(norm)\n\nclass Surface():\n \"\"\" object for each surface \"\"\"\n def __init__(self, v0, v1, v2, v3):\n self.vert = (v0, v1, v2, v3)\n self.norm = (0, 0, 0)\n self.zpos = 0\n\n def update(self):\n \"\"\" update the normal vector of the surface \"\"\"\n self.norm = get_norm_vec(self.vert[0],\n self.vert[1], self.vert[2])\n self.zpos = (self.vert[0][2] + self.vert[1][2] \\\n + self.vert[2][2] + self.vert[3][2]) / 4\n\nclass Cube():\n \"\"\" 3D Cube model \"\"\"\n polygons = (\n (2, 1, 5, 6), (0, 1, 2, 3), (4, 5, 1, 0),\n (2, 6, 7, 3), (7, 6, 5, 4), (0, 3, 7, 4)\n )\n\n def __init__(self, x, y, z, w, h, d, tag):\n self.xpos = x\n self.zpos = z\n self.pos = []\n self.tag = tag\n self.surfaces = []\n self.vertices = (\n (x - w, y - h, z + d),\n (x - w, y + h, z + d),\n (x + w, y + h, z + d),\n (x + w, y - h, z + d),\n (x - w, y - h, z - d),\n (x - w, y + h, z - d),\n (x + w, y + h, z - d),\n (x + w, y - h, z - d),\n )\n\n for vert in self.vertices:\n self.pos.append([vert[0], vert[1], vert[2]])\n\n for i in range(6):\n indices = self.polygons[i]\n pos0 = self.pos[indices[0]]\n pos1 = self.pos[indices[1]]\n pos2 = self.pos[indices[2]]\n pos3 = self.pos[indices[3]]\n self.surfaces.append(Surface(pos0, pos1, pos2, pos3))\n\n def set_camera(self, camera_x, camera_y, camera_z,\n mrot_x, mrot_y):\n \"\"\" set camera location and update vertices positions \"\"\"\n for i in range(len(self.vertices)):\n vert = self.vertices[i]\n xpos = vert[0] - camera_x\n ypos = vert[1] - camera_y\n zpos = vert[2]\n\n # rotate around Y axis\n ppos = mrot_y[0] * xpos + mrot_y[1] * ypos \\\n + mrot_y[2] * zpos\n qpos = mrot_y[3] * xpos + mrot_y[4] * ypos \\\n + mrot_y[5] * zpos\n rpos = mrot_y[6] * xpos + mrot_y[7] * ypos \\\n + mrot_y[8] * zpos\n\n # rotate around X axis\n self.pos[i][0] = mrot_x[0] * ppos + mrot_x[1] * qpos\\\n + mrot_x[2] * rpos\n self.pos[i][1] = mrot_x[3] * ppos + mrot_x[4] * qpos\\\n + mrot_x[5] * rpos\n self.pos[i][2] = mrot_x[6] * ppos + mrot_x[7] * qpos\\\n + mrot_x[8] * rpos - camera_z\n\n for surface in self.surfaces:\n surface.update()\n\ndef eventloop():\n \"\"\" handle events in eventloop \"\"\"\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n elif event.type == KEYDOWN:\n if event.key == K_LEFT:\n CAMERA_THETA[1] -= 0.01\n elif event.key == K_RIGHT:\n CAMERA_THETA[1] += 0.01\n elif event.key == K_UP:\n CAMERA_THETA[0] += 0.01\n elif event.key == K_DOWN:\n CAMERA_THETA[0] -= 0.01\n CAMERA_THETA[0] = max(1.0, min(1.3, CAMERA_THETA[0]))\n CAMERA_THETA[1] = max(-0.5, min(0.5, CAMERA_THETA[1]))\n\ndef tick():\n \"\"\" called periodically from the main loop \"\"\"\n eventloop()\n\n cval, sval = cos(CAMERA_THETA[1]), sin(CAMERA_THETA[1])\n mrot_y = [cval, 0, sval, 0, 1, 0, -sval, 0, cval]\n cval, sval = cos(CAMERA_THETA[0]), sin(CAMERA_THETA[0])\n mrot_x = [1, 0, 0, 0, cval, -sval, 0, sval, cval]\n\n ENGINE.set_gravity(-CAMERA_THETA[1] * 20, -CAMERA_THETA[0] * 5)\n ENGINE.step(0.01)\n\n if BALL.ypos < 0 or BALL.ypos > 1200:\n BALL.xpos = randint(0, 300) + 100\n BALL.ypos = 1000\n\n IMAGES[0] = Cube(BALL.xpos, BALL.ypos, 0, 10, 10, 10, \"ball\")\n for cube in CUBES:\n cube.set_camera(300, 300, -1500, mrot_x, mrot_y)\n for pin in IMAGES:\n pin.set_camera(300, 300, -1500, mrot_x, mrot_y)\n\ndef paint():\n \"\"\" update the surface \"\"\"\n SURFACE.fill((0, 0, 0))\n\n # draw bars on both sides\n surfaces = []\n for cube in CUBES:\n surfaces.extend(cube.surfaces)\n surfaces = sorted(surfaces, key=lambda x: x.zpos, reverse=True)\n\n for surf in surfaces:\n dot = surf.norm[0]*LIGHT[0] + surf.norm[1]*LIGHT[1] \\\n + surf.norm[2]*LIGHT[2]\n ratio = (dot + 1) / 2\n (rval, gval, bval) = (floor(255*ratio),\n floor(255*ratio), floor(255*ratio))\n\n pts = []\n for i in range(4):\n (xpos, ypos, zpos) = (surf.vert[i][0],\n surf.vert[i][1], surf.vert[i][2])\n if zpos <= 10:\n continue\n xpos = int(xpos * 1200 / zpos + 300)\n ypos = int(-ypos * 1200 / zpos + 300)\n pts.append((xpos, ypos))\n\n if len(pts) > 3:\n pygame.draw.polygon(SURFACE, (rval, gval, bval), pts)\n\n # draw pins\n surfaces = []\n for pin in IMAGES:\n surf = pin.surfaces[1]\n surf.tag = pin.tag\n surfaces.append(surf)\n surfaces = sorted(surfaces, key=lambda x: x.zpos, reverse=True)\n\n for surf in surfaces:\n (xpos, ypos, zpos) = (surf.vert[0][0],\n surf.vert[0][1], surf.vert[0][2])\n if zpos < 10:\n continue\n xpos = int(xpos * 1200 / zpos + 300)\n ypos = int(-ypos * 1200 / zpos + 300)\n scale = (4000-zpos)/20000\n if surf.tag == \"ball\":\n draw_rotate_center(PNGS[2], xpos, ypos, 0, scale)\n elif surf.tag == \"pin0\":\n draw_rotate_center(PNGS[0], xpos, ypos,\n degrees(CAMERA_THETA[1]), scale)\n elif surf.tag == \"pin1\":\n draw_rotate_center(PNGS[1], xpos, ypos,\n degrees(CAMERA_THETA[1]), scale)\n\n pygame.display.update()\n\ndef draw_rotate_center(image, xpos, ypos, theta, zoom):\n \"\"\" rotate image \"\"\"\n rotate_sprite = pygame.transform.rotozoom(image, theta, zoom)\n rect = rotate_sprite.get_rect()\n SURFACE.blit(rotate_sprite, (xpos-(rect.width/2),\n ypos-(rect.height/2)))\n\ndef onhit(self, peer):\n \"\"\" callback function when a pin is hit by the ball \"\"\"\n self.pin.tag = \"pin1\"\n\ndef main():\n \"\"\" main routine \"\"\"\n cubedata = [\n {\"xpos\": 25, \"ypos\": 600, \"width\": 25, \"height\": 600},\n {\"xpos\": 575, \"ypos\": 600, \"width\": 25, \"height\": 600},\n ]\n\n for cube in cubedata:\n xpos, ypos, width, height = cube[\"xpos\"], cube[\"ypos\"],\\\n cube[\"width\"], cube[\"height\"]\n CUBES.append(Cube(xpos, ypos, 0, width, height, 25, \"cube\"))\n cube_obj = RectangleEntity(xpos - width, ypos - height,\n width * 2, height * 2)\n ENGINE.entities.append(cube_obj)\n\n ENGINE.entities.append(BALL)\n IMAGES.append(Cube(0, 0, 0, 15, 15, 15, \"ball\"))\n\n for yindex in range(5):\n for xindex in range(7 + yindex%2):\n xpos = xindex * 60 + (95 if yindex % 2 == 1 else 120)\n ypos = yindex * 150 + 100\n pin = Cube(xpos, ypos, 0, 10, 10, 10, \"pin0\")\n IMAGES.append(pin)\n pin_obj = CircleEntity(xpos, ypos, 10, True, 0.8)\n pin_obj.pin = pin\n pin_obj.onhit = types.MethodType(onhit, pin_obj)\n ENGINE.entities.append(pin_obj)\n\n while True:\n tick()\n paint()\n FPSCLOCK.tick(30)\n\npygame.init()\npygame.key.set_repeat(5, 5)\nSURFACE = pygame.display.set_mode([600, 600])\nFPSCLOCK = pygame.time.Clock()\nENGINE = Engine(-100, -100, 800, 1400, 0, 0)\nBALL = CircleEntity(randint(0, 300) + 100, 1000, 15, False, 0.9)\nCUBES = []\nIMAGES = []\nCAMERA_THETA = [1.2, 0]\nLIGHT = normalize([0.5, -0.8, -0.2])\nPNGS = (pygame.image.load(\"pin0.png\"),\n pygame.image.load(\"pin1.png\"),\n pygame.image.load(\"ball.png\"))\n\nif __name__ == '__main__':\n main()\n","sub_path":"PythonMathSamples/3d_peg.py","file_name":"3d_peg.py","file_ext":"py","file_size_in_byte":8800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"297300776","text":"from rest_framework import serializers\nfrom cebolla.models import *\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\nimport pytz\nfrom django.conf import settings\n\nclass PriceSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = Price\n\t\tfields = ('name','price')\n\nclass IngredientSerializer(serializers.ModelSerializer):\n\t\tid = serializers.IntegerField(required = True)\n\t\tclass Meta:\n\t\t\tmodel = Ingredient\n\t\t\tfields = ('id', 'name','price','scale','label')\n\t\t\t\n\t\tdef validate_scale(self, scale):\n\t\t\tif scale > 0:\n\t\t\t\tif Ingredient.objects.filter(scale = scale).exists():\n\t\t\t\t\tquery = Ingredient.objects.filter(scale = scale)\n\t\t\t\t\tprint(self)\n\t\t\t\t\tif len(query) > 1:\n\t\t\t\t\t\traise serializers.ValidationError('Dos ingredientes asignados a la misma pesa.')\n\t\t\t\t\telif query[0].id != self.initial_data['id']:\n\t\t\t\t\t\traise serializers.ValidationError('Dos ingredientes asignados a la misma pesa.')\n\t\t\treturn scale\n\nclass ItemSerializer(serializers.ModelSerializer):\n\t# gets object based on its primary key\n\tid = serializers.IntegerField(required = False)\n\tingredient = serializers.SlugRelatedField(slug_field = 'name',queryset=Ingredient.objects.all())\n\torder = serializers.SlugRelatedField(slug_field = 'name',read_only=True)\n\t#itemPrice = serializers.IntegerField(read_only=True)\n\tclass Meta:\n\t\tmodel = Item\n\t\tfields = ('id','ingredient','amount','itemPrice','order')\n\t\t\n\t# def create(self,validated_data):\n\t\t# ingredientLocalId = validated_data.pop('ingredientLocal')\n\t\t# itemPrice = IngredientLocal.objects.get(pk=ingredientLocalId).price\n\t\t# item = Item.objects.create(**validated_data, itemPrice=itemPrice)\n\t\t# return item\n\n\nclass OrderSerializer(serializers.ModelSerializer):\n#\talgo = serializers.IntegerField()\n\titems = ItemSerializer(many=True, required=True)\n\torderPrice = serializers.IntegerField()\n\tname = serializers.CharField(required=False)\n\tclass Meta:\n\t\tmodel = Order\n\t\tfields = ('id','orderPrice','rfID','items','ongoing','receiving','name')\n\t\t\n\tdef validate_items(self, items):\n\t\tif len(items) == 0:\n\t\t\traise serializers.ValidationError('se requiere al menos un item')\n\t\treturn items\n\t\t\n\tdef update(self,instance,validated_data):\n\t\t\n\t\tprint(\"Hola\")\n\t\titems = validated_data.pop('items')\n\t\tinstance.name = validated_data.pop('name')\n\t\tinstance.orderPrice = validated_data.pop('orderPrice')\n\t\tprevious_items = list(Item.objects.filter(order = instance))\n\t\t#print(previous_items)\n\t\tkitchen_labels = ['bases']\n\t\tfor item in items:\n\t\t\tif not item.get('id'):\n\t\t\t\tamount = item.get('amount')\n\t\t\t\tingredient = item.get('ingredient')\n\t\t\t\titemPrice = item.get('itemPrice')\n\t\t\t\titem = Item.objects.create(amount=amount,itemPrice=itemPrice,ingredient=ingredient,order=instance)\n\t\t\t\tif item.ingredient.label in kitchen_labels:\n\t\t\t\t\tKitchenItem.objects.create(item = item, status = 'pedido', amount = amount)\n\t\t\telse:\n\t\t\t\toldItem = Item.objects.get(id = item.get('id'))\n\t\t\t\tprevious_items.remove(oldItem)\n\t\t\t\toldItem = Item.objects.get(id = item.get('id'))\n\t\t\t\tamount = item.get('amount')\n\t\t\t\tincrease = amount - oldItem.amount\n\t\t\t\tif oldItem.ingredient.label in kitchen_labels and increase > 0:\n\t\t\t\t\tif KitchenItem.objects.filter(item = oldItem).exclude(status = 'terminado').exists():\n\t\t\t\t\t\tkitchenItem = KitchenItem.objects.filter(item = oldItem).exclude(status = 'terminado')[0]\n\t\t\t\t\t\t#print(kitchenItem)\n\t\t\t\t\t\t#if kitchenItem.status != 'terminado':\n\t\t\t\t\t\tkitchenItem.status = 'actualizado'\n\t\t\t\t\t\tkitchenItem.amount += increase\n\t\t\t\t\t\t#else:\n\t\t\t\t\t\t#\tkitchenItem = KitchenItem.objects.create(item = oldItem, status = 'pedido')\n\t\t\t\t\t\t#\tkitchenItem.amount = increase\n\t\t\t\t\telse:\n\t\t\t\t\t\tkitchenItem = KitchenItem.objects.create(item = oldItem, status = 'pedido')\n\t\t\t\t\t\tkitchenItem.amount = increase\n\t\t\t\t\tkitchenItem.save()\n\t\t\t\toldItem.amount = item.get('amount')\n\t\t\t\toldItem.save()\t\n\t\tfor item in previous_items:\n\t\t\titem.delete()\n\t\tinstance.save()\n\t\treturn instance\n\t\t\nclass KitchenItemSerializer(serializers.ModelSerializer):\n\t# gets object based on its primary key\n\titem = ItemSerializer(required=True)\n\n\t#itemPrice = serializers.IntegerField(read_only=True)\n\tclass Meta:\n\t\tmodel = KitchenItem\n\t\tfields = ('id','item','status','amount')\n\t\t\n\tdef update(self,instance,validated_data):\n\t\t#item = validated_data.pop('item')\n\t\tinstance.status = validated_data.pop('status')\n\t\tinstance.save()\n\t\treturn instance\t\n\t\t\n\t# def create(self,validated_data):\n\t\t# ingredientLocalId = validated_data.pop('ingredientLocal')\n\t\t# itemPrice = IngredientLocal.objects.get(pk=ingredientLocalId).price\n\t\t# item = Item.objects.create(**validated_data, itemPrice=itemPrice)\n\t\t# return item\n\nclass DateTimeFieldWihTZ(serializers.DateTimeField):\n\t'''Class to make output of a DateTime Field timezone aware'''\n\tdef to_representation(self, instance):\n\t\tformat = \"%Y-%m-%d %H:%M:%S\"\n\t\tlocal_timezone = pytz.timezone(getattr(settings, 'America/New_York', None))\n\t\trepresentation = instance.astimezone(local_timezone).strftime(format)\n\t\treturn representation\n\t\t\nclass MessagesSerializer(serializers.ModelSerializer):\n\tdate = serializers.DateTimeField(format=\"%Y-%m-%d %H:%M:%S\",default_timezone=pytz.timezone(\"Chile/Continental\"),read_only=True)\n\t#date = DateTimeFieldWihTZ(read_only=True)\n\tclass Meta:\n\t\tmodel = Messages\n\t\tfields = ('id','name','message','date')\n\n\n\n\n","sub_path":"Karu/cebolla/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":5270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"194402868","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"robm_move/move.py - Navigation vers un point\n\nCe noeud permet de faire naviguer le robot jusqu'à un but spécifié dans\nRViz.\n\nS'abonne à :\n\t- move_base_simple/goal (geometry_msgs/PoseStamped): but\n\t- odometry (nav_msgs/Odometry): pose du robot calculée par odométrie\nPublie :\n\t- cmd_vel (geometry_msgs/Twist): commande en vitesse\n\"\"\"\n\nimport rospy\nfrom math import pi, cos, sin, atan2, sqrt\n\nfrom geometry_msgs.msg import Twist, PoseStamped, Quaternion\nfrom nav_msgs.msg import Odometry\nfrom tf.transformations import euler_from_quaternion\n\n# Extract yaw from a Quaternion message\ndef yaw_from_quaternion_msg( q ):\n\tquat_array = [q.x, q.y, q.z, q.w]\n\tyaw = euler_from_quaternion(quat_array)[2]\n\treturn yaw\n\n\n\nclass Move:\n\tdef __init__(self):\n\t\t# Position désirée\n\t\tself.x_d = None\n\t\tself.y_d = None\n\t\t# Cap désiré\n\t\tself.theta_d = None\n\t\t# Publishers et subscribers\n\t\tself._sub_goal = rospy.Subscriber(\"move_base_simple/goal\", PoseStamped, self.goal_callback)\n\t\tself._sub_odom = rospy.Subscriber(\"odometry\", Odometry, self.odom_callback)\n\t\tself._cmd_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1)\n\t\t# compteur pour arrêter l'envoi de commandes après arrêt du robot\n\t\tself._nb_successive_zeros = 0\n\n\n\tdef publish_speed_cmd(self, v, w):\n\t\t\"\"\"Publie la commande de vitesse lineaire v et angulaire w\n\n\t\tArrête de publier des commandes d'arrêt si le robot est déjà à\n\t\tl'arrêt depuis un certain temps, pour éviter de fatiguer les\n\t\tmoteurs. Les vitesses sont en unités arbitraires, entre -1 et 1\n\n\t\t:param v: commande de vitesse linéaire (entre -1 et 1)\n\t\t:param w: commande de vitesse angulaire (entre -1 et 1)\n\t\t\"\"\"\n\t\t# Mise à jour du compteur de commandes d'arrêt\n\t\tif v == 0 and w == 0:\n\t\t\tself._nb_successive_zeros += 1\n\t\telse:\n\t\t\tself._nb_successive_zeros = 0\n\n\t\t# Si nécessaire, on publie la commande\n\t\tif self._nb_successive_zeros < 5:\n\t\t\tvel_msg = Twist()\n\t\t\tvel_msg.linear.x = v\n\t\t\tvel_msg.angular.z = w\n\t\t\tself._cmd_pub.publish(vel_msg)\n\n\n\tdef goal_callback(self, goal):\n\t\t\"\"\"Callback du mise à jour du but\"\"\"\n\t\trospy.loginfo(\"Goal set\")\n\t\t# Extract goal position and orientation from msg\n\t\tself.x_d = goal.pose.position.x\n\t\tself.y_d = goal.pose.position.y\n\t\tself.theta_d = yaw_from_quaternion_msg(goal.pose.orientation)\n\n\n\tdef odom_callback(self, odom):\n\t\t\"\"\"Callback de reception de message d'odometrie.\n\t\tLe calcul de la commande est effectué dans cette fonction.\n\t\t\"\"\"\n\t\t# Ne rien faire si le but n'est pas connu\n\t\tif self.x_d == None or self.y_d == None or self.theta_d == None:\n\t\t\treturn\n\n\t\t# Extract current position and orientation from msg\n\t\tx = odom.pose.pose.position.x\n\t\ty = odom.pose.pose.position.y\n\t\ttheta = yaw_from_quaternion_msg(odom.pose.pose.orientation)\n\n\t\t# Calculer la distance au but entre la position actuelle et désirée\n\t\td = sqrt(pow((self.x_d - x), 2) + pow((self.y_d - y), 2))\n\n\t\t# Calculer le cap à suivre entre la position actelle te désirée\n\t\tgoalAngle = atan2(self.y_d - y, self.x_d - x)\n\n\t\t# L'erreur est la différence entre l'angle pour atteindre le but et l'angle actuel\n\t\terror = goalAngle - theta\n\n\t\t# On calcule le sinus et le cosinus de l'angle\n\t\tsinError = sin(error)\n\t\tcosError = cos(error)\n\n\t\t# Le cosinus de l'angle détermine la grandeur de l'erreur\n\t\tif cosError < 0:\n\t\t\t# Dans ce cas, le robot doit faire une rotation de plus de 90°\n\t\t\t# Le sinus de l'angle détermine de quel côté doit tourner le robot\n\t\t\tif sinError >= 0:\n\t\t\t\t# Dans ce cas, le robot doit tourner vers la droite, suivant le cercle trigonométrique\n\t\t\t\t# TODO: vérifier que error = 1 correspond à tourner en vitesse maximale vers la droite\n\t\t\t\terror = 1\n\t\t\telse:\n\t\t\t\t# Dans ce cas, le robot doit tourner vers la gauche\n\t\t\t\terror = -1\n\t\telse:\n\t\t\t# Dans ce cas, l'angle est inférieur à 90°, le robot doit donc tourner en fonction du sinus\n\t\t\t# Qui déterminera à la fois le sens et la vitesse optimale de rotation\n\t\t\terror = sinError\n\n\t\t# Calculer la vitesse linéaire du robot\n\t\tw = 0.0\n\t\tv = 0.0\n\t\tv_max = 0.7\n\n\t\t# Vitesse proportionnelle\n\t\tif d > 0.15:\n\t\t\t# Si la distance est supérieure à 15cm, on multiplie la distance par 2\n\t\t\tv = d * 2\n\t\telse :\n\t\t\t# Dans le cas contraire la vitesse est égale à la distance (>0.15)\n\t\t\t# A laquelle on soustrait 0.05 afin que la vitesse atteigne 0 à 5cm.\n\t\t\tv = d - 0.05\n\n\t\t# Plafond\n\t\tif v > 0.7:\n\t\t\tv = v_max\n\n\t\tif d < 0.05:\n\t\t\terror = 0\n\n\t\t# Si la vitesse linéaire n'est pas nulle, on est pas arrivé à destination \n\t\tif v > 0.01 :\n\t\t\t# Si l'erreur n'est pas trop basse, on annule le déplacement linéaire pour effectuer la rotation\n\t\t\tif error > 0.1 :\n\t\t\t\tw = error * 0.4\n\t\t\t\tv = 0.0\n\t\t\t# Sinon on considère qu'il n'y a pas besoin de tourner\n\t\t\telse :\n\t\t\t\tw = 0.0\n\t\t# Si la vitesse linéaire est nulle, on est arrivé à destination\n\t\telse :\n\t\t\tv = 0.0\n\t\t\t# Il ne reste plus qu'a s'orienter dans l'orientation finale désirée.\n\t\t\terror = theta_d - theta\n\t\t\t# On réutilise le même calcul que précedement\n\t\t\tsinError = sin(error)\n\t\t\tcosError = cos(error)\n\t\t\tif cosError < 0:\n\t\t\t\tif sinError >= 0:\n\t\t\t\t\terror = 1\n\t\t\t\telse:\n\t\t\t\t\terror = -1\n\t\t\telse:\n\t\t\t\terror = sinError\n\t\t\tif error > 0.1 :\n\t\t\t\tw = error * 0.4\n\t\t\telse :\n\t\t\t\tw = 0.0\n\n\t\t# Publish speed command (in not zero for too long)\n\t\tself.publish_speed_cmd(v, w)\n\n\ndef move_node():\n\t# Initialize ROS node\n\trospy.init_node('move')\n\t# Create move object\n\tmove = Move()\n\t# Process incoming ROS messages until termination\n\trospy.spin()\n\n\nif __name__ == '__main__':\n\ttry:\n\t\tmove_node()\n\texcept rospy.ROSInterruptException:\n\t\tpass\n","sub_path":"src/robm_move/scripts/move.py","file_name":"move.py","file_ext":"py","file_size_in_byte":5574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"483785411","text":"from django.shortcuts import render, redirect\nfrom .form import UserRegistration\nfrom django.contrib import messages\nfrom ads.models import Post\n\ndef register(request):\n if request.method == \"POST\":\n form = UserRegistration(request.POST)\n if form.is_valid():\n form.save()\n username=form.cleaned_data.get('username')\n messages.success(request, f'Пользователь {username}, успешно зарегестрирован. Для продолжения работы авторизуйтесь.')\n return redirect('login')\n else:\n form = UserRegistration()\n return render(request,'user/registration.html',{'form':form,'title':'Регистрация'})\n\ndef profile(request):\n post = Post.objects.all()\n return render(request,'user/profile.html',{'all_post':post,'title':'Ваш профиль'})\n","sub_path":"user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"213325895","text":"import os\nimport codecs\nimport json\nimport yaml\n\nfrom utils.i18n import gettext\n\n\ndef load_config(config_path, loader=yaml.Loader):\n \"\"\"\n 在项目启动时去加载配置\n :param config_path: 配置路径\n :param loader: 配置加载器\n :return:\n \"\"\"\n if config_path is None:\n return dict()\n if not os.path.exists(config_path): # 判断路径是否真实存在\n raise RuntimeError(gettext(u\"config.yml not found in {config_path}\").format(config_path))\n if \".json\" in config_path: # 如果是 .json 格式的配置\n # codecs 模块是专门用来做编码转换的\n with codecs.open(config_path, encoding=\"utf-8\") as f:\n json_config = f.read()\n config = json.loads(json_config)\n else:\n with codecs.open(config_path, encoding=\"utf-8\") as stream:\n config = yaml.load(stream, loader)\n return config\n\n\nif __name__ == '__main__':\n config = load_config(config_path='config.yml')\n print(config)\n\n\n# 使用 codecs 的原因:\n# 由于python中默认的编码是ascii,如果直接使用open方法得到文件对象然后进行文件的读写,都将无法使用包含中文字符\n# (以及其他���ascii码字符),因此建议使用utf-8编码。\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"318350593","text":"# -*- coding: utf-8 -*-\n\nimport torch\nimport time\nfrom torch.autograd import Variable\nimport numpy as np\nimport torch.nn as nn\n\n\nclass BasicModule(torch.nn.Module):\n def __init__(self):\n super(BasicModule, self).__init__()\n self.model_name=str(type(self)) # model name\n self.cost = nn.CrossEntropyLoss()\n\n def weights_init(self, m):\n classname = m.__class__.__name__\n if classname.find('Linear') != -1:\n self.init_linear(m)\n elif classname.find('LSTM') != -1:\n self.init_lstm(m)\n\n def init_linear(self, input_linear):\n \"\"\"\n Initialize linear transformation\n \"\"\"\n bias = np.sqrt(6.0 / (input_linear.weight.size(0) + input_linear.weight.size(1)))\n nn.init.uniform_(input_linear.weight, -bias, bias)\n if input_linear.bias is not None:\n input_linear.bias.data.zero_()\n\n def init_lstm(self, input_lstm):\n \"\"\"\n Initialize lstm\n \"\"\"\n for ind in range(0, input_lstm.num_layers):\n weight = eval('input_lstm.weight_ih_l' + str(ind))\n bias = np.sqrt(6.0 / (weight.size(0) / 4 + weight.size(1)))\n nn.init.uniform_(weight, -bias, bias)\n weight = eval('input_lstm.weight_hh_l' + str(ind))\n bias = np.sqrt(6.0 / (weight.size(0) / 4 + weight.size(1)))\n nn.init.uniform_(weight, -bias, bias)\n if input_lstm.bias:\n for ind in range(0, input_lstm.num_layers):\n weight = eval('input_lstm.bias_ih_l' + str(ind))\n weight.data.zero_()\n weight.data[input_lstm.hidden_size: 2 * input_lstm.hidden_size] = 1\n weight = eval('input_lstm.bias_hh_l' + str(ind))\n weight.data.zero_()\n weight.data[input_lstm.hidden_size: 2 * input_lstm.hidden_size] = 1\n\n def init_cnn(self, input_cnn):\n n = input_cnn.in_channels\n for k in input_cnn.kernel_size:\n n *= k\n stdv = np.sqrt(6. / n)\n input_cnn.weight.data.uniform_(-stdv, stdv)\n if input_cnn.bias is not None:\n input_cnn.bias.data.uniform_(-stdv, stdv)\n\n def cross_entopy_loss(self, logits, label):\n '''\n logits: Logits with the size (..., class_num)\n label: Label with whatever size.\n return: [Loss] (A single value)\n '''\n N = logits.size(-1)\n return self.cost(logits.view(-1, N), label.view(-1))\n\n def accuracy(self, pred, label):\n '''\n pred: Prediction results with whatever size\n label: Label with whatever size\n return: [Accuracy] (A single value)\n '''\n return torch.mean((pred.view(-1) == label.view(-1)).float()) * 100","sub_path":"models/BasicModule.py","file_name":"BasicModule.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"415363853","text":"# Trung-Hieu Tran @ IPVS\n# 180921\n\n# from utils.epinet_dataset import EPI_Dataset\nfrom __future__ import print_function\nfrom chainmap import ChainMap\nimport argparse\nimport os\nimport random\nimport sys\n\nimport numpy as np\nfrom keras import optimizers\n\n# reproduceable with random\nfrom numpy.random import seed\nfrom tensorflow import set_random_seed\nimport tensorflow as tf\nfrom keras.callbacks import TensorBoard\nfrom keras.callbacks import ModelCheckpoint\nimport keras\nfrom utils.epinet_dataset import Dataset_Generator\nfrom time import strftime, gmtime\nfrom utils.keras_epinet import define_epinet_v1\n\n\ndef set_seed(config):\n seed = config[\"seed\"]\n set_random_seed(seed)\n np.random.seed(seed)\n # if not config[\"no_cuda\"]:\n # torch.cuda.manual_seed(seed)\n random.seed(seed)\n\ndef train(config):\n train_set, dev_set, test_set = Dataset_Generator.splits(config)\n print(\" Summary: Train set %d , Dev set %d, Test set %d\"%(len(train_set),\n len(dev_set),\n len(test_set)))\n image_h = config['patch_size']\n image_w = config['patch_size']\n view_size = config['view_size']\n model_conv_depth=7\n model_filt_num=70\n model_learning_rate=0.1**5\n model_512=define_epinet_v1((image_h, image_w),\n view_size,\n model_conv_depth,\n model_filt_num,\n model_learning_rate)\n\n model_512.summary()\n # sgd = optimizers.SGD(lr=config['lr'][0],decay=config['weight_decay'],\n # nesterov=config['use_nesterov'], momentum=config['momentum'])\n optimizer = optimizers.RMSprop(lr=model_learning_rate)\n model_512.compile(optimizer=optimizer,\n loss='mean_absolute_error',\n metrics=['mae'])\n\n configPro = tf.ConfigProto(device_count={'GPU':2,'CPU':2})\n sess = tf.Session(config=configPro)\n keras.backend.set_session(sess)\n # tensorboard logs\n str_time = strftime(\"%y%m%d_%H%M%S\",gmtime())\n tensorboard = TensorBoard(log_dir=\"logs/view_5/v5_{}\".format(str_time))\n # checkpoint\n filepath=\"logs/view_5/v5_%s_improvement-{epoch:02d}-{val_loss:.2f}.hdf5\"%(str_time)\n checkpoint = ModelCheckpoint(filepath, monitor='val_loss',\n verbose=1, save_best_only=True,\n mode='auto')\n\n callbacks_list = [tensorboard,checkpoint]\n\n # keras.backend.get_session().run(tf.initialize_all_variables())\n keras.backend.get_session().run(tf.global_variables_initializer())\n if 'weight_file' in config:\n model_512.load_weights(config['weight_file'])\n\n model_512.fit_generator(generator=train_set,\n steps_per_epoch=(len(train_set)),\n epochs = config['n_epochs'],\n verbose=1,\n validation_data = dev_set,\n validation_steps= (len(dev_set)),\n use_multiprocessing=False,\n workers=1,\n max_queue_size=10,\n callbacks=callbacks_list)\n model_512.save(config['output_file'])\n\n\n\ndef main():\n config = {}\n # config['data_dir'] ='/home/trantu/lightfield/datasets/hci/full/additional'\n # config['disparity_dir'] = '/home/trantu/lightfield/datasets/hci/full/depths/additional'\n\n # config['data_dir'] ='/home/trantu/lightfield/local/hci/full/additional'\n # config['disparity_dir'] = '/home/trantu/lightfield/local/hci/full/depths/additional'\n config['patch_size'] = 61\n # config['stride'] = 6\n config['input_file'] = '/home/trantu/maps/pool1/data/epinet/train_5v_61p_10s.h5'\n # config['input_file'] = '/home/trantu/tmp/train_9v_23p_6s.h5'\n config['output_file'] = './weights.h5'\n # config['output_file'] = '/home/trantu/tmp/t9.h5'\n config['view_size'] = 5\n\n # config['aug_shift'] = True\n # config['thres_patch'] = 0.03*255 # threshold to select good patch\n config['batch_size'] = 16\n config['dset_input'] = 'inputs'\n config['dset_label'] = 'labels'\n config['seed'] = 1234\n config['mode'] = 'train'\n config['n_epochs'] = 100\n\n # GPU setting ( gtx 1080ti - gpu0 ) \n os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"5,6\"\n set_seed(config)\n if config[\"mode\"] == \"train\":\n train(config)\n elif config[\"mode\"] == \"eval\":\n print(\"TODO\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"train_keras.py","file_name":"train_keras.py","file_ext":"py","file_size_in_byte":4624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"63739316","text":"#!/usr/bin/env python3\n\"\"\" Setup.py file \"\"\"\nimport os\nimport subprocess\nimport setuptools.command.install\n\n\n# create and install translation files\nclass InstallWithLocale(setuptools.command.install.install):\n def create_mo_files(self):\n data_files = []\n localedir = 'locale'\n po_dirs = [localedir + '/' + l + '/LC_MESSAGES/'\n for l in next(os.walk(localedir))[1]]\n for d in po_dirs:\n mo_dir = os.path.join(self.root, 'usr/share', d)\n os.makedirs(mo_dir, exist_ok=True)\n mo_files = []\n po_files = [f\n for f in next(os.walk(d))[2]\n if os.path.splitext(f)[1] == '.po']\n for po_file in po_files:\n filename, extension = os.path.splitext(po_file)\n mo_file = filename + '.mo'\n msgfmt_cmd = 'msgfmt {} -o {}'.format(\n d + po_file,\n os.path.join(mo_dir, mo_file))\n subprocess.check_call(msgfmt_cmd, shell=True)\n mo_files.append(d + mo_file)\n data_files.append((d, mo_files))\n return data_files\n\n def run(self):\n self.create_mo_files()\n super().run()\n\n\nsetuptools.setup(\n name='qui',\n version='0.1',\n author='Invisible Things Lab',\n author_email='marmarta@invisiblethingslab.com',\n description='Qubes User Interface And Configuration Package',\n license='GPL2+',\n url='https://www.qubes-os.org/',\n packages=[\"qui\", \"qui.updater\", \"qui.tray\", \"qubes_config\",\n \"qubes_config.global_config\", \"qubes_config.widgets\",\n \"qubes_config.new_qube\", 'qubes_config.policy_editor'],\n entry_points={\n 'gui_scripts': [\n 'qui-domains = qui.tray.domains:main',\n 'qui-devices = qui.tray.devices:main',\n 'qui-disk-space = qui.tray.disk_space:main',\n 'qui-updates = qui.tray.updates:main',\n 'qubes-update-gui = qui.updater.updater:main',\n 'qui-clipboard = qui.clipboard:main',\n 'qubes-new-qube = qubes_config.new_qube.new_qube_app:main',\n 'qubes-global-config = qubes_config.global_config.global_config:main',\n 'qubes-policy-editor = qubes_config.policy_editor.policy_editor:main'\n ]\n },\n package_data={'qui': [\"updater.glade\",\n \"updater_settings.glade\",\n \"qubes-updater-base.css\",\n \"qubes-updater-light.css\",\n \"qubes-updater-dark.css\",\n \"styles/qubes-colors-light.css\",\n \"styles/qubes-colors-dark.css\",\n \"styles/qubes-widgets-base.css\",\n ],\n 'qubes_config': [\"new_qube.glade\",\n \"global_config.glade\",\n \"qubes-new-qube-base.css\",\n \"qubes-new-qube-light.css\",\n \"qubes-new-qube-dark.css\",\n \"qubes-global-config-base.css\",\n \"qubes-global-config-light.css\",\n \"qubes-global-config-dark.css\",\n \"qubes-policy-editor-base.css\",\n \"qubes-policy-editor-light.css\",\n \"qubes-policy-editor-dark.css\",\n \"policy_editor.glade\",\n \"policy_editor/policy_help.txt\"]},\n cmdclass={\n 'install': InstallWithLocale\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"563975429","text":"\"\"\"\nA :class:`Group` can contain sub-:class:`Group`\\\\s and/or :class:`~msl.io.dataset.Dataset`\\\\s.\n\"\"\"\nimport re\n\nfrom .dataset import Dataset\nfrom .dataset_logging import DatasetLogging\nfrom .vertex import Vertex\n\n\nclass Group(Vertex):\n\n def __init__(self, name, parent, read_only, **metadata):\n \"\"\"A :class:`Group` can contain sub-:class:`Group`\\\\s and/or :class:`~msl.io.dataset.Dataset`\\\\s.\n\n Do not instantiate directly. Create a new :class:`Group` using\n :meth:`~msl.io.group.Group.create_group`.\n\n Parameters\n ----------\n name : :class:`str`\n The name of this :class:`Group`. Uses a naming convention analogous to UNIX\n file systems where each :class:`~msl.io.group.Group` can be thought\n of as a directory and where every subdirectory is separated from its\n parent directory by the ``'/'`` character.\n parent : :class:`Group`\n The parent :class:`Group` to this :class:`Group`.\n read_only : :class:`bool`\n Whether the :class:`Group` is to be accessed in read-only mode.\n **metadata\n Key-value pairs that are used to create the :class:`~msl.io.metadata.Metadata`\n for this :class:`Group`.\n \"\"\"\n super(Group, self).__init__(name, parent, read_only, **metadata)\n\n def __repr__(self):\n g = len(list(self.groups()))\n d = len(list(self.datasets()))\n m = len(self.metadata)\n return ''.format(self._name, g, d, m)\n\n def __getitem__(self, item):\n if item and not item[0] == '/':\n item = '/' + item\n try:\n return self._mapping[item]\n except KeyError:\n pass # raise a more detailed error message below\n self._raise_key_error(item)\n\n def __getattr__(self, item):\n try:\n return self.__getitem__('/' + item)\n except KeyError as e:\n msg = str(e)\n raise AttributeError(msg)\n\n def __delattr__(self, item):\n try:\n return self.__delitem__('/' + item)\n except KeyError as e:\n msg = str(e)\n raise AttributeError(msg)\n\n @staticmethod\n def is_dataset(obj):\n \"\"\"Test whether an object is a :class:`~msl.io.dataset.Dataset`.\n\n Parameters\n ----------\n obj : :class:`object`\n The object to test.\n\n Returns\n -------\n :class:`bool`\n Whether `obj` is an instance of :class:`~msl.io.dataset.Dataset`.\n \"\"\"\n return isinstance(obj, Dataset)\n\n @staticmethod\n def is_dataset_logging(obj):\n \"\"\"Test whether an object is a :class:`~msl.io.dataset_logging.DatasetLogging`.\n\n Parameters\n ----------\n obj : :class:`object`\n The object to test.\n\n Returns\n -------\n :class:`bool`\n Whether `obj` is an instance of :class:`~msl.io.dataset_logging.DatasetLogging`.\n \"\"\"\n return isinstance(obj, DatasetLogging)\n\n @staticmethod\n def is_group(obj):\n \"\"\"Test whether an object is a :class:`~msl.io.group.Group`.\n\n Parameters\n ----------\n obj : :class:`object`\n The object to test.\n\n Returns\n -------\n :class:`bool`\n Whether `obj` is an instance of :class:`~msl.io.group.Group`.\n \"\"\"\n return isinstance(obj, Group)\n\n def datasets(self, exclude=None, include=None, flags=0):\n \"\"\"Get the :class:`~msl.io.dataset.Dataset`\\\\s in this :class:`Group`.\n\n Parameters\n ----------\n exclude : :class:`str`, optional\n A regex pattern to use to exclude :class:`~msl.io.dataset.Dataset`\\\\s.\n The :func:`re.search` function is used to compare the `exclude` regex\n pattern with the `name` of each :class:`~msl.io.dataset.Dataset`. If\n there is a match, the :class:`~msl.io.dataset.Dataset` is not yielded.\n include : :class:`str`, optional\n A regex pattern to use to include :class:`~msl.io.dataset.Dataset`\\\\s.\n The :func:`re.search` function is used to compare the `include` regex\n pattern with the `name` of each :class:`~msl.io.dataset.Dataset`. If\n there is a match, the :class:`~msl.io.dataset.Dataset` is yielded.\n flags : :class:`int`, optional\n Regex flags that are passed to :func:`re.compile`.\n\n Yields\n ------\n :class:`~msl.io.dataset.Dataset`\n The filtered :class:`~msl.io.dataset.Dataset`\\\\s based on the\n `exclude` and `include` regex patterns. The `exclude` pattern\n has more precedence than the `include` pattern if there is a\n conflict.\n \"\"\"\n e = False if exclude is None else re.compile(exclude, flags=flags)\n i = False if include is None else re.compile(include, flags=flags)\n for obj in self._mapping.values():\n if self.is_dataset(obj):\n if e and e.search(obj.name):\n continue\n if i and not i.search(obj.name):\n continue\n yield obj\n\n def groups(self, exclude=None, include=None, flags=0):\n \"\"\"Get the sub-:class:`.Group`\\\\s of this :class:`.Group`.\n\n Parameters\n ----------\n exclude : :class:`str`, optional\n A regex pattern to use to exclude :class:`.Group`\\\\s. The\n :func:`re.search` function is used to compare the `exclude` regex\n pattern with the `name` of each :class:`.Group`. If there is a match,\n the :class:`.Group` is not yielded.\n include : :class:`str`, optional\n A regex pattern to use to include :class:`.Group`\\\\s. The\n :func:`re.search` function is used to compare the `include` regex\n pattern with the `name` of each :class:`.Group`. If there is a match,\n the :class:`.Group` is yielded.\n flags : :class:`int`, optional\n Regex flags that are passed to :func:`re.compile`.\n\n Yields\n ------\n :class:`Group`\n The filtered :class:`.Group`\\\\s based on the `exclude` and `include`\n regex patterns. The `exclude` pattern has more precedence than the\n `include` pattern if there is a conflict.\n \"\"\"\n e = False if exclude is None else re.compile(exclude, flags=flags)\n i = False if include is None else re.compile(include, flags=flags)\n for obj in self._mapping.values():\n if self.is_group(obj):\n if e and e.search(obj.name):\n continue\n if i and not i.search(obj.name):\n continue\n yield obj\n\n def descendants(self):\n \"\"\"Get all descendant (children) :class:`.Group`\\\\s of this :class:`.Group`.\n\n Yields\n ------\n :class:`.Group`\n The descendants of this :class:`.Group`.\n \"\"\"\n for obj in self._mapping.values():\n if self.is_group(obj):\n yield obj\n\n def ancestors(self):\n \"\"\"Get all ancestor (parent) :class:`.Group`\\\\s of this :class:`.Group`.\n\n Yields\n ------\n :class:`.Group`\n The ancestors of this :class:`.Group`.\n \"\"\"\n parent = self.parent\n while parent is not None:\n yield parent\n parent = parent.parent\n\n def add_group(self, name, group):\n \"\"\"Add a :class:`Group`.\n\n Automatically creates the ancestor :class:`Group`\\\\s if they do not exist.\n\n Parameters\n ----------\n name : :class:`str`\n The name of the new :class:`Group` to add.\n group : :class:`Group`\n The :class:`Group` to add. The :class:`~msl.io.dataset.Dataset`\\\\s and\n :class:`~msl.io.metadata.Metadata` that are contained within the\n `group` will be copied.\n \"\"\"\n if not isinstance(group, Group):\n raise TypeError('Must pass in a Group object, got {!r}'.format(group))\n\n name = '/' + name.strip('/')\n\n if not group: # no sub-Groups or Datasets, only add the Metadata\n self.create_group(name + group.name, **group.metadata.copy())\n return\n\n for key, vertex in group.items():\n n = name + key\n if self.is_group(vertex):\n self.create_group(n, read_only=vertex.read_only, **vertex.metadata.copy())\n else: # must be a Dataset\n self.create_dataset(\n n, read_only=vertex.read_only, data=vertex.data.copy(), **vertex.metadata.copy()\n )\n\n def create_group(self, name, read_only=None, **metadata):\n \"\"\"Create a new :class:`Group`.\n\n Automatically creates the ancestor :class:`Group`\\\\s if they do not exist.\n\n Parameters\n ----------\n name : :class:`str`\n The name of the new :class:`Group`.\n read_only : :class:`bool`, optional\n Whether to create this :class:`Group` in read-only mode.\n If :data:`None` then uses the mode for this :class:`Group`.\n **metadata\n Key-value pairs that are used to create the :class:`~msl.io.metadata.Metadata`\n for this :class:`Group`.\n\n Returns\n -------\n :class:`Group`\n The new :class:`Group` that was created.\n \"\"\"\n read_only, metadata = self._check(read_only, **metadata)\n name, parent = self._create_ancestors(name, read_only)\n return Group(name, parent, read_only, **metadata)\n\n def require_group(self, name, read_only=None, **metadata):\n \"\"\"Require that a :class:`Group` exists.\n\n If the :class:`Group` exists then it will be returned if it does not exist\n then it is created.\n\n Automatically creates the ancestor :class:`Group`\\\\s if they do not exist.\n\n Parameters\n ----------\n name : :class:`str`\n The name of the :class:`Group`.\n read_only : :class:`bool`, optional\n Whether to return the :class:`Group` in read-only mode.\n If :data:`None` then uses the mode for this :class:`Group`.\n **metadata\n Key-value pairs that are used as :class:`~msl.io.metadata.Metadata`\n for this :class:`Group`.\n\n Returns\n -------\n :class:`Group`\n The :class:`Group` that was created or that already existed.\n \"\"\"\n name = '/' + name.strip('/')\n group_name = name if self.parent is None else self.name + name\n for group in self.groups():\n if group.name == group_name:\n if read_only is not None:\n group.read_only = read_only\n group.add_metadata(**metadata)\n return group\n return self.create_group(name, read_only=read_only, **metadata)\n\n def add_dataset(self, name, dataset):\n \"\"\"Add a :class:`~msl.io.dataset.Dataset`.\n\n Automatically creates the ancestor :class:`Group`\\\\s if they do not exist.\n\n Parameters\n ----------\n name : :class:`str`\n The name of the new :class:`~msl.io.dataset.Dataset` to add.\n dataset : :class:`~msl.io.dataset.Dataset`\n The :class:`~msl.io.dataset.Dataset` to add. The :class:`~msl.io.dataset.Dataset`\n and the :class:`~msl.io.metadata.Metadata` are copied.\n \"\"\"\n if not isinstance(dataset, Dataset):\n raise TypeError('Must pass in a Dataset object, got {!r}'.format(dataset))\n\n name = '/' + name.strip('/')\n self.create_dataset(\n name, read_only=dataset.read_only, data=dataset.data.copy(), **dataset.metadata.copy()\n )\n\n def create_dataset(self, name, read_only=None, **kwargs):\n \"\"\"Create a new :class:`~msl.io.dataset.Dataset`.\n\n Automatically creates the ancestor :class:`Group`\\\\s if they do not exist.\n\n Parameters\n ----------\n name : :class:`str`\n The name of the new :class:`~msl.io.dataset.Dataset`.\n read_only : :class:`bool`, optional\n Whether to create this :class:`~msl.io.dataset.Dataset` in read-only mode.\n If :data:`None` then uses the mode for this :class:`Group`.\n **kwargs\n Key-value pairs that are passed to :class:`~msl.io.dataset.Dataset`.\n\n Returns\n -------\n :class:`~msl.io.dataset.Dataset`\n The new :class:`~msl.io.dataset.Dataset` that was created.\n \"\"\"\n read_only, kwargs = self._check(read_only, **kwargs)\n name, parent = self._create_ancestors(name, read_only)\n return Dataset(name, parent, read_only, **kwargs)\n\n def require_dataset(self, name, read_only=None, **kwargs):\n \"\"\"Require that a :class:`~msl.io.dataset.Dataset` exists.\n\n If the :class:`~msl.io.dataset.Dataset` exists then it will be returned\n if it does not exist then it is created.\n\n Automatically creates the ancestor :class:`Group`\\\\s if they do not exist.\n\n Parameters\n ----------\n name : :class:`str`\n The name of the :class:`~msl.io.dataset.Dataset`.\n read_only : :class:`bool`, optional\n Whether to create this :class:`~msl.io.dataset.Dataset` in read-only mode.\n If :data:`None` then uses the mode for this :class:`Group`.\n **kwargs\n Key-value pairs that are passed to :class:`~msl.io.dataset.Dataset`.\n\n Returns\n -------\n :class:`~msl.io.dataset.Dataset`\n The :class:`~msl.io.dataset.Dataset` that was created or that already existed.\n \"\"\"\n name = '/' + name.strip('/')\n dataset_name = name if self.parent is None else self.name + name\n for dataset in self.datasets():\n if dataset.name == dataset_name:\n if read_only is not None:\n dataset.read_only = read_only\n if kwargs: # only add the kwargs that should be Metadata\n for kw in ['shape', 'dtype', 'buffer', 'offset', 'strides', 'order', 'data']:\n kwargs.pop(kw, None)\n dataset.add_metadata(**kwargs)\n return dataset\n return self.create_dataset(name, read_only=read_only, **kwargs)\n\n def add_dataset_logging(self, name, dataset_logging):\n \"\"\"Add a :class:`~msl.io.dataset_logging.DatasetLogging`.\n\n Automatically creates the ancestor :class:`Group`\\\\s if they do not exist.\n\n Parameters\n ----------\n name : :class:`str`\n The name of the new :class:`~msl.io.dataset_logging.DatasetLogging` to add.\n dataset_logging : :class:`~msl.io.dataset_logging.DatasetLogging`\n The :class:`~msl.io.dataset_logging.DatasetLogging` to add. The\n :class:`~msl.io.dataset_logging.DatasetLogging` and the\n :class:`~msl.io.metadata.Metadata` are copied.\n \"\"\"\n if not isinstance(dataset_logging, DatasetLogging):\n raise TypeError('Must pass in a DatasetLogging object, got {!r}'.format(dataset_logging))\n\n name = '/' + name.strip('/')\n self.create_dataset_logging(\n name,\n level=dataset_logging.level,\n attributes=dataset_logging.attributes,\n logger=dataset_logging.logger,\n date_fmt=dataset_logging.date_fmt,\n data=dataset_logging.data.copy(),\n **dataset_logging.metadata.copy()\n )\n\n def create_dataset_logging(self, name, level='INFO', attributes=None, logger=None, date_fmt=None, **kwargs):\n \"\"\"Create a :class:`~msl.io.dataset.Dataset` that handles :mod:`logging` records.\n\n Automatically creates the ancestor :class:`Group`\\\\s if they do not exist.\n\n Parameters\n ----------\n name : :class:`str`\n A name to associate with the :class:`~msl.io.dataset.Dataset`.\n level : :class:`int` or :class:`str`, optional\n The :ref:`logging level ` to use.\n attributes : :class:`list` or :class:`tuple` of :class:`str`, optional\n The :ref:`attribute names ` to include in the\n :class:`~msl.io.dataset.Dataset` for each :ref:`logging record `.\n If :data:`None` then uses ``asctime``, ``levelname``, ``name``, and ``message``.\n logger : :class:`~logging.Logger`, optional\n The :class:`~logging.Logger` that the :class:`~msl.io.dataset_logging.DatasetLogging` object\n will be added to. If :data:`None` then it is added to the ``root`` :class:`~logging.Logger`.\n date_fmt : :class:`str`, optional\n The :class:`~datetime.datetime` :ref:`format code `\n to use to represent the ``asctime`` :ref:`attribute ` in.\n If :data:`None` then uses the ISO 8601 format ``'%Y-%m-%dT%H:%M:%S.%f'``.\n **kwargs\n Additional keyword arguments are passed to :class:`~msl.io.dataset.Dataset`.\n The default behaviour is to append every :ref:`logging record `\n to the :class:`~msl.io.dataset.Dataset`. This guarantees that the size of the\n :class:`~msl.io.dataset.Dataset` is equal to the number of\n :ref:`logging records ` that were added to it. However, this behaviour\n can decrease the performance if many :ref:`logging records ` are\n added often because a copy of the data in the :class:`~msl.io.dataset.Dataset` is\n created for each :ref:`logging record ` that is added. You can improve\n the performance by specifying an initial size of the :class:`~msl.io.dataset.Dataset`\n by including a `shape` or a `size` keyword argument. This will also automatically\n create additional empty rows in the :class:`~msl.io.dataset.Dataset`, that is\n proportional to the size of the :class:`~msl.io.dataset.Dataset`, if the size of the\n :class:`~msl.io.dataset.Dataset` needs to be increased. If you do this then you will\n want to call :meth:`~msl.io.dataset_logging.DatasetLogging.remove_empty_rows` before\n writing :class:`~msl.io.dataset_logging.DatasetLogging` to a file or interacting\n with the data in :class:`~msl.io.dataset_logging.DatasetLogging` to remove the\n extra rows that were created.\n\n Returns\n -------\n :class:`~msl.io.dataset_logging.DatasetLogging`\n The :class:`~msl.io.dataset_logging.DatasetLogging` that was created.\n\n Examples\n --------\n >>> import logging\n >>> from msl.io import JSONWriter\n >>> logger = logging.getLogger('my_logger')\n >>> root = JSONWriter()\n >>> log_dset = root.create_dataset_logging('log')\n >>> logger.info('hi')\n >>> logger.error('cannot do that!')\n >>> log_dset.data\n array([(..., 'INFO', 'my_logger', 'hi'), (..., 'ERROR', 'my_logger', 'cannot do that!')],\n dtype=[('asctime', 'O'), ('levelname', 'O'), ('name', 'O'), ('message', 'O')])\n\n Get all ``ERROR`` :ref:`logging records `\n\n >>> errors = log_dset[log_dset['levelname'] == 'ERROR']\n >>> print(errors)\n [(..., 'ERROR', 'my_logger', 'cannot do that!')]\n\n Stop the :class:`~msl.io.dataset_logging.DatasetLogging` object\n from receiving :ref:`logging records `\n\n >>> log_dset.remove_handler()\n \"\"\"\n read_only, metadata = self._check(False, **kwargs)\n name, parent = self._create_ancestors(name, read_only)\n if attributes is None:\n # if the default attribute names are changed then update the `attributes`\n # description in the docstring of create_dataset_logging() and require_dataset_logging()\n attributes = ['asctime', 'levelname', 'name', 'message']\n if date_fmt is None:\n # if the default date_fmt is changed then update the `date_fmt`\n # description in the docstring of create_dataset_logging() and require_dataset_logging()\n date_fmt = '%Y-%m-%dT%H:%M:%S.%f'\n return DatasetLogging(name, parent, level=level, attributes=attributes,\n logger=logger, date_fmt=date_fmt, **metadata)\n\n def require_dataset_logging(self, name, level='INFO', attributes=None, logger=None, date_fmt=None, **kwargs):\n \"\"\"Require that a :class:`~msl.io.dataset.Dataset` exists for handling :mod:`logging` records.\n\n If the :class:`~msl.io.dataset_logging.DatasetLogging` exists then it will be returned\n if it does not exist then it is created.\n\n Automatically creates the ancestor :class:`Group`\\\\s if they do not exist.\n\n Parameters\n ----------\n name : :class:`str`\n A name to associate with the :class:`~msl.io.dataset.Dataset`.\n level : :class:`int` or :class:`str`, optional\n The :ref:`logging level ` to use.\n attributes : :class:`list` or :class:`tuple` of :class:`str`, optional\n The :ref:`attribute names ` to include in the\n :class:`~msl.io.dataset.Dataset` for each :ref:`logging record `.\n If the :class:`~msl.io.dataset.Dataset` exists and if `attributes`\n are specified, and they do not match those of the existing\n :class:`~msl.io.dataset.Dataset`, then a :exc:`ValueError` is raised.\n If :data:`None` and the :class:`~msl.io.dataset.Dataset` does not exist\n then uses ``asctime``, ``levelname``, ``name``, and ``message``.\n logger : :class:`~logging.Logger`, optional\n The :class:`~logging.Logger` that the :class:`~msl.io.dataset_logging.DatasetLogging` object\n will be added to. If :data:`None` then it is added to the ``root`` :class:`~logging.Logger`.\n date_fmt : :class:`str`, optional\n The :class:`~datetime.datetime` :ref:`format code `\n to use to represent the ``asctime`` :ref:`attribute ` in.\n If :data:`None` then uses the ISO 8601 format ``'%Y-%m-%dT%H:%M:%S.%f'``.\n **kwargs\n Additional keyword arguments are passed to :class:`~msl.io.dataset.Dataset`.\n The default behaviour is to append every :ref:`logging record `\n to the :class:`~msl.io.dataset.Dataset`. This guarantees that the size of the\n :class:`~msl.io.dataset.Dataset` is equal to the number of\n :ref:`logging records ` that were added to it. However, this behaviour\n can decrease the performance if many :ref:`logging records ` are\n added often because a copy of the data in the :class:`~msl.io.dataset.Dataset` is\n created for each :ref:`logging record ` that is added. You can improve\n the performance by specifying an initial size of the :class:`~msl.io.dataset.Dataset`\n by including a `shape` or a `size` keyword argument. This will also automatically\n create additional empty rows in the :class:`~msl.io.dataset.Dataset`, that is\n proportional to the size of the :class:`~msl.io.dataset.Dataset`, if the size of the\n :class:`~msl.io.dataset.Dataset` needs to be increased. If you do this then you will\n want to call :meth:`~msl.io.dataset_logging.DatasetLogging.remove_empty_rows` before\n writing :class:`~msl.io.dataset_logging.DatasetLogging` to a file or interacting\n with the data in :class:`~msl.io.dataset_logging.DatasetLogging` to remove the\n extra rows that were created.\n\n Returns\n -------\n :class:`~msl.io.dataset_logging.DatasetLogging`\n The :class:`~msl.io.dataset_logging.DatasetLogging` that was created or\n that already existed.\n \"\"\"\n name = '/' + name.strip('/')\n dataset_name = name if self.parent is None else self.name + name\n for dataset in self.datasets():\n if dataset.name == dataset_name:\n if ('logging_level' not in dataset.metadata) or \\\n ('logging_level_name' not in dataset.metadata) or \\\n ('logging_date_format' not in dataset.metadata):\n raise ValueError('The required Dataset was found but it is not used for logging')\n\n if attributes and (dataset.dtype.names != tuple(attributes)):\n raise ValueError('The attribute names of the existing '\n 'logging Dataset are {} which does not equal {}'\n .format(dataset.dtype.names, tuple(attributes)))\n\n if isinstance(dataset, DatasetLogging):\n return dataset\n\n # replace the existing Dataset with a new DatasetLogging object\n meta = dataset.metadata.copy()\n data = dataset.data.copy()\n\n # remove the existing Dataset from its descendants, itself and its ancestors\n groups = tuple(self.descendants()) + (self,) + tuple(self.ancestors())\n for group in groups:\n for dset in group.datasets():\n if dset is dataset:\n key = '/' + dset.name.lstrip(group.name)\n del group._mapping[key]\n\n # temporarily make this Group not in read-only mode\n original_read_only_mode = bool(self._read_only)\n self._read_only = False\n kwargs.update(meta)\n dset = self.create_dataset_logging(name, level=level, attributes=data.dtype.names,\n logger=logger, date_fmt=meta.logging_date_format,\n data=data, **kwargs)\n self._read_only = original_read_only_mode\n return dset\n\n return self.create_dataset_logging(name, level=level, attributes=attributes,\n logger=logger, date_fmt=date_fmt, **kwargs)\n\n def remove(self, name):\n \"\"\"Remove a :class:`Group` or a :class:`~msl.io.dataset.Dataset`.\n\n Parameters\n ----------\n name : :class:`str`\n The name of the :class:`Group` or :class:`~msl.io.dataset.Dataset` to remove.\n\n Returns\n -------\n :class:`Group`, :class:`~msl.io.dataset.Dataset` or :data:`None`\n The :class:`Group` or :class:`~msl.io.dataset.Dataset` that was\n removed or :data:`None` if there was no :class:`Group` or\n :class:`~msl.io.dataset.Dataset` with the specified `name`.\n \"\"\"\n name = '/' + name.strip('/')\n return self.pop(name, None)\n\n def _check(self, read_only, **kwargs):\n self._raise_if_read_only()\n kwargs.pop('parent', None)\n if read_only is None:\n return self._read_only, kwargs\n return read_only, kwargs\n\n def _create_ancestors(self, name, read_only):\n # automatically create the ancestor Groups if they do not already exist\n names = name.strip('/').split('/')\n parent = self\n for n in names[:-1]:\n if n not in parent:\n parent = Group(n, parent, read_only)\n else:\n parent = parent[n]\n return names[-1], parent\n","sub_path":"msl/io/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":27710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"439533235","text":"# %%\nimport tensorflow as tf \nimport numpy as np\nimport copy\nimport pandas as pd\nfrom sklearn.preprocessing import MultiLabelBinarizer\n\nmodel_name = 'graph_convolution_transformer'\na_partition_vocab_size = len(a_dict) + 1\nb_partition_vocab_size = len(b_dict) + 1\ntar_maxlen = copy.deepcopy(maxlen_b)\nkwargs = {\n 'model_name' : model_name,\n 'a_dict' : a_dict,\n 'b_dict' : b_dict, \n 'batch_size' : 64,\n 'num_layers' : 3,\n 'd_model' : 64,\n 'num_heads' : 4,\n 'd_ff' : 32,\n 'input_vocab_size' : a_partition_vocab_size,\n 'target_vocab_size' : b_partition_vocab_size,\n 'maximum_position_encoding' : tar_maxlen,\n 'dropout_rate' : 0.1,\n 'end_token_index' : b_dict[''],\n 'use_bgslp' : True,\n 'd_bgc' : 64,\n 'pooling' : 'mean',\n 'degree_factor' : 1e+8,\n 'num_hop' : 3,\n 'normalized_laplacian' : True\n}\n\n# %%\nmha = MultiHeadAttention(**kwargs)\nmask_generator = Mask_Generator(**kwargs)\n_, dec_padding_mask, _ = mask_generator(a_sequence[:30, :], b_sequence[:30, 1:])\n\nenc_emb = tf.keras.layers.Embedding(input_dim = a_partition_vocab_size, output_dim = 256)\ndec_emb = tf.keras.layers.Embedding(input_dim = b_partition_vocab_size, output_dim = 256)\nquery = dec_emb(b_sequence[:30, 1:])\nkey = enc_emb(a_sequence[:30, :])\nvalue = enc_emb(a_sequence[:30, :])\n\nmha(query, key, value, a_code[:30, :], b_code[:30, :], dec_padding_mask)\n\n# %%\natt_map = tf.Variable(np.random.randn(30, 54, 44), dtype = tf.float32)\nslp = SignlessLaplacianPropagation(**kwargs)\nslp(a_code[:30], b_code[:30], att_map)\n\n\n\n# %%\n# tt = list(map(lambda x: np.where(aa == x)[0], aa_unq))\n\nnode_batch = truncated_data['SMILES Category'][320:420]\ntf_var = tf.Variable(node_batch)\ntf_unq = tf.unique(tf_var)[0]\ndomain_indicator = tf.strings.substr(tf_unq, pos = 0, len = 1)[0].numpy()\ncode_indicator = tf.strings.regex_replace(tf_unq.numpy(), domain_indicator, '')\ncode_num = tf.strings.to_number(code_indicator, out_type = tf.int32)\n\n# %%\na = np.random.randint(0, 2, (7, 5))\nb = np.random.randn(5, 2, 2)\nc = tf.reshape(tf.reduce_sum(a, axis = 1), shape = (-1, 1))\n\nprint('a :', a)\nprint('c :', c)\n\nd = a * 1 / tf.reshape(tf.reduce_sum(a, axis = 1), shape = (-1, 1))\nprint('d :', d)\ntf.tensordot(d, b, axes = [[1], [0]])","sub_path":"drug-translation/temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"}